コード例 #1
0
        /// <summary>
        /// Change the component operational state.
        /// </summary>
        /// <param name="operationalState"></param>
        protected void ChangeOperationalState(OperationalStateEnum operationalState)
        {
            OperationalStateEnum previousState;

            lock (this)
            {
                if (operationalState == _operationalState)
                {
                    return;
                }

                previousState = _operationalState;
            }

            TracerHelper.Trace(this.GetType().Name + " is now " + operationalState.ToString() + " has [" + _operationStateChangeSubscribers.Count + "] subscribers.");

            _operationalState = operationalState;
            if (OperationalStateChangedEvent != null)
            {
                OperationalStateChangedEvent(this, previousState);
            }

            // Send to monitoring subscribers.
            lock (this)
            {
                foreach (TransportInfo info in _operationStateChangeSubscribers)
                {
                    TracerHelper.Trace("Sending operational state [" + operationalState.ToString() + "] to [" + info.OriginalSenderId.Value.Id.Print() + "].");
                    this.SendResponding(info, new ChangeOperationalStateMessage(this.OperationalState, false));
                }
            }
        }
コード例 #2
0
        // for the double (and int) values, 0 means do not change, -1 means set to "not assigned"
        // << Result format : int& orderTicket, int& operationID, double& stopLoss, double& takeProfit, double& targetOpenPrice, int& expiration
        public string RequestModifyOrder()
        {
            try
            {
                int operationId;
                ModifyOrderMessage message = base.GetPendingMessage <ModifyOrderMessage>(true, out operationId);

                if (message == null)
                {
                    return(string.Empty);
                }

                string result =
                    message.Symbol.Name.ToString() + SeparatorSymbol +
                    message.OrderId.ToString() + SeparatorSymbol +
                    operationId.ToString() + SeparatorSymbol +
                    TranslateModificationValue(message.StopLoss).ToString(GeneralHelper.UniversalNumberFormatInfo) + SeparatorSymbol +
                    TranslateModificationValue(message.TakeProfit).ToString(GeneralHelper.UniversalNumberFormatInfo) + SeparatorSymbol +
                    TranslateModificationValue(message.TargetOpenPrice).ToString(GeneralHelper.UniversalNumberFormatInfo) + SeparatorSymbol +
                    TranslateModificationValue(message.Expiration).ToString();

                TracerHelper.Trace(result);

                return(result);
            }
            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(string.Empty);
        }
コード例 #3
0
        /// <summary>
        /// Prepare the object for operation. Access to this allows externals to use the 2
        /// step component registration process.
        /// Called to bring up a component for operation. Does not add the component
        /// permanently to the platform.
        /// </summary>
        public bool InitializeComponent(PlatformComponent component)
        {
            TracerHelper.Trace(component.Name);

            try
            {
                if (component.IsInitialized == false)
                {
                    Arbiter.AddClient(component);
                    // This allows the component to persist while initializing.
                    component.PersistenceDataUpdatedEvent += new GeneralHelper.GenericDelegate <IDBPersistent>(HandleComponentPersistenceDataUpdatedEvent);
                }

                if (component.IsInitialized || component.Initialize(this))
                {
                    return(true);
                }
            }
            catch (Exception ex)
            {
                SystemMonitor.Error(string.Format("Exception occured during initializing component [{0}, {1}]", component.Name, ex.Message));
            }

            // Failed to initialize component.
            component.PersistenceDataUpdatedEvent -= new GeneralHelper.GenericDelegate <IDBPersistent>(HandleComponentPersistenceDataUpdatedEvent);
            Arbiter.RemoveClient(component);
            return(false);
        }
コード例 #4
0
        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.");
            }
        }
