Пример #1
0
        // >>
        public void OrderInformation(int orderTicket, int operationID, string orderSymbol, int orderType, decimal volume,
                                     decimal inputOpenPrice, decimal inputClosePrice, decimal inputOrderStopLoss, decimal inputOrderTakeProfit,
                                     decimal currentProfit, decimal orderSwap, int inputOrderPlatformOpenTime,
                                     int inputOrderPlatformCloseTime, int inputOrderExpiration, decimal orderCommission,
                                     string orderComment, int orderCustomID, bool operationResult, string operationResultMessage)
        {
            TracerHelper.TraceEntry();

            try
            {
                #region Preprocess Data

                decimal?openPrice              = Convert(inputOpenPrice);
                decimal?closePrice             = Convert(inputClosePrice);
                decimal?orderStopLoss          = Convert(inputOrderStopLoss);
                decimal?orderTakeProfit        = Convert(inputOrderTakeProfit);
                int?    orderPlatformOpenTime  = Convert(inputOrderPlatformOpenTime);
                int?    orderPlatformCloseTime = Convert(inputOrderPlatformCloseTime);
                int?    orderExpiration        = Convert(inputOrderExpiration);

                // Perform dataDelivery fixes to convert to proper cases.
                bool isOpen = orderPlatformCloseTime.HasValue == false || orderPlatformCloseTime == 0;

                OrderStateEnum orderState = OrderStateEnum.Unknown;
                // According to documentataion this is the way to establish if order is closed, see here : http://docs.mql4.com/trading/OrderSelect
                if (isOpen)
                {
                    if (CommonFinancial.OrderInfo.TypeIsDelayed((OrderTypeEnum)orderType) == false &&
                        orderPlatformOpenTime > 0)
                    {
                        orderState = OrderStateEnum.Executed;
                    }
                    else
                    {
                        orderState = OrderStateEnum.Submitted;
                    }
                }
                else
                {
                    orderState = OrderStateEnum.Closed;
                }

                if (orderState == OrderStateEnum.Executed)
                {// Since the integration might report close price for opened orders, at the current closing price.
                    closePrice = null;
                }

                DateTime?openTime       = GeneralHelper.GenerateDateTimeSecondsFrom1970(orderPlatformOpenTime);
                DateTime?closeTime      = GeneralHelper.GenerateDateTimeSecondsFrom1970(orderPlatformCloseTime);
                DateTime?expirationTime = GeneralHelper.GenerateDateTimeSecondsFrom1970(orderExpiration);

                CombinedDataSubscriptionInformation sessionSubscriptionInfo = GetDataSession(orderSymbol);

                if (sessionSubscriptionInfo == null)
                {
                    SystemMonitor.Error("Corresponding symbol [" + orderSymbol + "] session info not found.");
                    return;
                }

                #endregion

                bool      isNewlyAcquired  = false;
                OrderInfo?orderInformation = null;

                lock (this)
                {
                    if (orderTicket > -1)
                    {// Store call information for later use.
                        TracerHelper.TraceEntry("Storing information.");

                        orderInformation = new OrderInfo(
                            orderTicket.ToString(), sessionSubscriptionInfo.SessionInformation.Info.Symbol, ConvertOrderType(orderType), orderState,
                            ConvertVolume(sessionSubscriptionInfo.SessionInformation.Info.LotSize, volume), openPrice, closePrice,
                            orderStopLoss, orderTakeProfit, currentProfit,
                            orderSwap, openTime, closeTime, openTime,
                            expirationTime, orderCommission, orderComment, orderCustomID.ToString());

                        isNewlyAcquired = _orders.ContainsKey(orderTicket.ToString()) == false || _orders[orderTicket.ToString()].HasValue == false;
                        _orders[orderTicket.ToString()] = orderInformation;
                    }
                    else
                    {// This is the flush call - send all stored to user.
                        SystemMonitor.NotImplementedWarning("Case not implemented.");

                        //    //TracerHelper.TraceEntry("Sending information.");
                        //    //OrdersInformationResponceMessage message = new OrdersInformationResponceMessage(_sessionInformation.Info, operationID, _pendingInformations.ToArray(), operationResult);
                        //    //message.OperationResultMessage = operationResultMessage;
                        //    //SendToSubscriber(message);
                        //    //// Clear for new operations.
                        //    //_totalOrderInformationsOperationID = -1;
                        //    //_pendingInformations.Clear();
                    }
                }

                //if (isNewlyAcquired)
                {// Send a notification to subscribers, an order orderInfo was acquired.
                    OrdersInformationUpdateResponceMessage message = new OrdersInformationUpdateResponceMessage(_accountInfo,
                                                                                                                new OrderInfo[] { orderInformation.Value }, true);

                    SendToSubscribers(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);
            }
        }
Пример #2
0
        /// <summary>
        /// The initialization of a platform consumes 2 main dataDelivery sources.
        /// The settings is used for primary, startup information (like where
        /// is the persistence DB file etc.) and the information inside the
        /// persistence is than on used to create components etc.
        /// </summary>
        public bool Initialize(PlatformSettings platformSettings)
        {
            TracerHelper.TraceEntry();

            SystemMonitor.CheckThrow(_settings == null, "Platform already initialized.");

            lock (this)
            {
                _settings = platformSettings;
                if (_persistenceHelper == null)
                {
                    _persistenceHelper = CreatePlatformPersistenceHelper(platformSettings);
                }
            }

            if (_persistenceHelper == null)
            {
                return(false);
            }

            LoadModules(_settings);

            if (PersistenceHelper.Count <Platform>(new MatchExpression("Name", this.Name)) == 0)
            {// This is a new platform.
                lock (this)
                {
                    _guid = Guid.NewGuid();
                }

                if (PersistenceHelper.Insert <Platform>(this, null) == false)
                {
                    SystemMonitor.Error("Failed to persist new platform [" + this.Name + "]");
                    return(false);
                }
            }
            else
            {// This is existing.
                // Now try to load self from persistance storage.
                bool selectionResult = PersistenceHelper.SelectScalar <Platform>(this, new MatchExpression("Name", this.Name));

                if (selectionResult == false)
                {// Failed to load self from DB.
                    return(false);
                }
            }

            lock (this)
            {
                if (_serializationData.ContainsValue("diagnosticsMode"))
                {
                    _settings.DiagnosticsMode = _serializationData.GetBoolean("diagnosticsMode");
                }

                if (_serializationData.ContainsValue("uiSerializationInfo"))
                {
                    // The main serialization dataDelivery stores the UI orderInfo.
                    _uiSerializationInfo = _serializationData.GetValue <SerializationInfoEx>("uiSerializationInfo");
                }

                if (_serializationData.ContainsValue("componentSpecificSerializationInfo"))
                {
                    // The main serialization dataDelivery stores the UI orderInfo.
                    _componentSpecificSerializationInfo = _serializationData.GetValue <SerializationInfoEx>("componentSpecificSerializationInfo");
                }
            }

            //_server = new Arbiter.TransportIntegrationServer(_platformUri);
            //Arbiter.AddClient(_server);

            GeneralHelper.FireAndForget(delegate()
            {// LoadFromFile components.
             // Registering of components is better done outside the lock,
             // since components may launch requests to platform at initializations.

                _isLoading = true;

                // Components are stored in the PlatformComponents database, they are being serialized and the entire object is
                // persisted in the DB, as well as the type information for it and a reference to the platform instance it belongs to.
                List <long> failedSerializationsIds = new List <long>();
                List <PlatformComponent> components = PersistenceHelper.SelectSerializedType <PlatformComponent>(
                    new MatchExpression("PlatformId", this.Id), "Data", null, failedSerializationsIds);

                SortedList <int, List <PlatformComponent> > componentsByLevel = GetComponentsByLevel(components);

                GatherMandatoryComponents(componentsByLevel);

                foreach (int level in componentsByLevel.Keys)
                {// Register lower level components first.
                    foreach (PlatformComponent component in componentsByLevel[level])
                    {
                        if (DoRegisterComponent(component, true) == false &&
                            component.Id.HasValue && ComponentDeserializationFailedEvent != null)
                        {
                            ComponentDeserializationFailedEvent(component.Id.Value, component.GetType().Name);
                        }
                    }
                }

                // Handle failed deserializations.
                foreach (int id in failedSerializationsIds)
                {
                    string typeName = "Unknown";

                    try
                    {// Extract the type of this entry.
                        List <object[]> result = PersistenceHelper.SelectColumns <PlatformComponent>(
                            new MatchExpression("Id", id), new string[] { "Type" }, 1);

                        Type type = Type.GetType(result[0][0].ToString());

                        if (type != null)
                        {
                            typeName = type.Name;
                        }
                    }
                    catch (Exception ex)
                    {
                        SystemMonitor.Error("Failed to extract type information [" + ex.Message + "].");
                    }

                    if (ComponentDeserializationFailedEvent != null)
                    {
                        ComponentDeserializationFailedEvent(id, typeName);
                    }
                }

                _isLoading = false;
            });

            return(true);
        }
Пример #3
0
 /// <summary>
 /// Is this order type delayed, otherwise it is for instant execution.
 /// </summary>
 /// <param name="orderType"></param>
 /// <returns></returns>
 public static bool TypeIsDelayed(OrderTypeEnum orderType)
 {
     SystemMonitor.CheckWarning(orderType != OrderTypeEnum.UNKNOWN, "Order type not established yet.");
     return(orderType != OrderTypeEnum.BUY_MARKET &&
            orderType != OrderTypeEnum.SELL_MARKET);
 }
Пример #4
0
 static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
 {
     SystemMonitor.Error(e.Exception.Message);
 }
 public override void ReceiveConversationTimedOut(Conversation conversation)
 {
     SystemMonitor.NotExpectedCritical();
 }
Пример #6
0
        /// <summary>
        ///
        /// </summary>
        void worker_DoWork(ExecutionEntity entity)
        {
            lock (this)
            {
                if (_clientsRunningExecutioners.ContainsKey(entity.ReceiverID) == false)
                {
                    _clientsRunningExecutioners[entity.ReceiverID] = 1;
                }
                else
                {
                    _clientsRunningExecutioners[entity.ReceiverID] = _clientsRunningExecutioners[entity.ReceiverID] + 1;
                }
            }

            TracerHelper.Trace(" Enlisted entity at [" + entity.ReceiverID.Id.Name + "] entity starting [" + entity.Message.GetType().Name + ", " +
                               entity.ReceiverID.Id.Name + "], total count [" + _threadPool.ActiveRunningThreadsCount.ToString() + "]");

            DateTime startTime = DateTime.Now;

            // Notify executor we are running this entity.
            entity.Conversation.EntityExecutionStarted(entity);

            try
            {
                IArbiterClient receiver = _arbiter.GetClientByID(entity.ReceiverID);
                if (receiver != null)
                {
                    SystemMonitor.CheckError(((TransportMessage)entity.Message).TransportInfo.TransportInfoCount > 0);

                    // Do the entity.
                    if (entity is ExecutionEntityWithReply)
                    {
                        ExecutionEntityWithReply replyEntity = (ExecutionEntityWithReply)entity;
                        SystemMonitor.CheckError(replyEntity.ReplyMessage == null && replyEntity.ReplyTimeOut == TimeSpan.Zero);
                        receiver.ReceiveExecutionWithReply(replyEntity);
                    }
                    else
                    {
                        SystemMonitor.CheckError(entity.GetType() == typeof(ExecutionEntity));
                        receiver.ReceiveExecution(entity);
                    }
                    entity.Conversation.EntityExecutionFinished(entity);
                }
            }
            catch (TargetInvocationException exception)
            {
                if (exception.InnerException is ThreadInterruptedException)
                {// ThreadInterruptedException's are OK, since we use them to awake sleeping threads when closing down.
                    SystemMonitor.Report(exception.ToString() + "[" + exception.InnerException.Message + "]");
                    entity.Conversation.EntityExecutionFailed(entity, exception);
                }
                else
                {
                    SystemMonitor.OperationError(exception.ToString() + "[" + exception.InnerException.Message + "]");
                    entity.Conversation.EntityExecutionFailed(entity, exception);
                }
            }
            catch (ThreadInterruptedException exception)
            {
                // ThreadInterruptedException's are OK, since we use them to awake sleeping threads when closing down.
                SystemMonitor.Report(exception.ToString() + "[" + exception.Message + "]");
                entity.Conversation.EntityExecutionFailed(entity, exception);
            }
            catch (Exception exception)
            {
                SystemMonitor.Error(exception.ToString());
                entity.Conversation.EntityExecutionFailed(entity, exception);
            }
            finally
            {
                entity.Die();
            }

            lock (this)
            {
                if (_clientsRunningExecutioners.ContainsKey(entity.ReceiverID))
                {
                    int newClientsValue = _clientsRunningExecutioners[entity.ReceiverID] - 1;
                    if (newClientsValue <= 0)
                    {
                        _clientsRunningExecutioners.Remove(entity.ReceiverID);
                    }
                    else
                    {
                        _clientsRunningExecutioners[entity.ReceiverID] = newClientsValue;
                    }
                }
                else
                {
                    if (IsDisposed == false)
                    {
                        SystemMonitor.Error("ClientsRunningExecutioners not properly maintained.");
                    }
                }

                //TracerHelper.TraceExit("entity finished for [" + (DateTime.Now - startTime).Milliseconds + "]ms [" + entity.Message.GetType().Name + ", " + entity.ReceiverID.Id.Name + "], total count [" + _threadPool.ActiveRunningThreadsCount.ToString() + "]");
            }

            // Continue execution chain.
            UpdatePendingExecution();
        }
Пример #7
0
        /// <summary>
        /// Request bar dataDelivery from entry.
        /// </summary>
        public bool RequestDataHistoryUpdate(DataSessionInfo sessionInfo, DataHistoryRequest request, bool waitResult)
        {
            DataStoreEntry entry = DataStore.Instance.GetEntryBySessionInfo(sessionInfo);

            if (this.OperationalState != OperationalStateEnum.Operational ||
                entry == null)
            {
                SystemMonitor.OperationError("Data history request received while not operational, or invalid session requrested.");
                return(false);
            }

            if (entry.Period != request.Period)
            {
                SystemMonitor.OperationError("Data history request received but period not recognized.");
                return(false);
            }

            if (request.MaxValuesRetrieved.HasValue == false)
            {
                request.MaxValuesRetrieved = int.MaxValue;
            }

            if (request.StartIndex.HasValue == false)
            {
                request.StartIndex = -1;
            }

            GeneralHelper.GenericReturnDelegate <bool> operationDelegate = delegate()
            {
                if (request.IsTickBased)
                {
                    DataReaderWriter <DataTick> readerWriter = entry.GetDataTickReaderWriter();

                    List <DataTick>   dataTicks;
                    DataHistoryUpdate update = new DataHistoryUpdate(request.Period, new DataTick[] { });
                    if (readerWriter.Read(request.StartIndex.Value, request.MaxValuesRetrieved.Value, out dataTicks))
                    {
                        update.DataTicksUnsafe.AddRange(dataTicks);

                        if (DataHistoryUpdateEvent != null)
                        {
                            DataHistoryUpdateEvent(this, sessionInfo, update);
                        }

                        return(true);
                    }
                }
                else
                {
                    DataReaderWriter <DataBar> readerWriter = entry.GetDataBarReaderWriter();
                    if (readerWriter == null)
                    {
                        SystemMonitor.OperationError("Failed to establish file reader writer for entry.");
                        return(false);
                    }

                    List <DataBar>    dataBars;
                    DataHistoryUpdate update = new DataHistoryUpdate(request.Period, new DataBar[] { });

                    bool readResult = false;
                    if (request.StartIndex.Value < 0)
                    {// Instruction is to read the last count items.
                        readResult = readerWriter.ReadLast(
                            request.MaxValuesRetrieved.Value, out dataBars);
                    }
                    else
                    {
                        readResult = readerWriter.Read(request.StartIndex.Value,
                                                       request.MaxValuesRetrieved.Value, out dataBars);
                    }

                    if (readResult)
                    {
                        update.DataBarsUnsafe.AddRange(dataBars);

                        if (DataHistoryUpdateEvent != null)
                        {
                            DataHistoryUpdateEvent(this, sessionInfo, update);
                        }

                        return(true);
                    }
                }

                return(false);
            };

            if (waitResult)
            {
                return(operationDelegate());
            }
            else
            {
                GeneralHelper.FireAndForget(operationDelegate);
                return(true);
            }
        }
Пример #8
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);
            }

            DataSourceStub.IImplementation implementation = Implementation;
            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 _symbolsRunningSessions.Values)
                        {
                            if (combined.FullUnsubscribe(message.TransportInfo.OriginalSenderId.Value))
                            {// For every sessionInformation that has something
                                // Make sure to pass combined as parameter, otherwise the value is in foreach and chages before the thread starts.
                                GeneralHelper.FireAndForget(
                                    delegate(CombinedDataSubscriptionInformation combinedValue)
                                {
                                    if (implementation != null)
                                    {// First allow the implementation to unsubscribe since it needs the combined dataDelivery.
                                        implementation.SessionDataSubscriptionUpdate(combinedValue.SessionInformation.Info, message.Subscribe, message.Information);
                                    }
                                }, combined);
                            }
                        }
                    }
                }
            }
            else
            {
                if (_symbolsRunningSessions.ContainsKey(message.SessionInfo.Symbol) == false ||
                    _symbolsRunningSessions[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 = GetUnsafeSessionSubscriptions(message.SessionInfo);
                if (combined != null)
                {
                    combined.HandleRequest(message.TransportInfo, message.Subscribe, message.Information);
                    if (implementation != null)
                    {
                        GeneralHelper.FireAndForget(delegate()
                        {
                            implementation.SessionDataSubscriptionUpdate(message.SessionInfo, 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);
        }
Пример #9
0
        /// <summary>
        ///
        /// </summary>
        public override bool Write(int startingRow, int rowCount, ReadOnlyCollection <DataBar> bars)
        {
            FileStream fs;

            if (startingRow == 0)
            {
                fs = new FileStream(FilePath, FileMode.CreateNew);
            }
            else
            {
                if (File.Exists(FilePath) == false)
                {
                    SystemMonitor.OperationError("Failed to find to write to.");
                    return(false);
                }

                fs = new FileStream(FilePath, FileMode.Open, FileAccess.ReadWrite);
            }

            using (fs)
            {
                using (BinaryWriter bw = new BinaryWriter(fs))
                {
                    if (startingRow == 0)
                    {
                        if (WriteHeader(bw) == false)
                        {
                            return(false);
                        }
                    }
                    else
                    {
                        using (BinaryReader reader = new BinaryReader(fs))
                        {
                            try
                            {
                                for (int i = 0; i < startingRow; i++)
                                {
                                    ReadBarData(reader, DecimalDigits);
                                }
                            }
                            catch (Exception ex)
                            {
                                SystemMonitor.OperationError("Error in moving to required starting row [" + ex.Message + "].");
                                return(false);
                            }
                        }
                    }

                    int count = 0;
                    foreach (DataBar bar in bars)
                    {
                        if (count > rowCount)
                        {
                            break;
                        }
                        WriteBarData(bw, bar);
                        count++;
                    }
                }
            }


            return(true);
        }
Пример #10
0
        protected override bool OnInitialize(Platform platform)
        {
            TracerHelper.TraceEntry();

            if (base.OnInitialize(platform) == false)
            {
                return(false);
            }

            string expertName = this.Name + ".expert";

            // Clean expertname since we might be sending it trough command line.
            expertName = expertName.Replace(" ", "_");
            expertName = expertName.Replace("\"", "");

            lock (this)
            {
                if (_expert == null)
                {// Create the expert.
                    SystemMonitor.CheckThrow(_expertType.IsSubclassOf(typeof(Expert)), "Invalid expert type passed in.");
                    ConstructorInfo constructor = _expertType.GetConstructor(new Type[] { typeof(ISourceAndExpertSessionManager), typeof(string) });

                    if (constructor == null)
                    {// Try the second option for construction.
                        constructor = _expertType.GetConstructor(new Type[] { typeof(ISourceAndExpertSessionManager) });
                    }

                    if (constructor == null)
                    {
                        SystemMonitor.Error("Failed to find corresponding constructor for expert type [" + _expertType.ToString() + "].");
                        return(false);
                    }

                    if (constructor.GetParameters().Length == 2)
                    {
                        _expert = (Expert)constructor.Invoke(new object[] { this, expertName });
                    }
                    else
                    {
                        _expert = (Expert)constructor.Invoke(new object[] { this });
                    }
                }

                if (_expert.Initialize() == false)
                {
                    SystemMonitor.Error("Expert host failed to connect to platform.");
                    return(false);
                }

                if (_expert != null)
                {
                    _expert.PersistenceDataUpdateEvent += new Expert.ExpertUpdateDelegate(_expert_PersistenceDataUpdateEvent);
                }
            }

            foreach (PlatformExpertSession session in SessionsArray)
            {
                if (session.Initialize(null) == false)
                {
                    SystemMonitor.OperationWarning("Failed to initialize session.");
                }
            }

            ChangeOperationalState(OperationalStateEnum.Operational);

            TracerHelper.TraceExit();
            return(true);
        }
 /// <summary>
 ///
 /// </summary>
 public double[] CreateFixedLineResultLength(double value)
 {
     //return MathHelper.CreateFixedLineResultLength(value,  ResultSets[0].Values.Length);
     SystemMonitor.NotImplementedCritical();
     return(null);
 }
Пример #12
0
 public void Initialize(ChartPane pane)
 {
     SystemMonitor.CheckThrow(_pane == null);
     _pane = pane;
 }
Пример #13
0
        /// <summary>
        /// Loads the data entry from a file.
        /// </summary>
        /// <param name="FileNameGuidSeparator">Separator symbol separating the Guid part from the symbol part. Pass null/string.Empty if none.</param>
        public bool LoadFromFile(string filePath, string fileNameGuidSeparator)
        {
            _fileName = Path.GetFileName(filePath);

            _period    = null;
            _copyright = string.Empty;

            string symbolName = Path.GetFileNameWithoutExtension(filePath);

            if (string.IsNullOrEmpty(fileNameGuidSeparator) == false)
            {
                symbolName = symbolName.Substring(0, symbolName.IndexOf(fileNameGuidSeparator));
            }

            if (FinancialHelper.EstablishForexPairAndPeriod(symbolName, out symbolName) == false)
            {
                SystemMonitor.OperationWarning(string.Format("Failed to establish symbol information for file [{0}].", filePath));
            }

            if (DataType == EntryDataTypeEnum.DataBar)
            {
                DataReaderWriter <DataBar> readerWriter = GetDataBarReaderWriter();
                if (readerWriter == null)
                {
                    SystemMonitor.OperationWarning(string.Format("Failed to create reader/writer for file [{0}].", filePath));
                    _fileName = null;
                    return(false);
                }

                _decimalDigits = -1;

                readerWriter.DataPageReadEvent += delegate(DataReaderWriter <DataBar> reader, List <DataBar> pageData)
                {
                    if (_period.HasValue == false)
                    {
                        _period = FinancialHelper.GetPrevalentPeriod(pageData);
                    }

                    if (pageData.Count > 0 && (pageData[0].DateTime < _startTime || _startTime == DateTime.MinValue))
                    {
                        _startTime = pageData[0].DateTime;
                    }

                    if (pageData.Count > 0 && (pageData[pageData.Count - 1].DateTime > _endTime || _endTime == DateTime.MinValue))
                    {
                        _endTime = pageData[pageData.Count - 1].DateTime;
                    }

                    if (_decimalDigits < 0)
                    {
                        _decimalDigits = FinancialHelper.EstablishDecimalDigits(pageData);
                    }

                    return(true);
                };

                int totalRowsRead = 0;
                if (readerWriter.ReadDataPaged(int.MaxValue, out totalRowsRead) == false)
                {
                    _quoteCount = 0;
                    _symbol     = Symbol.Emtpy;
                    return(false);
                }

                _quoteCount = totalRowsRead;

                if (readerWriter is HSTDataBarReaderWriter)
                {// If this is an Hst, read the additional information from it.
                    _copyright     = ((HSTDataBarReaderWriter)readerWriter).Copyright;
                    symbolName     = ((HSTDataBarReaderWriter)readerWriter).Symbol;
                    _decimalDigits = ((HSTDataBarReaderWriter)readerWriter).DecimalDigits;
                    _period        = ((HSTDataBarReaderWriter)readerWriter).Period;
                }

                _symbol = new Symbol(string.Empty, symbolName, FileName.Replace(DataStore.FileNameGuidSeparator, " "));
            }
            else
            {
                SystemMonitor.NotImplementedCritical("Mode not supported.");
            }

            return(true);
        }
Пример #14
0
        // << Result format ; string& symbol, double& minVolume, double& desiredPrice (0 for none), int& slippage, double& takeProfit, double& stopLoss, int& orderType, int& operationID, string& comment
        public string RequestNewOrder()
        {
            int operationId;

            try
            {
                OrderMessage message = base.GetPendingMessage <OrderMessage>(true, out operationId);

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

                // Process comment.
                message.Comment = message.Comment.Replace(SeparatorSymbol, ",");

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

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

                // Process TP.
                if (message.TakeProfit.HasValue == false)
                {
                    message.TakeProfit = 0;
                }

                // Process SL.
                if (message.StopLoss.HasValue == false)
                {
                    message.StopLoss = 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 == false)
                    {
                        base.CompleteOperation(operationId, new ResponceMessage(false, "Failed to establish symbol session."));
                    }
                    return(string.Empty);
                }

                decimal volume = ConvertVolume(session.SessionInformation.Info.LotSize, message.Volume);

                string result =
                    message.Symbol.Name + SeparatorSymbol +
                    volume.ToString(GeneralHelper.UniversalNumberFormatInfo) + SeparatorSymbol +
                    message.DesiredPrice.Value.ToString(GeneralHelper.UniversalNumberFormatInfo) + SeparatorSymbol +
                    slippage.ToString() + SeparatorSymbol +
                    message.TakeProfit.Value.ToString(GeneralHelper.UniversalNumberFormatInfo) + SeparatorSymbol +
                    message.StopLoss.Value.ToString(GeneralHelper.UniversalNumberFormatInfo) + SeparatorSymbol +
                    ((int)message.OrderType).ToString() + SeparatorSymbol +
                    operationId + SeparatorSymbol +
                    message.Comment;

                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
        internal void BuildObjectGraph(Action shutdown)
        {
            ValidateCommandLineArguments();

            InitializeLogging();
            InitializeText();

            context         = new ClientContext();
            uiFactory       = BuildUserInterfaceFactory();
            actionCenter    = uiFactory.CreateActionCenter();
            messageBox      = BuildMessageBox();
            nativeMethods   = new NativeMethods();
            powerSupply     = new PowerSupply(ModuleLogger(nameof(PowerSupply)));
            runtimeProxy    = new RuntimeProxy(runtimeHostUri, new ProxyObjectFactory(), ModuleLogger(nameof(RuntimeProxy)), Interlocutor.Client);
            systemInfo      = new SystemInfo();
            taskbar         = uiFactory.CreateTaskbar(ModuleLogger("Taskbar"));
            taskview        = uiFactory.CreateTaskview();
            wirelessAdapter = new WirelessAdapter(ModuleLogger(nameof(WirelessAdapter)));

            var processFactory     = new ProcessFactory(ModuleLogger(nameof(ProcessFactory)));
            var applicationMonitor = new ApplicationMonitor(TWO_SECONDS, ModuleLogger(nameof(ApplicationMonitor)), nativeMethods, processFactory);
            var applicationFactory = new ApplicationFactory(applicationMonitor, ModuleLogger(nameof(ApplicationFactory)), nativeMethods, processFactory);
            var displayMonitor     = new DisplayMonitor(ModuleLogger(nameof(DisplayMonitor)), nativeMethods, systemInfo);
            var explorerShell      = new ExplorerShell(ModuleLogger(nameof(ExplorerShell)), nativeMethods);
            var fileSystemDialog   = BuildFileSystemDialog();
            var hashAlgorithm      = new HashAlgorithm();
            var splashScreen       = uiFactory.CreateSplashScreen();
            var systemMonitor      = new SystemMonitor(ModuleLogger(nameof(SystemMonitor)));

            var operations = new Queue <IOperation>();

            operations.Enqueue(new I18nOperation(logger, text));
            operations.Enqueue(new RuntimeConnectionOperation(context, logger, runtimeProxy, authenticationToken));
            operations.Enqueue(new ConfigurationOperation(context, logger, runtimeProxy));
            operations.Enqueue(new DelegateOperation(UpdateAppConfig));
            operations.Enqueue(new LazyInitializationOperation(BuildClientHostOperation));
            operations.Enqueue(new ClientHostDisconnectionOperation(context, logger, FIVE_SECONDS));
            operations.Enqueue(new LazyInitializationOperation(BuildKeyboardInterceptorOperation));
            operations.Enqueue(new LazyInitializationOperation(BuildMouseInterceptorOperation));
            operations.Enqueue(new ApplicationOperation(context, applicationFactory, applicationMonitor, logger, text));
            operations.Enqueue(new DisplayMonitorOperation(context, displayMonitor, logger, taskbar));
            operations.Enqueue(new SystemMonitorOperation(context, systemMonitor, logger));
            operations.Enqueue(new LazyInitializationOperation(BuildShellOperation));
            operations.Enqueue(new LazyInitializationOperation(BuildBrowserOperation));
            operations.Enqueue(new LazyInitializationOperation(BuildServerOperation));
            operations.Enqueue(new LazyInitializationOperation(BuildProctoringOperation));
            operations.Enqueue(new ClipboardOperation(context, logger, nativeMethods));

            var sequence = new OperationSequence(logger, operations);

            ClientController = new ClientController(
                actionCenter,
                applicationMonitor,
                context,
                displayMonitor,
                explorerShell,
                fileSystemDialog,
                hashAlgorithm,
                logger,
                messageBox,
                sequence,
                runtimeProxy,
                shutdown,
                splashScreen,
                systemMonitor,
                taskbar,
                text,
                uiFactory);
        }
        /// <summary>
        /// Main SynchronousExecute method.
        /// </summary>
        public bool SynchronousExecute(AccountInfo account, Order order, Symbol symbol, OrderTypeEnum orderType,
                                       int volume, decimal?allowedSlippage, decimal?desiredPrice, decimal?takeProfit, decimal?stopLoss,
                                       string comment, TimeSpan operationTimeOut, out OrderInfo?info, out string operationResultMessage)
        {
            TracerHelper.Trace(this.Name);

            info = null;
            operationResultMessage = string.Empty;

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

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

            allowedSlippage = ProcessSlippage(allowedSlippage);

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

            request.PerformSynchronous = true;

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

            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);
            }


            //if (orderType == OrderTypeEnum.BUY_MARKET
            //    || orderType == OrderTypeEnum.SELL_MARKET)
            //{// Immediate order.
            //    resultState = OrderStateEnum.Executed;
            //}
            //else
            //{// Delayed pending order.
            //    resultState = OrderStateEnum.Submitted;
            //}

            ExecuteMarketOrderResponseMessage responseMessage = (ExecuteMarketOrderResponseMessage)response;

            operationResultMessage = "Order opened.";

            info = responseMessage.Info;

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

            return(true);
        }
Пример #17
0
        /// <summary>
        /// Obtain the next execution entity and remove it from pending.
        /// Children to override to manage the way operations are performed, if they need to.
        /// This is where currently the MultiThreads per client protection is performed.
        /// </summary>
        protected virtual ExecutionEntity PopNextExecutionEntity()
        {
            lock (this)
            {
                // Check total executioners count.
                if (_threadPool.FreeThreadsCount < 2)
                {
                    //if ((DateTime.Now - _executionersBusyWarningShownTime) >= _warningsTimeSpan)
                    {
                        SystemMonitor.OperationError("All of the [" + _threadPool.MaximumThreadsCount + "] arbiter [" + _arbiter.Name + "] executioners are busy, entity execution delayed.", TracerItem.PriorityEnum.Medium);
                        //_executionersBusyWarningShownTime = DateTime.Now;
                    }

                    return(null);
                }

                // List of IDs we tried to execute upon already, and presumably failed.
                List <ArbiterClientId> processedIds = new List <ArbiterClientId>();

                // Try looking for a new entity.
                for (int i = 0; i < _pendingEntities.Count; i++)
                {// Look for an entity that we are allowed to execute now.
                    ExecutionEntity entity  = _pendingEntities[i];
                    IArbiterClient  iClient = _arbiter.GetClientByID(entity.ReceiverID);

                    if (processedIds.Contains(entity.ReceiverID))
                    {// Alredy tried on this entity, skip.
                        continue;
                    }
                    else
                    {// First time we see this entity.
                        processedIds.Add(entity.ReceiverID);
                    }

                    bool isTransportResponseMessage = (entity.Message is TransportMessage &&
                                                       ((TransportMessage)(entity.Message)).IsRequest == false);

                    int runningOnClient = 0;
                    if (_clientsRunningExecutioners.ContainsKey(entity.ReceiverID))
                    {
                        runningOnClient = _clientsRunningExecutioners[entity.ReceiverID];
                    }

                    if (isTransportResponseMessage == false && iClient != null &&
                        iClient.SingleThreadMode && runningOnClient > 0 /*_executionersAndClientIDs.ContainsValue(entity.ReceiverID)*/)
                    {// We are not allowed to run this, as there is already an executioner there.
                        // And it is not a responce requestMessage.
                        continue;
                    }

                    if (runningOnClient >= _maxExecutionersPerEntity)
                    {// This entity is already consuming too many threads. It must release some before using more.
                        //if ((DateTime.Now - _executionersBusyWarningShownTime) >= _warningsTimeSpan)
                        {
                            //_executionersBusyWarningShownTime = DateTime.Now;
                            SystemMonitor.OperationError("An entity [" + entity.ReceiverID.Id.Name + "] is using all its threads allowed. Further entity executions will be delayed.", TracerItem.PriorityEnum.Medium);
                        }

                        continue;
                    }

                    //TraceHelper.Trace("PopNextExecutionEntity [" + iClient.ToString() + "][" + iClient.SingleThreadMode + "," + _executionersAndClientIDs.ContainsValue(entity.ReceiverID) + "][" + entity.Message.ToString() + "]");

                    _pendingEntities.Remove(entity);

                    // OK, this entity is good to go.
                    return(entity);
                }

                return(null);
            }
        }
Пример #18
0
        void _executor_OrderUpdatedEvent(IOrderSink providerSink, AccountInfo accountInfo, string[] previousOrdersIds,
                                         OrderInfo[] ordersInfos, Order.UpdateTypeEnum[] updatesType)
        {
            ISourceOrderExecution provider = _provider;

            if (providerSink != _provider)
            {
                SystemMonitor.Warning("Provider mismatch.");
                return;
            }

            List <Order> updatedOrders = new List <Order>();
            List <Order.UpdateTypeEnum> updatedOrdersUpdateTypes = new List <Order.UpdateTypeEnum>();

            for (int i = 0; i < ordersInfos.Length; i++)
            {
                if (string.IsNullOrEmpty(ordersInfos[i].Id))
                {
                    SystemMonitor.Warning("Order update of order with no ID.");
                    continue;
                }

                if (previousOrdersIds.Length > i && previousOrdersIds[i] != ordersInfos[i].Id &&
                    string.IsNullOrEmpty(previousOrdersIds[i]) == false)
                {// Order Id has changed, remove old order.
                    Order superceededOrder = GetOrderById(previousOrdersIds[i]);
                    RemoveOrder(superceededOrder);
                }

                Order order = GetOrderById(ordersInfos[i].Id);
                if (order == null)
                {// Create new order based on incoming information.
                    if (provider.SupportsActiveOrderManagement)
                    {
                        order = new ActiveOrder(_manager, provider, _manager.ObtainQuoteProvider(_delivery.SourceId, ordersInfos[i].Symbol),
                                                _delivery.SourceId, ordersInfos[i].Symbol, true);
                    }
                    else
                    {
                        order = new PassiveOrder(_manager, _delivery.SourceId, provider.SourceId);
                    }

                    order.AdoptInfo(ordersInfos[i]);

                    if (AddOrder(order) == false)
                    {
                        SystemMonitor.OperationError("Failed to add order to keeper (id [" + order.Id + "] already used for another order).", TracerItem.PriorityEnum.Medium);
                    }
                }
                else
                {// Existing order, to be updated.
                    OrderInfo info = ordersInfos[i];

                    // First, check for critical modifications (price changes).
                    if (order.Info.IsCriticalUpdate(info))
                    {
                        SystemMonitor.Report(string.Format("Order has received a critical data modication Id[{0}], Open[{1} / {2}], Close[{3} / {4}].", order.Id, order.OpenPrice.ToString(), info.OpenPrice.ToString(), order.ClosePrice.ToString(),
                                                           info.ClosePrice.ToString()), TracerItem.PriorityEnum.High);

                        if (OrdersCriticalInformationChangedEvent != null)
                        {
                            OrdersCriticalInformationChangedEvent(this, accountInfo, order, info);
                        }
                    }

                    if (order.UpdateInfo(info) == false)
                    {
                        SystemMonitor.OperationError("Failed to update order [" + order.Id + "].");
                        continue;
                    }

                    lock (this)
                    {
                        // Remove from any of the sub arrays it may be in.
                        foreach (OrderStateEnum state in Enum.GetValues(typeof(OrderStateEnum)))
                        {
                            if (_ordersByState.ContainsKey(state) && _ordersByState[state].Contains(order))
                            {
                                _ordersByState[state].Remove(order);
                            }
                        }

                        _ordersByState[info.State].Add(order);
                    }

                    updatedOrders.Add(order);
                    updatedOrdersUpdateTypes.Add(updatesType[i]);
                }
            }

            if (updatedOrders.Count > 0 && OrdersUpdatedEvent != null)
            {
                OrdersUpdatedEvent(this, accountInfo, updatedOrders.ToArray(), updatedOrdersUpdateTypes.ToArray());
            }
        }
 void source_PersistenceDataUpdatedEvent(IDBPersistent source)
 {
     SystemMonitor.CheckError(_persistenceHelper.UpdateToDB((NewsSource)source, null), "Failed to update source.");
 }
Пример #20
0
        /// <summary>
        /// Add orders.
        /// </summary>
        public bool AddOrders(IEnumerable <Order> orders)
        {
            lock (this)
            {
                foreach (Order order in orders)
                {
                    if (string.IsNullOrEmpty(order.Id) == false && (_orders.ContainsKey(order.Id) || _orders.ContainsValue(order)))
                    {
                        SystemMonitor.OperationWarning("Can not add order [" + order.Id + "] since (order or id) already added.");
                        return(false);
                    }
                }

                foreach (Order order in orders)
                {
                    if (string.IsNullOrEmpty(order.Id))
                    {
                        SystemMonitor.Warning("Adding an order with no Id, order skipped.");
                        continue;
                    }

                    if (order.Symbol.IsEmpty)
                    {
                        SystemMonitor.Warning("Adding an order with no Symbol assigned, order skipped.");
                        continue;
                    }

                    _orders.Add(order.Id, order);
                    if (_ordersByState.ContainsKey(order.State))
                    {
                        _ordersByState[order.State].Add(order);
                    }
                    else
                    {
                        SystemMonitor.Error("State for this order [" + order.State + "] not found.");
                    }

                    if (_ordersBySymbol.ContainsKey(order.Symbol) == false)
                    {
                        _ordersBySymbol.Add(order.Symbol, new ListEx <Order>());
                    }

                    if (_ordersBySymbol.ContainsKey(order.Symbol))
                    {
                        _ordersBySymbol[order.Symbol].Add(order);
                    }
                    else
                    {
                        SystemMonitor.Error("Order symbol not in list [" + order.Symbol + "] not found.");
                    }

                    order.OrderUpdatedEvent += new Order.OrderUpdatedDelegate(order_OrderUpdatedEvent);

                    // Make sure there is a position for this order.
                    ObtainPositionBySymbol(order.Symbol);
                }
            }

            if (OrdersAddedEvent != null)
            {
                if (_provider.DefaultAccount == null)
                {
                    SystemMonitor.OperationError("Orders update arrived too soon.", TracerItem.PriorityEnum.Medium);
                }
                else
                {
                    OrdersAddedEvent(this, _provider.DefaultAccount.Info, orders);
                }
            }

            return(true);
        }
Пример #21
0
        static void Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
            Application.ThreadExit      += new EventHandler(Application_ThreadExit);

            if (args.Length == 0)
            {
                MessageBox.Show("Use ForexPlatformClient.exe to run the platform.", "Application Message", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            // The application starts in global diagnostics mode by default. When the platform initializes, it restores it setting on that.
            // No major warnings/errors are expected in normal operation before the initialization of the platform.
            SystemMonitor.GlobalDiagnosticsMode = true;

            if (args[0].ToLower() == "ManagedLaunch".ToLower())
            {// Default managed starting procedure.
                try
                {
                    // Single instance mode check.
                    bool createdNew;
                    GeneralHelper.CreateCheckApplicationMutex(Application.ProductName, out createdNew);

                    if (createdNew == false)
                    {
                        if (Settings.Default.SingleInstanceMode)
                        {
                            MessageBox.Show("Application already running and single instance mode set (config file).", Application.ProductName + " Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                        else
                        {
                            if (MessageBox.Show("Another instance of the application is already running, do you wish to continue?", Application.ProductName + " Note", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) != DialogResult.OK)
                            {
                                return;
                            }
                        }
                    }

                    // Log file.
                    string logFile = Settings.Default.TraceLogFile;

                    if (string.IsNullOrEmpty(logFile) == false)
                    {
                        TracerHelper.Tracer.Add(new FileTracerItemSink(TracerHelper.Tracer,
                                                                       GeneralHelper.MapRelativeFilePathToExecutingDirectory(logFile)));
                    }

                    if (createdNew == false)
                    {
                        TracerHelper.Trace("Running as second (multiple) instance.");
                    }

                    Form mainForm = new OpenForexPlatformBeta();
                    Application.Run(mainForm);
                }
                catch (Exception ex)
                {
                    SystemMonitor.Error(ex.GetType().Name + "; " + ex.Message);
                }
                finally
                {
                    GeneralHelper.DestroyApplicationMutex();
                }
            }
            else if (args[0].ToLower() == "experthost" && args.Length >= 4)
            {// Start as an expert host.
                Uri    uri        = new Uri(args[1]);
                Type   expertType = Type.ReflectionOnlyGetType(args[2], true, true);
                string expertName = args[3];

                RemoteExpertHostForm hostForm = new RemoteExpertHostForm(uri, expertType, expertName);
                Application.Run(hostForm);
            }
            else
            {
                MessageBox.Show("Starting parameters not recognized. Process will not start.", "Error in starting procedure.", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Пример #22
0
        /// <summary>
        /// Will close open order (?!) or cancel pending one.
        /// </summary>
        /// <param name="desiredPrice"></param>
        /// <param name="slippage"></param>
        /// <param name="operationResultMessage"></param>
        /// <returns></returns>
        public bool CloseOrCancel(decimal?desiredPrice, decimal?slippage, out string operationResultMessage)
        {
            if (this.OpenPrice.HasValue == false)
            {
                operationResultMessage = "Invalid order open price.";
                return(false);
            }

            if (State != OrderStateEnum.Executed && State != OrderStateEnum.Submitted)
            {
                operationResultMessage = "Close/Decrease volume can be done only to open/pending orders.";
                return(false);
            }

            decimal operationPrice;
            bool    operationResult = false;

            ISourceOrderExecution executionProvider = _executionProvider;

            if (executionProvider == null)
            {
                operationResultMessage = "Execution provider not assigned.";
                return(false);
            }

            DateTime closeTime = DateTime.MinValue;

            string modifiedId;

            // Close/Cancel order.
            if (State == OrderStateEnum.Executed)
            {
                operationResult = executionProvider.CloseOrder(_executionProvider.DefaultAccount.Info, this,
                                                               slippage, desiredPrice, out operationPrice, out closeTime, out modifiedId, out operationResultMessage);
            }
            else if (State == OrderStateEnum.Submitted)
            {
                operationPrice  = decimal.MinValue;
                operationResult = executionProvider.CancelPendingOrder(_executionProvider.DefaultAccount.Info, this, out modifiedId, out operationResultMessage);
            }
            else
            {
                operationResultMessage = "Order not in expected state.";
                return(false);
            }

            if (operationResult == false)
            {
                SystemMonitor.Report("Order volume decrease has failed in executioner.");
                return(false);
            }

            if (string.IsNullOrEmpty(modifiedId))
            {// Since the original order has changed its ticket number; and we have failed to establish the new one - we can no longer track it so unregister.
                SystemMonitor.OperationWarning("Failed to establish new modified order ticket; order will be re-aquired.", TracerItem.PriorityEnum.High);
                executionProvider.TradeEntities.RemoveOrder(this);

                return(true);
            }

            if (State == OrderStateEnum.Executed)
            {
                if (modifiedId != this.Id)
                {
                    operationResultMessage = "Failed to close order, id returned is different.";
                    return(false);

                    //executionProvider.TradeEntities.RemoveOrder(this);

                    //OrderInfo newUpdatedInfo = _info;
                    //newUpdatedInfo.Id = modifiedId;
                    //newUpdatedInfo.Volume = 0;

                    //ActiveOrder updatedOrder = new ActiveOrder(_manager, _executionProvider, _quoteProvider, _dataSourceId, Symbol, true);
                    //updatedOrder.AdoptInfo(newUpdatedInfo);
                    //_executionProvider.TradeEntities.AddOrder(updatedOrder);

                    // Request updated order info for this and new one and remove current one.
                    //if (_executionProvider != null && _executionProvider.DefaultAccount != null && string.IsNullOrEmpty(modifiedId) == false)
                    //{
                    //    _executionProvider.BeginOrdersInformationUpdate(_executionProvider.DefaultAccount.Info, new string[] { this.Id, modifiedId }, out operationResultMessage);
                    //}
                }
                else
                {
                    _info.Volume = 0;

                    State            = OrderStateEnum.Closed;
                    _info.CloseTime  = closeTime;
                    _info.ClosePrice = operationPrice;
                }
            }
            else if (State == OrderStateEnum.Submitted)
            {
                lock (this)
                {
                    //_initialVolume -= volumeDecrease;
                    _info.Volume = 0;
                    State        = OrderStateEnum.Canceled;
                }
            }

            if (State == OrderStateEnum.Closed)
            {// Closed.
                RaiseOrderUpdatedEvent(UpdateTypeEnum.Closed);
            }
            else if (State == OrderStateEnum.Canceled)
            {// Still open.
                RaiseOrderUpdatedEvent(UpdateTypeEnum.Canceled);
            }

            return(true);
        }
Пример #23
0
 public override void ReceiveExecutionWithReply(ExecutionEntityWithReply entity)
 {
     SystemMonitor.CheckError(entity.Message.GetType().IsSubclassOf(typeof(TransportMessage)));
     OnMessageReceived((TransportMessage)entity.Message);
 }
Пример #24
0
        protected void AssignClientSource(object source)
        {
            SuperPoolClient client = _client;

            if (client == null)
            {
#if Matrix_Diagnostics
                SystemMonitor.Error("Failed to add client source, since client not available (possible Dispose).");
#endif
                return;
            }

            SuperPoolSubscription owner = _owner;
            if (owner == null)
            {
#if Matrix_Diagnostics
                SystemMonitor.Error("Failed to add client source, since no owner is available (possible Dispose).");
#endif
                return;
            }

            ReleaseCurrentClientSource();

            _clientSource = source;

            if (_clientSource == null)
            {
#if Matrix_Diagnostics
                SystemMonitor.OperationWarning("Starting a client with no source attached.");
#endif
                return;
            }

            foreach (Type interfaceType in ReflectionHelper.GatherTypeAttributeMarkedInterfaces(source.GetType(), typeof(SuperPoolInterfaceAttribute)))
            {// Gather all events, from interfaces marked with [SuperPoolInterfaceAttribute].
                // Make sure to have created the corresponding proxy instance for this interface type.
                owner.ProxyTypeManager.ObtainInterfaceProxy(interfaceType);

                foreach (EventInfo eventInfo in interfaceType.GetEvents())
                {
                    Type delegateType = eventInfo.EventHandlerType;
                    GeneratedMethodInfo methodInfo = owner.ProxyTypeManager.Builder.GenerateDynamicMethodProxyDelegate(delegateType);

                    // Create delegate can operate in 2 modes:
                    // - create a static delegate like this (requires instnace upon call): info.Method.CreateDelegate(delegateType);
                    // - create an instance delegate like this (can be direct called): info.Method.CreateDelegate(delegateType, instance);

                    Delegate delegateInstance = methodInfo.StandaloneDynamicMethod.CreateDelegate(delegateType, this);
                    eventInfo.AddEventHandler(source, delegateInstance);

                    EventHandlingInformation subscriptionInfo = new EventHandlingInformation()
                    {
                        DelegateInstance    = delegateInstance,
                        EventInfo           = eventInfo,
                        GeneratedMethodInfo = methodInfo
                    };

                    lock (this)
                    {
                        _eventsMethods.Add(methodInfo.Id, subscriptionInfo);
                    }
                }
            }
        }
Пример #25
0
        /// <summary>
        /// Central sending function.
        /// </summary>
        /// <param name="receiverID">The ID of the receiver module. Can be <b>null</b> and this sends to all in the Arbiter.</param>
        protected TransportMessage[] DoSendCustom(bool isRequest, Guid sessionGuid,
                                                  Type expectedResponceMessageClassType, int responcesRequired,
                                                  ArbiterClientId?receiverId, ArbiterClientId?senderId, TransportMessage message, TimeSpan timeOut)
        {
            TracerHelper.TraceEntry();

            SessionResults session = null;

            if (receiverId.HasValue && receiverId.Value.IsEmpty /*receiverId.Value.CompareTo(ArbiterClientId.Empty) == 0*/)
            {
                SystemMonitor.Error("Can not send an item to empty receiver. Use null to specify broadcast.");
                return(null);
            }

            // Preliminary verification.
            if (Arbiter == null)
            {
                SystemMonitor.OperationWarning("Using a client [" + this.GetType().Name + ":" + senderId.Value.ClientName + " to " + (receiverId.HasValue ? receiverId.Value.Id.Name : string.Empty) + " , " + message.GetType().Name + "] with no Arbiter assigned.");
                return(null);
            }

            message.IsRequest = isRequest;

            TransportInfoUnit infoUnit = new TransportInfoUnit(sessionGuid, senderId, receiverId);

            message.TransportInfo.AddTransportInfoUnit(infoUnit);

            bool sessionEventResult = false;

            if (expectedResponceMessageClassType != null)
            {// Responce waiting session.
                session = new SessionResults(responcesRequired, expectedResponceMessageClassType);
                lock (_communicationSessions)
                {// Register the session.
                    _communicationSessions.Add(sessionGuid, session);
                }
            }

            SystemMonitor.CheckError(message.TransportInfo.CurrentTransportInfo != null);
            Conversation conversation;

            if (receiverId == null)
            {
                // We shall not use the next level time out mechanism.
                conversation = Arbiter.CreateConversation(senderId.Value, message, TimeSpan.Zero);
            }
            else
            {// Addressed conversation.
                // We shall not use the next level time out mechanism.
                conversation = Arbiter.CreateConversation(senderId.Value, receiverId.Value, message, TimeSpan.Zero);
            }

            if (conversation != null && expectedResponceMessageClassType != null)
            {     // Responce waiting session (only if conversation was properly created).
                if (timeOut == TimeSpan.Zero)
                { // Wait forever.
                    sessionEventResult = session.SessionEndEvent.WaitOne();
                }
                else
                {// Wait given period.
                    sessionEventResult = session.SessionEndEvent.WaitOne(timeOut, false);
                }

                lock (_communicationSessions)
                {// Remote the session.
                    _communicationSessions.Remove(sessionGuid);
                }
            }

            message.TransportInfo.PopTransportInfo();

            if (expectedResponceMessageClassType == null)
            {// No responce waiting, just return.
                TracerHelper.TraceExit();
                return(null);
            }

            // Responce waiting session.
            if (sessionEventResult == false)
            {// Timed out - only send and receives can time out, as the other ones do not have sessions!!
                TracerHelper.TraceError("Session has timed out [" + message.GetType().Name + "].");
                return(null);
            }

            TracerHelper.TraceExit();
            return(session.Responces.ToArray());
        }
Пример #26
0
        /// <summary>
        /// Constructor.
        /// </summary>
        public ClientEventsHandler(SuperPoolSubscription owner, SuperPoolClient client)
        {
            _owner = owner;
            if (Initialize(client) == false)
            {
#if Matrix_Diagnostics
                SystemMonitor.Error("Failed to initialize subscription for client."); SystemMonitor.ErrorIf(Initialize(client) == false, "Failed to initialize subscription for client."); SystemMonitor.ErrorIf(Initialize(client) == false, "Failed to initialize subscription for client."); SystemMonitor.Error("Failed to initialize subscription for client.");
#endif
            }
        }
Пример #27
0
 /// <summary>
 /// Check if given order type is buy (or sell).
 /// </summary>
 public static bool TypeIsBuy(OrderTypeEnum orderType)
 {
     SystemMonitor.CheckOperationWarning(orderType != OrderTypeEnum.UNKNOWN, "Order type not established yet.");
     return(orderType == OrderTypeEnum.BUY_MARKET || orderType == OrderTypeEnum.BUY_LIMIT_MARKET || orderType == OrderTypeEnum.BUY_STOP_MARKET);
 }
Пример #28
0
        /// <summary>
        ///
        /// </summary>
        public void Update(AccountInfo other)
        {
            if (other.Guid != Guid.Empty)
            {
                if (this.Guid != other.Guid)
                {
                    SystemMonitor.Warning("Account update with mismatching Guid.");
                    return;
                }
            }

            if (other.Balance.HasValue)
            {
                _balance = other._balance;
            }

            if (other._credit.HasValue)
            {
                _credit = other._credit;
            }

            if (string.IsNullOrEmpty(other._company) == false)
            {
                _company = other._company;
            }

            if (other._baseCurrency.IsEmpty == false)
            {
                _baseCurrency = other._baseCurrency;
            }

            if (string.IsNullOrEmpty(other._id) == false)
            {
                _id = other._id;
            }

            if (string.IsNullOrEmpty(other._server) == false)
            {
                _server = other._server;
            }

            if (string.IsNullOrEmpty(other._name) == false)
            {
                _name = other._name;
            }

            if (other._equity.HasValue)
            {
                _equity = other._equity;
            }

            if (other._freeMargin.HasValue)
            {
                _freeMargin = other._freeMargin;
            }

            if (other._leverage.HasValue)
            {
                _leverage = other._leverage;
            }

            if (other._margin.HasValue)
            {
                _margin = other._margin;
            }

            if (other._profit.HasValue)
            {
                _profit = other._profit;
            }
        }
Пример #29
0
        /// <summary>
        ///
        /// </summary>
        public bool Update(OrderInfo updateInfo)
        {
            if (updateInfo.Id != _id ||
                (updateInfo.Symbol.Name != _symbol.Name)
                // Can not filter type here, since type may change (for ex. the server may accept market orders as Market_Limit)
                /*|| (updateInfo.Type != OrderTypeEnum.UNKNOWN && updateInfo.Type != Type)*/)
            {
                SystemMonitor.Warning("Mismatching order basic parameters.");
                return(false);
            }

            _volume = updateInfo._volume;
            _state  = updateInfo._state;

            if (updateInfo._openPrice.HasValue)
            {
                _openPrice = updateInfo._openPrice;
            }

            if (updateInfo._closePrice.HasValue)
            {
                _closePrice = updateInfo._closePrice;
            }

            //if (updateInfo._stopLoss.HasValue)
            {
                _stopLoss = updateInfo._stopLoss;
            }

            //if (updateInfo._takeProfit.HasValue)
            {
                _takeProfit = updateInfo._takeProfit;
            }

            if (updateInfo._currentProfit.HasValue)
            {
                _currentProfit = updateInfo._currentProfit;
            }

            if (updateInfo._swap.HasValue)
            {
                _swap = updateInfo._swap;
            }

            if (updateInfo._closeTime.HasValue)
            {
                _closeTime = updateInfo._closeTime;
            }

            if (updateInfo._openTime.HasValue)
            {
                _openTime = updateInfo._openTime;
            }

            if (updateInfo._expiration.HasValue)
            {
                _expiration = updateInfo._expiration;
            }

            if (updateInfo._commission.HasValue)
            {
                _commission = updateInfo._commission;
            }

            if (updateInfo._comment != null)
            {
                _comment = updateInfo._comment;
            }

            if (updateInfo._tag != null)
            {
                _tag = updateInfo._tag;
            }

            return(true);
        }
Пример #30
0
        // >>
        public void OrderOpened(string symbol, int operationID, int orderTicket, decimal openingPrice,
                                int orderOpenTime, bool operationResult, string operationResultMessage)
        {
            TracerHelper.Trace(symbol);

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

                DateTime?time = GeneralHelper.GenerateDateTimeSecondsFrom1970(orderOpenTime);
                if (time.HasValue == false)
                {
                    if (operation != null)
                    {
                        base.CompleteOperation(operationID, new ResponceMessage(false, "Failed to convert time for order."));
                    }

                    SystemMonitor.Error("Failed to convert time for order.");
                    return;
                }

                string orderId = orderTicket.ToString();
                if (orderTicket < 0)
                {// The system needs orderId empty to recognize the result as failure.
                    orderId         = string.Empty;
                    operationResult = false;
                }

                if (operation != null)
                {
                    ResponceMessage message = null;

                    lock (this)
                    {
                        if (operation.Request is SubmitOrderMessage)
                        {
                            message = new SubmitOrderResponceMessage(_accountInfo, orderId, true);
                            message.OperationResultMessage = operationResultMessage;
                            message.OperationResult        = operationResult;
                        }
                        else if (operation.Request is ExecuteMarketOrderMessage)
                        {
                            OrderInfo info = new OrderInfo(orderId, CreateSymbol(symbol), OrderTypeEnum.UNKNOWN, OrderStateEnum.Executed, int.MinValue);
                            info.OpenTime  = time;
                            info.OpenPrice = openingPrice;

                            message = new ExecuteMarketOrderResponceMessage(_accountInfo, info, operationResult);
                            message.OperationResultMessage = operationResultMessage;
                        }
                        else
                        {
                            SystemMonitor.Error("Failed to establish placed order request type.");
                            message = new ResponceMessage(false);
                        }
                    }

                    base.CompleteOperation(operationID, message);
                }

                if (string.IsNullOrEmpty(orderId) == false)
                {
                    // Do an update of this order.
                    lock (this)
                    {
                        _pendingOrdersInformations.Add(orderId);
                    }
                }
            }
            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);
            }
        }