void Receive(ChangeOperationalStateMessage message) {// Result can be returned to requestor. TracerHelper.TraceEntry(); // Make sure to compare only the *original senders* as the rest is not guaranteed to be the same, // since remote status synchronization source is fed to class from outside. if (message.IsRequest == false) { // This is a notification if (message.TransportInfo.OriginalSenderId.Equals(_remoteStatusSynchronizationSource.OriginalSenderId)) { // Message received from status synch source, change state to synchronize. if (StatusSynchronizationEnabled) { TracerHelper.Trace(this.GetType().Name + " is following its status synchronization source to new state [" + message.OperationalState.ToString() + "]."); ChangeOperationalState(message.OperationalState); } else { TracerHelper.Trace(this.GetType().Name + " is not following its status synchronization source to new state because synchronization is disabled."); } } else { SystemMonitor.Warning("Stat change notification received, but not from status source. Ignored."); } } else { TracerHelper.Trace(this.GetType().Name + " is following request from " + message.TransportInfo.CurrentTransportInfo.Value.SenderID.Value.Id.Name + " to " + message.OperationalState); bool result = OnChangeOperationalStateRequest(message.OperationalState); SystemMonitor.CheckWarning(result, "Component [" + this.Name + "] has not changed its operational state upon request."); } }
OrdersInformationUpdateResponseMessage Receive(GetOrdersInformationMessage message) { TracerHelper.TraceEntry(); List <OrderInfo> result = new List <OrderInfo>(); lock (this) { foreach (string id in message.OrderTickets) { if (_orders.ContainsKey(id) && _orders[id].HasValue) { result.Add(_orders[id].Value); } else { _pendingOrdersInformations.Add(id); } } } TracerHelper.TraceExit(); OrdersInformationUpdateResponseMessage response = new OrdersInformationUpdateResponseMessage(_accountInfo, result.ToArray(), true); if (message.RequestResponse) { return(response); } SendToSubscribers(response); return(null); }
ResponseMessage Receive(SubscribeToOperationalStateChangesMessage message) { bool result = false; lock (this) { if (message.Subscribe) {// Subscribe. TracerHelper.TraceEntry("Subscribing - " + message.TransportInfo.OriginalSenderId.Value.Id.Name); if (_operationStateChangeSubscribers.Contains(message.TransportInfo) == false) { _operationStateChangeSubscribers.Add(message.TransportInfo); result = true; } // Send an initial notification. this.SendResponding(message.TransportInfo, new ChangeOperationalStateMessage(this.OperationalState, false)); } else {// Unsubscribe. TracerHelper.TraceEntry("Unsubscribing - " + message.TransportInfo.OriginalSenderId.Value.Id.Name); result = _operationStateChangeSubscribers.Remove(message.TransportInfo); } } if (message.RequestResponse) { return(new ResponseMessage(result)); } else { return(null); } }
/// <summary> /// /// </summary> public void Quotes(string symbol, int operationId, double ask, double bid, double open, double close, double low, double high, double volume, double time) { TracerHelper.TraceEntry(); CombinedDataSubscriptionInformation session = GetDataSession(symbol); if (session == null) { SystemMonitor.Error("Failed to find symbol session [" + symbol + "], quotes not sent."); return; } try { QuoteUpdateMessage message = new QuoteUpdateMessage(session.SessionInformation.Info, new Quote((decimal)ask, (decimal)bid, (decimal)open, (decimal)close, (decimal)high, (decimal)low, (decimal)volume, GeneralHelper.GenerateDateTimeSecondsFrom1970((long)time)), true); SendToDataSubscribers(session, message, null); } catch (Exception ex) {// Make sure we handle any possible unexpected exceptions, as otherwise they bring the // entire package (MT4 included) down with a bad error. SystemMonitor.Error(ex.Message); } }
/// <summary> /// UI thread. /// Update user interface based on the underlying information. /// </summary> public void UpdateUI() { TracerHelper.TraceEntry(); listViewSessions.SuspendLayout(); //if (_manager != null) //{ // if (_manager.OperationalState != OperationalStateEnum.Operational) // { // listViewSessions.ForeColor = SystemColors.GrayText; // } // int totalCount = 0; // lock (_manager) // {// Since we do a lenghtly iteration make sure full lock is applied. // foreach (string group in _manager.Groups) // { // totalCount += _manager.GetGroupSessionsCount(group); // } // } // listViewSessions.VirtualListSize = totalCount; //} listViewSessions.ResumeLayout(); }
/// <summary> /// /// </summary> /// <param name="entity"></param> public void AddExecutionEntity(ExecutionEntity entity) { TracerHelper.TraceEntry(); lock (this) { if (_pendingEntities.Count > _maxPendingExecutionItems) { TracerHelper.TraceError("Too many pending entities in system. Some older entities are being dropped."); if ((DateTime.Now - _maxPendingItemsWarningShownTime) > _warningsTimeSpan) { _maxPendingItemsWarningShownTime = DateTime.Now; SystemMonitor.Error("Too many pending entities in system. Some older entities are being dropped."); } // Loose the oldest entity in line. _timeOutMonitor.RemoveEntity(_pendingEntities[0]); _pendingEntities.RemoveAt(0); } _timeOutMonitor.AddEntity(entity); _pendingEntities.Add(entity); } // Continue execution chain. UpdatePendingExecution(); }
/// <summary> /// Will unsubscribe to previous one. /// </summary> protected bool SetRemoteStatusSynchronizationSource(TransportInfo sourceTransportInfo) { lock (this) { if (_remoteStatusSynchronizationSource != null) { SubscribeToOperationalStateChangesMessage message = new SubscribeToOperationalStateChangesMessage(false); message.RequestResponse = false; SendResponding(_remoteStatusSynchronizationSource, message); } _remoteStatusSynchronizationSource = sourceTransportInfo; } bool result = true; if (sourceTransportInfo != null) { ResponseMessage response = SendAndReceiveResponding <ResponseMessage>(sourceTransportInfo, new SubscribeToOperationalStateChangesMessage(true)); result = response != null && response.OperationResult; } TracerHelper.TraceEntry(this.GetType().Name + ", Remote synchronization source " + sourceTransportInfo.OriginalSenderId.Value.Id.Name + " assinged - " + result.ToString()); return(result); }
/// <summary> /// OperationId is not mandatory - but is should be there when the update was requested by a special recepient. /// </summary> public void TradingValuesUpdate(string symbol, int operationId, double time, int period, int availableBarsCount, Int64[] times, decimal[] opens, decimal[] closes, decimal[] highs, decimal[] lows, decimal[] volumes) { TracerHelper.TraceEntry(); CombinedDataSubscriptionInformation session = GetDataSession(symbol); if (session == null) { SystemMonitor.Error("Failed to find symbol session [" + symbol + "], quotes not sent."); return; } try { // History update. TimeSpan periodValue = TimeSpan.FromMinutes(period); DataHistoryUpdate update = new DataHistoryUpdate(periodValue, GenerateDataBars(periodValue, times, opens, closes, highs, lows, volumes)); update.AvailableHistorySize = availableBarsCount; DataHistoryUpdateMessage message = new DataHistoryUpdateMessage(session.SessionInformation.Info, update, true); SendToDataSubscribers(session, null, message); } catch (Exception ex) {// Make sure we handle any possible unexpected exceptions, as otherwise they bring the // entire package (MT4 included) down with a bad error. SystemMonitor.Error(ex.Message); } TracerHelper.TraceExit(); }
/// <summary> /// /// </summary> public bool ClearTable <ItemType>() where ItemType : class, IDBPersistent { TracerHelper.TraceEntry(typeof(ItemType).Name); string tableName = _tablesTypeNames[typeof(ItemType)]; _clearMutex.WaitOne(); try { using (SQLiteConnection connection = GenerateConnection()) { using (SQLiteCommand command = new SQLiteCommand(connection)) { connection.Open(); command.CommandText = "DELETE FROM " + tableName; int result = command.ExecuteNonQuery(); } } } finally { _clearMutex.ReleaseMutex(); } TracerHelper.TraceExit(); return(true); }
/// <summary> /// Name of the platform must be unique. /// </summary> public Platform(string name) : base(name, false) { TracerHelper.TraceEntry(); Arbiter.Arbiter arbiter = new Arbiter.Arbiter("Platform"); //TracerHelper.TracingEnabled = false; arbiter.AddClient(this); }
/// <summary> /// Change default TransportClient behaviour. /// Handle a requestMessage received from local Arbiter and send down the pipe. /// </summary> /// <param name="requestMessage"></param> protected override void OnMessageReceived(TransportMessage message) { TracerHelper.TraceEntry(); if (message.TransportInfo == null) { SystemMonitor.Error("Transport message stack can not be null."); } if (message.TransportInfo == null || message.TransportInfo.TransportInfoCount == 0 || message.TransportInfo.CurrentTransportInfo.Value.ReceiverID == null || message.TransportInfo.CurrentTransportInfo.Value.ReceiverID.HasValue == false || message.TransportInfo.CurrentTransportInfo.Value.ReceiverID.Value.Equals(this.SubscriptionClientID) == false) {// This requestMessage was sent to me, not to one of the clients on the server. SystemMonitor.Error("Error. Send messages to server-client instances."); return; } // We shall now establish the tag defining which will be the client connection receiving the requestMessage (or all). // by default send to all. string tagID = "*"; if (message.IsRequest) {// Request. if (message.TransportInfo.ForwardTransportInfoCount != 0) { if (message.TransportInfo.CurrentForwardTransportInfoAddress.HasValue) {// Has value - take it into account, if no value is present, just use the "*" pop, // and use the rest of the AdditionalForwardTransportSessionStack. tagID = message.TransportInfo.CurrentForwardTransportInfoAddress.Value.SessionTag; } // Pop in both cases - if it is null or it is value. message.TransportInfo.PopForwardTransportInfo(); } } else {// Responce. // Clear the transporting information from the last node to here. message.TransportInfo.PopTransportInfo(); // Now this is the additional marking in the case with the server - the marking of the PipeChannel. SystemMonitor.CheckError(message.TransportInfo.TransportInfoCount > 0 && message.TransportInfo.CurrentTransportInfo.Value.SenderID.Value.Id.Name == "PipeChannelID"); // Responce requestMessage, read and pop out the channel ID entry . tagID = message.TransportInfo.PopTransportInfo().Value.SenderID.Value.SessionTag; } MessageContainer container = new MessageContainer(message); TracerHelper.Trace("[" + message.GetType().Name + "], tag [" + tagID + "] length [" + container.MessageStreamLength + "]"); GeneralHelper.FireAndForget(delegate() { _transportServer.SendMessageContainer(tagID, container); }); }
/// <summary> /// /// </summary> /// <param name="message"></param> protected void SendToSubscribers(TransportMessage message) { TracerHelper.TraceEntry(message.GetType().Name + " to " + _subscribers.Count + " subscribers"); lock (this) { foreach (KeyValuePair <ArbiterClientId, TransportInfo> pair in _subscribers) { SendResponding(pair.Value, message); } } }
/// <summary> /// /// </summary> /// <param name="message"></param> void SendToSubscriber(TransportMessage message) { TracerHelper.TraceEntry(message.GetType().Name); lock (this) { if (_subscriberTransportMessageInfo != null) { this.SendResponding(_subscriberTransportMessageInfo, message); } } TracerHelper.TraceExit(); }
void UpdateValues() { TracerHelper.TraceEntry(); lock (this) { foreach (DataBar data in _data) { _minVolume = Math.Min(_minVolume, (float)data.Volume); _maxVolume = Math.Max(_maxVolume, (float)data.Volume); } } RaiseSeriesValuesUpdated(true); }
private void Stop() { TracerHelper.TraceEntry(_tracer); if (CurrentSession.DataProvider != null && CurrentSession.DataProvider.Quotes != null) { CurrentSession.DataProvider.Quotes.QuoteUpdateEvent -= new QuoteProviderUpdateDelegate(Quote_QuoteUpdateEvent); } if (CurrentSession.DataProvider != null && CurrentSession.DataProvider.DataBars != null) { CurrentSession.DataProvider.DataBars.DataBarHistoryUpdateEvent -= new DataBarHistoryUpdateDelegate(DataBarHistory_DataBarHistoryUpdateEvent); } }
/// <summary> /// Needs to be on the same connection the insert was in. /// </summary> /// <returns></returns> long GetLastInsertRowId(SQLiteConnection connection, string tableName) { TracerHelper.TraceEntry(tableName); long value; using (SQLiteCommand command = new SQLiteCommand(connection)) { command.CommandText = "SELECT last_insert_rowid() FROM " + tableName; value = (long)command.ExecuteScalar(); } TracerHelper.TraceExit(); return(value); }
// >> public void ErrorOccured(int operationResult, string errorMessage) { TracerHelper.TraceEntry(errorMessage); try { //SessionErrorOccuredMessage message = new SessionErrorOccuredMessage(_sessionInformation.Info, operationResult, errorMessage); //SendToSubscriber(message); } catch (Exception ex) {// Make sure we handle any possible unexpected exceptions, as otherwise they bring the // entire package (MT4 included) down with a bad error. SystemMonitor.Error(ex.Message); } }
/// <summary> /// /// </summary> void Update() { TracerHelper.TraceEntry(); if (_isUpdating == true) { return; } _isUpdating = true; List <NewsEvent> events = new List <NewsEvent>(); WebRequest webRequest = WebRequest.Create(_xmlAddress); webRequest.Timeout = 5000; WebResponse response = webRequest.GetResponse(); if (response.ContentLength > 0) { try { XmlDocument document = new XmlDocument(); document.Load(response.GetResponseStream()); XmlNode weeklyEvents = document.ChildNodes[1]; foreach (XmlNode eventNode in weeklyEvents.ChildNodes) { events.Add(ParseEventXml(eventNode)); } } catch (Exception ex) { SystemMonitor.Error("Failed to obtain XML stream [" + ex.Message + "]."); } } lock (this) { _events.Clear(); _events.AddRange(events); } UpdateVisibleEvents(); ChartSeries.RaiseSeriesValuesUpdated(true); _isUpdating = false; }
/// <summary> /// /// </summary> protected virtual void UpdatePendingExecution() { ExecutionEntity entity; while (_pendingEntities != null && (entity = PopNextExecutionEntity()) != null) { TracerHelper.TraceEntry(" pending [" + _pendingEntities.Count + "] started executioners [" + _threadPool.ActiveRunningThreadsCount.ToString() + "]"); lock (this) { _threadPool.Queue(new GeneralHelper.GenericDelegate <ExecutionEntity>(worker_DoWork), entity); } } }
/// <summary> /// /// </summary> public long Count <ItemType>(MatchExpression matchExpression) where ItemType : class, IDBPersistent { TracerHelper.TraceEntry(typeof(ItemType).Name); string tableName = _tablesTypeNames[typeof(ItemType)]; StringBuilder commandText = new StringBuilder(); commandText.Append("SELECT count(*) FROM " + tableName); if (matchExpression != null && matchExpression.ClauseCount > 0) { commandText.Append(" WHERE "); } _countMutex.WaitOne(); SQLiteCommand command; long result = 0; try { using (SQLiteConnection connection = GenerateConnection()) { using (command = new SQLiteCommand(connection)) { if (matchExpression != null) { matchExpression.SetupCommandParameters(command, commandText); } command.CommandText = commandText.ToString(); connection.Open(); result = (long)command.ExecuteScalar(); } } } finally { _countMutex.ReleaseMutex(); } TracerHelper.TraceExit(); return(result); }
/// <summary> /// Un initialize manager, notify subsribers, clear resources. /// </summary> public void UnInitialize() { TracerHelper.TraceEntry(); if (_subscriberTransportMessageInfo != null) {// Send update to subscriber to let him now we are closing down. this.SendResponding(_subscriberTransportMessageInfo, new SubscriptionTerminatedMessage()); _subscriberTransportMessageInfo = null; } if (_integrationServer != null && Arbiter != null) { Arbiter.RemoveClient(_integrationServer); } // Give time to the termination message to arrive. System.Threading.Thread.Sleep(1000); }
/// <summary> /// Set operationContextSessionID to "*" to mark all clients. /// </summary> /// <param name="operationContextSessionID"></param> /// <param name="messageContainer"></param> public void SendMessageContainer(string operationContextSessionID, MessageContainer messageContainer) { TracerHelper.TraceEntry("[" + messageContainer.MessageStreamLength + "]"); if (messageContainer.MessageStreamLength > MaximumAllowedMessageSize) { TracerHelper.TraceError("Message too bid. Operation failed."); return; //throw new Exception("Arbiter::MessageContainerTransportServer::MessageContainer requestMessage is too big. Message will not be sent."); } Dictionary <IMessageContainerTransport, OperationContext> clientsContexts; lock (_contextManager) { clientsContexts = new Dictionary <IMessageContainerTransport, OperationContext>(_contextManager.ClientsContextsUnsafe); } List <IMessageContainerTransport> badInterfaces = new List <IMessageContainerTransport>(); foreach (IMessageContainerTransport clientCallback in clientsContexts.Keys) { // "*" indicates send to all clients if (operationContextSessionID == "*" || clientsContexts[clientCallback].SessionId == operationContextSessionID) { try { TracerHelper.Trace("clientCallback [" + operationContextSessionID + "]"); clientCallback.ReceiveMessageContainer(messageContainer); TracerHelper.Trace("clientCallback [" + operationContextSessionID + "] invoked"); } catch (Exception ex) { TracerHelper.TraceError("Failed to invoke client interface [" + ex.ToString() + "]"); badInterfaces.Add(clientCallback); } } } ProcessBadInterfaces(badInterfaces); TracerHelper.TraceExit(); }
/// <summary> /// /// </summary> public bool Delete <ItemType>(IEnumerable <ItemType> items) where ItemType : class, IDBPersistent { TracerHelper.TraceEntry(typeof(ItemType).Name); string tableName = _tablesTypeNames[typeof(ItemType)]; _deleteMutex.WaitOne(); try { using (SQLiteConnection connection = GenerateConnection()) { using (SQLiteCommand command = new SQLiteCommand(connection)) { connection.Open(); using (SQLiteTransaction transaction = connection.BeginTransaction()) { SQLiteParameter whereIdParam = new SQLiteParameter("@ParamId"); command.Parameters.Add(whereIdParam); command.CommandText = "DELETE FROM " + tableName + " WHERE Id = " + whereIdParam.ParameterName; foreach (IDBPersistent persistent in items) { SystemMonitor.CheckThrow(persistent.Id.HasValue, "Deleting an item with no ID already assigned."); whereIdParam.Value = persistent.Id; int result = command.ExecuteNonQuery(); } transaction.Commit(); } } } } finally { _deleteMutex.ReleaseMutex(); } TracerHelper.TraceExit(); return(true); }
// >> public void AccountInformation(int operationID, decimal accountBalance, decimal accountCredit, string accountCompany, string accountCurrency, decimal accountEquity, decimal accountFreeMargin, decimal accountLeverage, decimal accountMargin, string accountName, int accountNumber, decimal accountProfit, string accountServer, bool operationResult, string operationResultMessage) { TracerHelper.TraceEntry(); try { lock (this) { _accountInfo.Balance = Math.Round(accountBalance, 4); _accountInfo.Credit = Math.Round(accountCredit, 4); _accountInfo.Company = accountCompany; _accountInfo.BaseCurrency = new Symbol(accountCurrency); _accountInfo.Equity = Math.Round(accountEquity, 4); _accountInfo.FreeMargin = Math.Round(accountFreeMargin, 4); _accountInfo.Leverage = Math.Round(accountLeverage, 4); _accountInfo.Margin = Math.Round(accountMargin, 4); _accountInfo.Name = accountName; _accountInfo.Id = accountNumber.ToString(); _accountInfo.Profit = Math.Round(accountProfit, 4); _accountInfo.Server = accountServer; } AccountInformationUpdateMessage message = new AccountInformationUpdateMessage(_accountInfo, operationResult); message.OperationResultMessage = operationResultMessage; if (base.GetOperationById(operationID) != null) { base.CompleteOperation(operationID, message); } else {// This is an operationless update. SendToSubscribers(message); } } catch (Exception ex) { SystemMonitor.Error(ex.Message); } }
protected ResponseMessage Receive(RequestMessage message) { TracerHelper.TraceEntry(message.GetType().Name); try { OperationInformation info = new OperationInformation(); info.Request = message; if (message.PerformSynchronous) { ResponseMessage result; if (_stub.PerformOperation <ResponseMessage>(info, null, true, out result)) {// Operation performed successfully. TracerHelper.Trace("Operation [" + message.GetType().Name + "] performed successfully."); return(result); } else { TracerHelper.TraceOperationError("Operation [" + message.GetType().Name + "] timed out."); } } else { _stub.PlaceOperation(info, true); if (message.RequestResponse) { return(new ResponseMessage(true)); } return(null); } } catch (Exception ex) {// Make sure we handle any possible unexpected exceptions, as otherwise they bring the // entire package (MT4 included) down with a bad error. SystemMonitor.Error(ex.Message); } return(null); }
private void Start() { TracerHelper.TraceEntry(_tracer); if (_started == false) { _started = true; OnStart(); if (CurrentSession.DataProvider != null && CurrentSession.DataProvider.Quotes != null) { CurrentSession.DataProvider.Quotes.QuoteUpdateEvent += new QuoteProviderUpdateDelegate(Quote_QuoteUpdateEvent); } if (CurrentSession.DataProvider != null && CurrentSession.DataProvider.DataBars != null) { CurrentSession.DataProvider.DataBars.DataBarHistoryUpdateEvent += new DataBarHistoryUpdateDelegate(DataBarHistory_DataBarHistoryUpdateEvent); } } }
ResponceMessage Receive(SubscribeMessage message) { TracerHelper.TraceEntry(); lock (this) { if (_subscriberTransportMessageInfo != null) {// Notify existing subscriber he lost control. this.SendResponding(_subscriberTransportMessageInfo, new SubscriptionTerminatedMessage()); _subscriberTransportMessageInfo = null; } _subscriberTransportMessageInfo = message.TransportInfo.Clone(); } if (message.RequestResponce) { return(new ResponceMessage(true)); } return(null); }
/// <summary> /// Send container over to the other side. /// </summary> /// <param name="messageContainer"></param> /// <returns></returns> public virtual bool SendMessageContainer(MessageContainer messageContainer) { TracerHelper.TraceEntry("sending [" + messageContainer.MessageStreamLength + "], sessionID[" + this.ConnectionSessionID + "]"); SystemMonitor.CheckThrow(messageContainer.MessageStreamLength <= MessageContainerTransportServer.MaximumAllowedMessageSize, "MessageContainer message is too big. Message will not be sent."); if (_connectingEvent.WaitOne(_defaultConnectionTimeOut) == false) { SystemMonitor.OperationError("Failed to send message due to initialization timeout.", TracerItem.PriorityEnum.Medium); return(false); } try { IMessageContainerTransport messageInterface; lock (this) { if (_proxyServerInterface == null) { TracerHelper.TraceError("Failed to send to server, interface not created."); return(false); } messageInterface = _proxyServerInterface; } messageInterface.ReceiveMessageContainer(messageContainer); lock (this) { _lastServerCall = DateTime.Now; } } catch (Exception exception) { TracerHelper.TraceError("Failed to send to server, reason [" + exception.Message + "]."); return(false); } return(true); }
public bool UnInitialize() { TracerHelper.TraceEntry(); SortedList <int, List <PlatformComponent> > componentsByLevel; lock (this) { componentsByLevel = GetComponentsByLevel(_components.Values); } // Un initialize higher level components first. // Make sure component uninit is outside of locks, to evade dead locks. for (int i = 0; i < componentsByLevel.Keys.Count; i++) { int level = componentsByLevel.Keys[i]; foreach (PlatformComponent component in componentsByLevel[level]) { UnInitializeComponent(component); } } lock (this) { // Store additional. _serializationData.Clear(); _serializationData.AddValue("diagnosticsMode", _settings.DiagnosticsMode); _serializationData.AddValue("uiSerializationInfo", _uiSerializationInfo); _serializationData.AddValue("componentSpecificSerializationInfo", _componentSpecificSerializationInfo); PersistenceHelper.UpdateToDB <Platform>(this, null); _components.Clear(); this.Arbiter.Dispose(); } return(true); }
public bool UnInitialize() { TracerHelper.TraceEntry(); lock (this) { if (_serviceHost != null && _serviceHost.State != CommunicationState.Closed) { _serviceHost.BeginClose(TimeSpan.FromSeconds(2), null, null); _serviceHost.Abort(); _serviceHost.Close(); _serviceHost = null; } if (_reconectionTimer != null) { _reconectionTimer.Dispose(); _reconectionTimer = null; } } return(true); }