コード例 #5
0
        protected virtual DataSubscriptionResponseMessage Receive(DataSubscriptionRequestMessage message)
        {
            if (message.TransportInfo.OriginalSenderId.HasValue == false)
            {
                SystemMonitor.Error("Received a message with no original sender. Dropped.");
                return(null);
            }

            if (message.SessionInfo.IsEmtpy)
            {// General (un)subscription requestMessage, not specific to a sessionInformation.
                if (message.Subscribe)
                {
                    SystemMonitor.OperationError("Unexpected combination of empty session and subscribe request, ignored.");
                }
                else
                {// Unsubscribe to each that has a orderInfo for this original sender.
                    lock (this)
                    {
                        foreach (CombinedDataSubscriptionInformation combined in _dataSessions.Values)
                        {
                            if (combined.FullUnsubscribe(message.TransportInfo.OriginalSenderId.Value) == false)
                            {
                                SystemMonitor.OperationError("Failed to unsubscribe [" + message.TransportInfo.OriginalSenderId.Value.Id.Name + "].");
                            }
                        }
                    }
                }
            }
            else
            {
                lock (this)
                {
                    if (_dataSessions.ContainsKey(message.SessionInfo.Symbol) == false ||
                        _dataSessions[message.SessionInfo.Symbol].SessionInformation.Info.Equals(message.SessionInfo) == false)
                    {
                        SystemMonitor.Warning("Subsribe request for non existing session.");
                        return(new DataSubscriptionResponseMessage(message.SessionInfo, false));
                    }

                    CombinedDataSubscriptionInformation combined = _dataSessions[message.SessionInfo.Symbol];
                    if (combined != null)
                    {
                        TracerHelper.Trace("Subscribing... " + message.TransportInfo.OriginalSenderId.Value.Id.Name);
                        combined.HandleRequest(message.TransportInfo, message.Subscribe, message.Information);
                    }
                    else
                    {
                        SystemMonitor.OperationError("Combined subscription info not found.");
                    }
                }
            }

            // Finalizing / responding section.
            if (message.RequestResponse)
            {
                return(new DataSubscriptionResponseMessage(message.SessionInfo, true));
            }

            return(null);
        }
コード例 #6
0
        public bool InitializeIntegrationSession(string symbol,
                                                 decimal modePoint, decimal modeDigits, decimal modeSpread, decimal modeStopLevel, decimal modeLotSize, decimal modeTickValue,
                                                 decimal modeTickSize, decimal modeSwapLong, decimal modeSwapShort, decimal modeStarting, decimal modeExpiration,
                                                 decimal modeTradeAllowed, decimal modeMinLot, decimal modeLotStep, decimal modeMaxLot, decimal modeSwapType,
                                                 decimal modeProfitCalcMode, decimal modeMarginCalcMode, decimal modeMarginInit, decimal modeMarginMaintenance,
                                                 decimal modeMarginHedged, decimal modeMarginRequired, decimal modeFreezeLevel)
        {
            TracerHelper.Trace(symbol);
            CombinedDataSubscriptionInformation session = GetDataSession(symbol);

            if (session == null)
            {
                DataSessionInfo sessionInfo = new DataSessionInfo(Guid.NewGuid(), symbol,
                                                                  CreateSymbol(symbol), modeLotSize, (int)modeDigits);

                RuntimeDataSessionInformation runtimeSession = new RuntimeDataSessionInformation(sessionInfo);

                session = new CombinedDataSubscriptionInformation(runtimeSession);

                lock (this)
                {
                    _dataSessions.Add(sessionInfo.Symbol, session);
                }
            }

            return(true);
        }
コード例 #7
0
        // >>
        public void OrderModified(string symbol, int operationID, int orderTicket, int orderNewTicket, bool operationResult, string operationResultMessage)
        {
            TracerHelper.Trace(symbol);
            try
            {
                OperationInformation operation = base.GetOperationById(operationID);

                if (operation != null)
                {
                    ModifyOrderResponseMessage message;
                    lock (this)
                    {
                        message = new ModifyOrderResponseMessage(_accountInfo, orderTicket.ToString(), orderNewTicket.ToString(), operationResult);
                        message.OperationResultMessage = operationResultMessage;
                    }

                    base.CompleteOperation(operationID, message);
                }

                lock (this)
                {
                    _pendingOrdersInformations.Add(orderTicket.ToString());
                }
            }
            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);
            }
        }
コード例 #8
0
        /// <summary>
        /// This may contain a few operations on active orders, in order to match the rule "no opposing active orders"
        /// </summary>
        public virtual string ExecuteMarketBalanced(int volumeModification, decimal?desiredPrice, decimal?slippage, TimeSpan timeOut,
                                                    out PositionExecutionInfo executionInfo, out string operationResultMessage)
        {
            executionInfo = PositionExecutionInfo.Empty;

            ISourceOrderExecution provider = _orderProvider;

            if (provider == null || provider.DefaultAccount == null)
            {
                operationResultMessage = "Position not properly initialized.";
                return(string.Empty);
            }

            // Trace pre-execution info.
            string traceMessage = string.Format("Submit Volume Modification [{0}] Price [{1}] Slippage [{2}] TimeOut [{3}]",
                                                volumeModification.ToString(), GeneralHelper.ToString(desiredPrice), GeneralHelper.ToString(slippage), timeOut.ToString());

            traceMessage += GenerateConditionsInfo();

            TracerHelper.Trace(_tracer, traceMessage, TracerItem.PriorityEnum.High);

            if (OnExecuteMarketBalanced(provider, volumeModification, desiredPrice, slippage, timeOut, out executionInfo, out operationResultMessage))
            {
                return(Guid.NewGuid().ToString());
            }

            return(string.Empty);
        }
コード例 #9
0
        /// <summary>
        /// Places and tries to execute a market order synchronously. Since it might be a modification of an
        /// existing active order, no specific order Id is returned - instead a bool indicating operation result.
        /// </summary>
        /// <param name="manipulateExistingOrders">[where applicable] Is the operation allowed to close a matching existing order, or should we always open a new one. This is suitable for Active orders brokers, that dissallow hedged orders at the same time.</param>
        public string ExecuteMarket(OrderTypeEnum orderType, int volume, decimal?price, decimal?slippage,
                                    decimal?takeProfit, decimal?stopLoss, TimeSpan timeOut, out PositionExecutionInfo executionInfo,
                                    out string operationResultMessage)
        {
            operationResultMessage = string.Empty;
            executionInfo          = PositionExecutionInfo.Empty;

            ISourceOrderExecution provider = _orderProvider;

            if (provider == null || provider.DefaultAccount == null)
            {
                operationResultMessage = "Position not properly initialized.";
                return(string.Empty);
            }

            // Trace pre-execution info.
            string traceMessage = string.Format("Submit Type[{0}] Volume [{1}] Price [{2}] Slippage [{3}] TP [{4}] SL [{5}] TimeOut [{6}]", orderType.ToString(),
                                                volume.ToString(), GeneralHelper.ToString(price), GeneralHelper.ToString(slippage), GeneralHelper.ToString(takeProfit),
                                                GeneralHelper.ToString(stopLoss), timeOut.ToString());

            traceMessage += GenerateConditionsInfo();

            TracerHelper.Trace(_tracer, traceMessage, TracerItem.PriorityEnum.High);

            _isProcessing = true;

            string result = OnExecuteMarket(provider, orderType, volume, price, slippage, takeProfit, stopLoss, timeOut,
                                            out executionInfo, out operationResultMessage);

            SystemMonitor.CheckError(result == executionInfo.ExecutionId, operationResultMessage);

            _isProcessing = false;

            return(result);
        }
コード例 #10
0
ファイル: Arbiter.cs プロジェクト: yyl-20020115/OpenForexNew
        /// <summary>
        /// Will start a shoutcast mode conversation, the sender sending to all.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="requestMessage"></param>
        /// <param name="timeout"></param>
        /// <returns></returns>
        public ConversationMultiPoint CreateConversation(ArbiterClientId senderID, Message message, TimeSpan timeout)
        {
            if (message is TransportMessage)
            {
                SystemMonitor.CheckError(((TransportMessage)message).TransportInfo.CurrentTransportInfo != null);
                TracerHelper.Trace("sender[" + senderID.Id.Name + "], message [" + message.GetType().Name + "] [" + ((TransportMessage)message).TransportInfo.TransportInfoCount + "]");
            }
            else
            {
                TracerHelper.Trace("sender[" + senderID.Id.Name + "], message [" + message.GetType().Name + "]");
            }

            if (GetClientByID(senderID, false) == null)
            {
                SystemMonitor.Error("Creating conversation by not present sender/owner.");
                return(null);
            }

            ConversationMultiPoint conversation = new ConversationMultiPoint(_executionManager, message, senderID, GatherMessageClients(message, senderID), timeout);

            if (_isDisposed)
            {// Possible to get disposed while operating here.
                return(null);
            }

            lock (_timeOutMonitor)
            {
                _timeOutMonitor.AddEntity(conversation);
            }
            return(conversation);
        }
コード例 #11
0
        /// <summary>
        /// Full submit of orders with a full set of parameters.
        /// </summary>
        /// <returns>The Id of the placement operation, allowing to trace its further execution or Empty if placement fails.</returns>
        public string Submit(OrderTypeEnum orderType, int volume, decimal?price, decimal?slippage,
                             decimal?takeProfit, decimal?stopLoss, out string operationResultMessage)
        {
            ISourceOrderExecution provider = OrderExecutionProvider;

            if (provider == null || provider.DefaultAccount == null)
            {
                operationResultMessage = "Position not properly initialized.";
                return(string.Empty);
            }

            if (price.HasValue == false)
            {
                price = _price;
            }

            // Trace pre-execution info.
            string traceMessage = string.Format("Submit Type[{0}] Volume [{1}] Price [{2}] Slippage [{3}] TP [{4}] SL [{5}]", orderType.ToString(),
                                                volume.ToString(), GeneralHelper.ToString(price), GeneralHelper.ToString(slippage), GeneralHelper.ToString(takeProfit), GeneralHelper.ToString(stopLoss));

            traceMessage += GenerateConditionsInfo();

            TracerHelper.Trace(_tracer, traceMessage, TracerItem.PriorityEnum.High);

            return(OnSubmit(provider, orderType, volume, price, slippage, takeProfit, stopLoss, out operationResultMessage));
        }
コード例 #12
0
        /// <summary>
        /// Local execution. Expert to be executed locally, within the platform process
        /// space and on the platforms arbiter.
        /// </summary>
        protected ExpertHost(string name, Type expertType)
            : base(name, false)
        {
            TracerHelper.Trace(this.Name);
            _expertType = expertType;

            base.DefaultTimeOut = TimeSpan.FromSeconds(10);
        }
コード例 #13
0
        /// <summary>
        /// Constructor.
        /// </summary>
        public PlatformIndicator(string name, bool?isTradeable, bool?isScaledToQuotes, string[] resultSetNames)
            : base(name, isTradeable, isScaledToQuotes, resultSetNames)
        {
            TracerHelper.Trace(this.Name);

            _chartSeries = CreateChartSeries();
            // Needs immediate initialization since it will be added to chart.
            _chartSeries.Initialize(this);
        }
コード例 #14
0
        // << Result format : int& orderTicket, int& operationID, double& minVolume, double& price, int& slippage
        public string RequestCloseOrder()
        {
            try
            {
                int operationId;
                CloseOrderVolumeMessage message = base.GetPendingMessage <CloseOrderVolumeMessage>(true, out operationId);

                if (message == null)
                {
                    return(string.Empty);
                }

                // Convert slippage to points.
                int slippage = ConvertSlippage(message.Symbol, message.Slippage);

                // Process price.
                if (message.Price.HasValue == false)
                {
                    message.Price = 0;
                }

                // Process minVolume.
                CombinedDataSubscriptionInformation session = base.GetDataSession(message.Symbol);
                if (session == null)
                {
                    SystemMonitor.Error("Failed to establish symbol [" + message.Symbol.Name + "] session.");
                    if (message.PerformSynchronous)
                    {
                        base.CompleteOperation(operationId, new ResponseMessage(false, "Failed to establish symbol session."));
                    }
                    return(string.Empty);
                }

                decimal volumeDecreasal = ConvertVolume(session.SessionInformation.Info.LotSize, (int)message.VolumeDecreasal);

                string result =
                    message.OrderId.ToString() + SeparatorSymbol +
                    operationId.ToString() + SeparatorSymbol +
                    volumeDecreasal.ToString(GeneralHelper.UniversalNumberFormatInfo) + SeparatorSymbol +
                    message.Price.Value.ToString(GeneralHelper.UniversalNumberFormatInfo) + SeparatorSymbol +
                    slippage.ToString();

                TracerHelper.Trace(result);

                return(result);
            }
            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(string.Empty);
        }
コード例 #15
0
        /// <summary>
        ///
        /// </summary>
        protected bool DoRegisterComponent(PlatformComponent component, bool isInitial)
        {
            TracerHelper.Trace(component.Name);

            if (CanAcceptComponent(component.GetType()) == false)
            {
                SystemMonitor.Error("Failed to add component instance since only one instance of this type allowed.");
                return(false);
            }

            if (component.SubscriptionClientID.Id.Guid == Guid.Empty)
            {
                SystemMonitor.Error("Component [" + component.GetType().Name + "] has no valid Guid Id assigned.");
                return(false);
            }

            if (InitializeComponent(component) == false)
            {
                return(false);
            }

            lock (this)
            {
                if (_components.ContainsValue(component))
                {
                    SystemMonitor.OperationWarning("Component [" + component.GetType().Name + "] already added.");
                    return(true);
                }

                if (_components.ContainsKey(component.SubscriptionClientID.Id))
                {
                    SystemMonitor.Error("Component with this Id [" + component.SubscriptionClientID.Id.Name + ", " + component.SubscriptionClientID.Id.ToString() + "] already added.");
                    return(false);
                }

                _components.Add(component.SubscriptionClientID.Id, component);
            }

            component.OperationalStateChangedEvent += new OperationalStateChangedDelegate(component_OperationalStatusChangedEvent);

            if (component.IsPersistableToDB && PersistenceHelper.IsPersisted <PlatformComponent>(component) == false)
            {// New component not present in DB, persist.
                if (PersistenceHelper.Insert <PlatformComponent>(component, new KeyValuePair <string, object>("PlatformId", this.Id)) == false)
                {
                    SystemMonitor.Error("Failed to insert component [" + component.Name + "] to DB.");
                }
            }

            if (ActiveComponentAddedEvent != null)
            {
                ActiveComponentAddedEvent(component, isInitial);
            }

            return(true);
        }
コード例 #16
0
        // >>
        public void OrderClosed(string symbol, int operationID, int orderTicket, int orderNewTicket, decimal closingPrice, int orderCloseTime, bool operationResult, string operationResultMessage)
        {
            TracerHelper.Trace(symbol);

            try
            {
                OperationInformation operation = base.GetOperationById(operationID);

                string orderNewTicketString = orderNewTicket.ToString();
                if (orderNewTicket < 1)
                {// Anything below 1 (0, -1 etc) is considered empty.
                    orderNewTicketString = string.Empty;
                }

                DateTime?closeTime = GeneralHelper.GenerateDateTimeSecondsFrom1970(orderCloseTime);

                if (closeTime.HasValue == false)
                {
                    if (operation != null)
                    {
                        base.CompleteOperation(operationID, new ResponseMessage(false, "Failed to convert order close time."));
                    }
                    SystemMonitor.Error("Failed to convert order close time.");
                    return;
                }

                if (operation != null)
                {
                    CloseOrderVolumeResponseMessage message;
                    lock (this)
                    {
                        message = new CloseOrderVolumeResponseMessage(_accountInfo, orderTicket.ToString(), orderNewTicketString, closingPrice, closeTime.Value, operationResult);
                        message.OperationResultMessage = operationResultMessage;
                    }

                    base.CompleteOperation(operationID, message);
                }
                else
                {
                    SystemMonitor.Error("Failed to finish order close operation as expected.");
                }

                // Do an update of this order.
                lock (this)
                {
                    _pendingOrdersInformations.Add(orderTicket.ToString());
                }
            }
            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);
            }
        }
コード例 #17
0
        /// <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); });
        }
コード例 #18
0
        /// <summary>
        ///
        /// </summary>
        public string SubmitOrder(AccountInfo account, Order order, Symbol symbol, OrderTypeEnum orderType,
                                  int volume, decimal?allowedSlippage, decimal?desiredPrice, decimal?takeProfit, decimal?stopLoss,
                                  string comment, out string operationResultMessage)
        {
            TracerHelper.Trace(this.Name);

            if (OperationalState != OperationalStateEnum.Operational)
            {
                operationResultMessage = "Attempted operations on non operational order executioner.";
                SystemMonitor.Error(operationResultMessage);
                return(null);
            }

            if (account.IsEmpty ||
                string.IsNullOrEmpty(account.Id) ||
                string.IsNullOrEmpty(account.Name))
            {
                operationResultMessage = "Account info on order execution provider not properly assigned.";
                return(null);
            }

            allowedSlippage = ProcessSlippage(allowedSlippage);

            SubmitOrderMessage request = new SubmitOrderMessage(account,
                                                                symbol, orderType, volume, desiredPrice, allowedSlippage, takeProfit, stopLoss, comment);

            request.RequestResponse    = true;
            request.PerformSynchronous = true;

            ResponseMessage response = this.SendAndReceiveResponding <ResponseMessage>
                                           (SourceTransportInfo, request);

            if (response == null)
            {// Time out.
                operationResultMessage = "Failed receive result for order request. In this scenario inconsistency may occur!";
                SystemMonitor.Error(operationResultMessage);
                return(null);
            }

            if (response.OperationResult == false)
            {
                operationResultMessage = response.OperationResultMessage;
                return(null);
            }

            SubmitOrderResponseMessage responseMessage = (SubmitOrderResponseMessage)response;

            operationResultMessage = "Order submited.";

            //RaiseOrderUpdateEvent(account, order.Info, Order.UpdateTypeEnum.Submitted);

            return(responseMessage.OrderId);
        }
コード例 #19
0
 /// <summary>
 /// Follow synchrnozation source status.
 /// </summary>
 protected virtual void _statusSynchronizationSource_OperationalStatusChangedEvent(IOperational parameter1, OperationalStateEnum parameter2)
 {
     if (StatusSynchronizationEnabled)
     {
         TracerHelper.Trace(this.GetType().Name + " is following its source " + parameter1.GetType().Name + " to state " + parameter1.OperationalState.ToString());
         this.ChangeOperationalState(parameter1.OperationalState);
     }
     else
     {
         TracerHelper.Trace(this.GetType().Name + " is not following its source " + parameter1.GetType().Name + " to new state because synchronization is disabled.");
     }
 }
コード例 #20
0
        // >>
        public void AllOrders(int operationID, string symbol, int[] openMagicIDs, int[] openTickets,
                              int[] historicalMagicIDs, int[] historicalTickets, bool operationResult)
        {
            TracerHelper.Trace(symbol);

            try
            {
                lock (this)
                {
                    List <string> knownOrdersIds = GeneralHelper.EnumerableToList <string>(_orders.Keys);

                    for (int i = 0; i < openTickets.Length; i++)
                    {
                        string orderId = openTickets[i].ToString();
                        knownOrdersIds.Remove(orderId);

                        if (_orders.ContainsKey(orderId) == false ||
                            _orders[orderId].HasValue == false ||
                            _orders[orderId].Value.State != OrderStateEnum.Executed)
                        {
                            _orders[orderId] = null;
                            _pendingOrdersInformations.Add(orderId);
                        }
                    }

                    for (int i = 0; i < historicalTickets.Length; i++)
                    {
                        string orderId = historicalTickets[i].ToString();
                        knownOrdersIds.Remove(orderId);

                        if (_orders.ContainsKey(orderId) == false ||
                            _orders[orderId].HasValue == false ||
                            _orders[orderId].Value.State != OrderStateEnum.Closed)
                        {
                            _orders[orderId] = null;
                            _pendingOrdersInformations.Add(orderId);
                        }
                    }

                    foreach (string id in knownOrdersIds)
                    {// Make sure to remove non existing ones.
                        _orders.Remove(id);
                    }
                }
            }
            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);
            }
        }
コード例 #21
0
        /// <summary>
        ///
        /// </summary>
        public bool DecreaseOrderVolume(AccountInfo account, Order order, decimal volumeDecreasal, decimal?allowedSlippage,
                                        decimal?desiredPrice, out decimal decreasalPrice, out string modifiedId, out string operationResultMessage)
        {
            TracerHelper.Trace(this.Name);
            modifiedId     = order.Id;
            decreasalPrice = decimal.MinValue;

            if (OperationalState != OperationalStateEnum.Operational)
            {
                operationResultMessage = "Attempted operations on non operational order executioner.";
                SystemMonitor.Error(operationResultMessage);
                return(false);
            }

            allowedSlippage = ProcessSlippage(allowedSlippage);

            CloseOrderVolumeMessage message = new CloseOrderVolumeMessage(account, order.Symbol, order.Id,
                                                                          order.Tag, volumeDecreasal, desiredPrice, allowedSlippage);

            message.PerformSynchronous = true;

            ResponseMessage response = this.SendAndReceiveResponding <ResponseMessage>
                                           (SourceTransportInfo, message);

            if (response == null)
            {// Time out.
                operationResultMessage = "Failed receive result for order request. In this scenario inconsistency may occur!";
                SystemMonitor.Error(operationResultMessage);
                return(false);
            }

            if (response.OperationResult == false)
            {
                operationResultMessage = response.OperationResultMessage;
                return(false);
            }

            CloseOrderVolumeResponseMessage responseMessage = (CloseOrderVolumeResponseMessage)response;

            operationResultMessage = "Order volume decreased.";
            decreasalPrice         = responseMessage.ClosingPrice;

            // When modified, order changes its Id.
            modifiedId = responseMessage.OrderModifiedId;

            RaiseOrderUpdateEvent(account, responseMessage.OrderId, order.Info, ActiveOrder.UpdateTypeEnum.VolumeChanged);

            return(true);
        }
コード例 #22
0
        /// <summary>
        /// Helper.
        /// </summary>
        bool DoCloseOrder(AccountInfo account, Order order, decimal?allowedSlippage, decimal?desiredPrice, out decimal closingPrice,
                          out DateTime closingTime, out string modifiedId, out string operationResultMessage)
        {
            TracerHelper.Trace(this.Name);

            closingPrice = decimal.MinValue;
            closingTime  = DateTime.MinValue;
            modifiedId   = order.Id;

            if (OperationalState != OperationalStateEnum.Operational)
            {
                operationResultMessage = "Attempted operations on non operational order executioner.";
                SystemMonitor.Error(operationResultMessage);
                return(false);
            }

            allowedSlippage = ProcessSlippage(allowedSlippage);

            CloseOrderVolumeMessage message = new CloseOrderVolumeMessage(account, order.Symbol, order.Id,
                                                                          order.Tag, desiredPrice, allowedSlippage);

            message.PerformSynchronous = true;

            ResponseMessage response = this.SendAndReceiveResponding <ResponseMessage>
                                           (SourceTransportInfo, message);

            if (response == null)
            {// Time out.
                operationResultMessage = "Failed receive result for order request. In this scenario inconsistency may occur!";
                SystemMonitor.Error(operationResultMessage);
                return(false);
            }

            if (response.OperationResult)
            {
                CloseOrderVolumeResponseMessage responseMessage = (CloseOrderVolumeResponseMessage)response;
                operationResultMessage = "Order closed.";
                closingPrice           = responseMessage.ClosingPrice;
                closingTime            = responseMessage.ClosingDateTime;

                SystemMonitor.CheckError(order.Id == responseMessage.OrderId.ToString(), "Order id mismatch [" + order.Id + " / " + responseMessage.OrderId + "].");

                modifiedId = responseMessage.OrderModifiedId.ToString();
                return(true);
            }

            operationResultMessage = response.OperationResultMessage;
            return(false);
        }
コード例 #23
0
        /// <summary>
        /// Main drawing routine.
        /// </summary>
        public override void Draw(ChartPane managingPane, GraphicsWrapper g, int unitsUnification,
                                  RectangleF clippingRectangle, float itemWidth, float itemMargin)
        {
            TracerHelper.Trace(ReflectionHelper.GetCallingMethod(2).Name);

            if (Visible == false)
            {
                return;
            }

            lock (this)
            {
                base.Draw(g, _data.AsReadOnly(), unitsUnification, clippingRectangle, itemWidth, itemMargin, _maxVolume, null);
            }
        }
コード例 #24
0
        public string ClientRegister()
        {// A client has called - register it.
            lock (_contextManager)
            {
                _contextManager.AddContext(OperationContext.Current);
            }

            TracerHelper.Trace("[" + OperationContext.Current.SessionId + "]");
            if (ClientConnected != null)
            {
                ClientConnected(OperationContext.Current.SessionId);
            }
            IMessageContainerTransport callbackInterface = OperationContext.Current.GetCallbackChannel <IMessageContainerTransport>();

            return(OperationContext.Current.SessionId);
        }
コード例 #25
0
        /// <summary>
        /// Does not include results.
        /// </summary>
        /// <returns></returns>
        public override PlatformIndicator OnSimpleClone()
        {
            TracerHelper.Trace((this.DataProvider != null).ToString());

            GenericTALibIndicator newIndicator = CreateInstance(_methodInfo, _lookbackMethodInfo, Description, Tradeable, ScaledToQuotes);

            newIndicator._inputDefaultArrayParameters = new List <ParameterInfo>(_inputDefaultArrayParameters);
            newIndicator._intputParameters            = new List <ParameterInfo>(_intputParameters);
            newIndicator._outputArraysParameters      = new List <ParameterInfo>(_outputArraysParameters);
            newIndicator._parameters = (IndicatorParameters)_parameters.Clone();

            newIndicator._realInputArraySource  = _realInputArraySource;
            newIndicator._real1InputArraySource = _real1InputArraySource;

            return(newIndicator);
        }
コード例 #26
0
        /// <summary>
        /// Clear and disconnect all failed interfaces.
        /// </summary>
        /// <param name="badInterfaces"></param>
        protected void ProcessBadInterfaces(List <IMessageContainerTransport> badInterfaces)
        {
            foreach (IMessageContainerTransport interfaceContainer in badInterfaces)
            {
                TracerHelper.Trace("Removing bad interface...");
                try
                {
                    string           sessionID;
                    OperationContext context;
                    lock (_contextManager)
                    {
                        if (_contextManager.ClientsContextsUnsafe.ContainsKey(interfaceContainer) == false)
                        {// This interface already removed.
                            continue;
                        }

                        context   = _contextManager.ClientsContextsUnsafe[interfaceContainer];
                        sessionID = context.SessionId;
                        _contextManager.RemoveContext(interfaceContainer);
                    }

                    if (sessionID == null)
                    {
                        sessionID = string.Empty;
                    }

                    TracerHelper.Trace("Interface removed..." + sessionID);

                    if (ClientDisConnected != null)
                    {
                        ClientDisConnected(sessionID);
                    }

                    if (context.Channel.State == CommunicationState.Opened ||
                        context.Channel.State == CommunicationState.Opening)
                    {
                        TracerHelper.Trace("Closing client channel [" + context.Channel.SessionId + "].");
                        context.Channel.Close(TimeSpan.FromSeconds(2));
                        context.Channel.Abort();
                    }
                }
                catch (Exception ex)
                {
                    TracerHelper.Trace("Error encountered while clearing bad interface [" + ex.Message + "].");
                }
            }
        }
コード例 #27
0
        public bool BeginAccountInfoUpdate(AccountInfo accountInfo)
        {
            TracerHelper.Trace(this.Name);

            if (SourceTransportInfo == null)
            {
                SystemMonitor.OperationWarning("Failed to obtain account information - SourceTransportInfo not assigned.");
                return(false);
            }

            this.SendResponding(SourceTransportInfo, new AccountInformationMessage(accountInfo)
            {
                RequestResponse = false
            });

            return(true);
        }
コード例 #28
0
        /// <summary>
        /// Receive container from the server.
        /// </summary>
        /// <param name="messageContainer"></param>
        public virtual void ReceiveMessageContainer(MessageContainer messageContainer)
        {
            //_connectionSessionID = OperationContext.Current.SessionId;
            if (MessageContainerReceivedEvent != null)
            {
                TracerHelper.Trace("receiving [" + messageContainer.MessageStreamLength + "], sessionID[" + this.ConnectionSessionID + "]");
                MessageContainerReceivedEvent(messageContainer);
            }
            else
            {
                SystemMonitor.OperationError("container missed [" + messageContainer.MessageStreamLength + "], sessionID[" + this.ConnectionSessionID + "]");
            }

            lock (this)
            {
                _lastServerCall = DateTime.Now;
            }
        }
コード例 #29
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="messageContainer"></param>
 public void ReceiveMessageContainer(MessageContainer messageContainer)
 {
     TracerHelper.Trace("[" + messageContainer.MessageStreamLength + "], clientCallback[" + OperationContext.Current.SessionId + "]");
     if (MessageContainerReceivedEvent != null)
     {
         string sessionId = OperationContext.Current.SessionId;
         GeneralHelper.FireAndForget(delegate()
         {
             try
             {
                 MessageContainerReceivedEvent(sessionId, messageContainer);
             }
             catch (Exception ex)
             {
                 TracerHelper.TraceError(ex.Message);
             }
         });
     }
 }
コード例 #30
0
        /// <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();
        }