bool Construct()
        {
            if (_manager != null)
            {
                return(false);
            }

            StatusSynchronizationEnabled = true;

            lock (this)
            {
                _manager = new MBTradingConnectionManager(this);
                if (_manager.Quotes != null)
                {
                    _manager.Quotes.QuoteUpdateEvent += new MBTradingQuote.QuoteUpdateDelegate(Quotes_QuoteUpdateEvent);
                }

                _dataSourceStub.Initialize(this);
                _orderExecutionStub.Initialize(_manager.Orders);

                foreach (string symbol in EquitiesSymbols)
                {
                    _dataSourceStub.AddSuggestedSymbol(new Symbol(string.Empty, symbol));
                }

                foreach (string symbol in ForexSymbols)
                {
                    _dataSourceStub.AddSuggestedSymbol(new Symbol("FX", symbol));
                }
            }

            return(true);
        }
 protected void DisposeManager()
 {
     if (_manager != null)
     {
         _manager.Dispose();
         _manager = null;
     }
 }
Exemple #3
0
        /// <summary>
        ///
        /// </summary>
        public void SessionDataSubscriptionUpdate(DataSessionInfo session, bool subscribe, DataSubscriptionInfo?info)
        {
            SystemMonitor.CheckError(session.IsEmtpy == false, "Method needs valid session info assigned to operate.");

            DataSourceStub dataSourceStub = DataSourceStub;

            if (dataSourceStub == null)
            {
                return;
            }

            CombinedDataSubscriptionInformation combined = dataSourceStub.GetUnsafeSessionSubscriptions(session);

            if (combined == null)
            {
                SystemMonitor.OperationError("Update on not existing session.");
                return;
            }

            MBTradingConnectionManager manager = _manager;

            if (manager == null)
            {
                return;
            }

            DataSubscriptionInfo combinedInfo = combined.GetCombinedDataSubscription();

            if (combinedInfo.QuoteSubscription)
            {
                if (manager.Adapter != null)
                {
                    manager.Quotes.SubscribeSymbolSession(session.Symbol,
                                                          Commission.GenerateSymbolCommission(manager.Adapter, session.Symbol));
                }
                else
                {
                    SystemMonitor.OperationError("Failed to perform data subscription update, since manager adapter not assigned.");
                }

                GeneralHelper.FireAndForget(delegate()
                {// Run an async update of quotes.
                    string market;
                    Quote?quote = _manager.Quotes.GetSingleSymbolQuote(session.Symbol.Name, TimeSpan.FromSeconds(10), out market);
                    if (quote.HasValue)
                    {
                        DataSourceStub.UpdateQuote(session, quote, null);
                    }
                });
            }
            else
            {
                manager.Quotes.UnSubscribeSymbolSession(session.Symbol.Name);
            }
        }
Exemple #4
0
        /// <summary>
        ///
        /// </summary>
        internal bool Initialize(MBTradingConnectionManager manager, MbtQuotes quotesClient)
        {
            SystemMonitor.CheckError(_messageLoopOperator.InvokeRequred == false, "Init must better be called on message loop method.");

            _manager = manager;
            if (_quotesClient != null)
            {
                return(false);
            }

            _quotesClient = quotesClient;
            return(true);
        }
Exemple #5
0
        /// <summary>
        ///
        /// </summary>
        public void UnInitialize()
        {
            try
            {
                if (_orderClient != null)
                {
                    // An exception is generated here, upon trying to unsubscribe these events, so we shall leave them be.
                    // the wrapper class around the actual COM does something and releases too early ??

                    // ALWAYS CONSUME ORDERS EVENTS AND OPERATIONS TROUGH THE _orderClient VARIABLE, NEVER like this "_commManager.OrderClient"

                    _orderClient.OnAccountLoaded -= new _IMbtOrderClientEvents_OnAccountLoadedEventHandler(_ordersClient_OnAccountLoaded);
                    _orderClient.OnBalanceUpdate -= new _IMbtOrderClientEvents_OnBalanceUpdateEventHandler(_ordersClient_OnBalanceUpdate);
                    _orderClient.OnLogonSucceed  -= new _IMbtOrderClientEvents_OnLogonSucceedEventHandler(_ordersClient_OnLogonSucceed);
                    _orderClient.OnHistoryAdded  -= new _IMbtOrderClientEvents_OnHistoryAddedEventHandler(_orderClient_OnHistoryAdded);
                    _orderClient.OnSubmit        -= new _IMbtOrderClientEvents_OnSubmitEventHandler(_orderClient_OnSubmit);
                    _orderClient.OnAcknowledge   -= new _IMbtOrderClientEvents_OnAcknowledgeEventHandler(_orderClient_OnAcknowledge);
                    _orderClient.OnPositionAdded -= new _IMbtOrderClientEvents_OnPositionAddedEventHandler(_orderClient_OnPositionAdded);

                    _orderClient.OnExecute       -= new _IMbtOrderClientEvents_OnExecuteEventHandler(_orderClient_OnExecute);
                    _orderClient.OnReplacePlaced -= new _IMbtOrderClientEvents_OnReplacePlacedEventHandler(_orderClient_OnReplacePlaced);

                    _orderClient = null;
                }

                if (_timer != null)
                {
                    _timer.Dispose();
                    _timer = null;
                }

                if (_commManager != null)
                {
                    _commManager.OnAlertAdded -= new IMbtComMgrEvents_OnAlertAddedEventHandler(_commManager_OnAlertAdded);
                    _commManager = null;
                }
            }
            catch (Exception ex)
            {
                SystemMonitor.OperationError(ex.Message);
            }
            finally
            {
                _orderClient = null;
                _timer       = null;
                _commManager = null;
                _manager     = null;
                _adapter     = null;
            }
        }
        public Quote?GetQuoteUpdate(DataSessionInfo session)
        {
            MBTradingConnectionManager manager = _manager;

            if (manager != null)
            {
                MBTradingQuote.SessionQuoteInformation info = manager.Quotes.GetSymbolSessionInformation(session.Symbol.Name);
                if (info != null)
                {
                    return(info.Quote);
                }
            }

            return(null);
        }
        /// <summary>
        ///
        /// </summary>
        public Symbol?EstablishSymbolUsage(Symbol inputSymbol, TimeSpan timeOut)
        {
            MBTradingConnectionManager manager = _manager;

            if (manager == null || manager.Quotes == null)
            {
                return(null);
            }

            // Filter the baseCurrency trough its name and what symbols we know of.
            Symbol?knownSymbol = _dataSourceStub.MapSymbolToRunningSession(inputSymbol.Name);

            if (knownSymbol.HasValue == false)
            {
                if (_dataSourceStub.IsSuggestedSymbol(inputSymbol) &&
                    string.IsNullOrEmpty(inputSymbol.Group) == false)
                {
                    knownSymbol = inputSymbol;
                }
                else
                {// Upper case input baseCurrency.
                    inputSymbol = new Symbol(inputSymbol.Group, inputSymbol.Name.ToUpper());

                    string symbolMarket;
                    if (manager.Quotes.GetSingleSymbolQuote(inputSymbol.Name, timeOut, out symbolMarket).HasValue)
                    {// BaseCurrency found and established from broker.
                        knownSymbol = new Symbol(symbolMarket, inputSymbol.Name);
                    }
                    else
                    {
                        SystemMonitor.OperationError("Failed to map symbol with this name.");
                        return(null);
                    }
                }
            }

            lock (this)
            {
                if (_usedSymbols.ContainsKey(knownSymbol.Value.Name) == false)
                {
                    _usedSymbols.Add(knownSymbol.Value.Name, knownSymbol.Value);
                }
            }

            return(knownSymbol);
        }
Exemple #8
0
        /// <summary>
        ///
        /// </summary>
        public bool Initialize(MBTradingAdapter adapter, MBTradingConnectionManager manager, MbtComMgr communicationManager)
        {
            SystemMonitor.CheckError(_messageLoopOperator.InvokeRequred == false, "Init must better be called on message loop method.");

            StatusSynchronizationEnabled = true;
            StatusSynchronizationSource  = manager;

            try
            {
                _adapter     = adapter;
                _commManager = communicationManager;
                _orderClient = _commManager.OrderClient;

                // *Never* subscribe to COM events of a property, always make sure to hold the object alive
                // http://www.codeproject.com/Messages/2189754/Re-Losing-COM-events-handler-in-Csharp-client.aspx


                // *** ALWAYS CONSUME ORDERS EVENTS AND OPERATIONS TROUGH THE _orderClient VARIABLE, NEVER like this "_commManager.OrderClient"
                _commManager.OnAlertAdded += new IMbtComMgrEvents_OnAlertAddedEventHandler(_commManager_OnAlertAdded);

                _manager = manager;

                _orderClient.SilentMode = true;

                _timer = new Timer(TimerUpdate, null, 10000, 1000);

                _orderClient.OnAccountLoaded += new _IMbtOrderClientEvents_OnAccountLoadedEventHandler(_ordersClient_OnAccountLoaded);
                _orderClient.OnBalanceUpdate += new _IMbtOrderClientEvents_OnBalanceUpdateEventHandler(_ordersClient_OnBalanceUpdate);
                _orderClient.OnLogonSucceed  += new _IMbtOrderClientEvents_OnLogonSucceedEventHandler(_ordersClient_OnLogonSucceed);
                _orderClient.OnHistoryAdded  += new _IMbtOrderClientEvents_OnHistoryAddedEventHandler(_orderClient_OnHistoryAdded);
                _orderClient.OnSubmit        += new _IMbtOrderClientEvents_OnSubmitEventHandler(_orderClient_OnSubmit);
                _orderClient.OnAcknowledge   += new _IMbtOrderClientEvents_OnAcknowledgeEventHandler(_orderClient_OnAcknowledge);
                _orderClient.OnPositionAdded += new _IMbtOrderClientEvents_OnPositionAddedEventHandler(_orderClient_OnPositionAdded);

                _orderClient.OnExecute       += new _IMbtOrderClientEvents_OnExecuteEventHandler(_orderClient_OnExecute);
                _orderClient.OnReplacePlaced += new _IMbtOrderClientEvents_OnReplacePlacedEventHandler(_orderClient_OnReplacePlaced);
            }
            catch (Exception ex)
            {
                SystemMonitor.OperationError(ex.Message);
                return(false);
            }

            return(true);
        }
Exemple #9
0
        void ConvertQuoteRecord(ref Quote quote, Commission?commission, QUOTERECORD pRec)
        {
            quote.Ask = (0 == pRec.dAsk) ? (decimal?)null : (decimal)pRec.dAsk;
            quote.Bid = (0 == pRec.dBid) ? (decimal?)null : (decimal)pRec.dBid;

            MBTradingConnectionManager manager = _manager;

            if (commission.HasValue && (manager != null && manager.Adapter != null && manager.Adapter.ApplyQuoteCommission))
            {
                commission.Value.ApplyCommissions(manager.Adapter, ref quote);
            }

            quote.High = (0 == pRec.dHigh) ? (decimal?)null : (decimal)pRec.dHigh;
            quote.Low  = (0 == pRec.dLow) ? (decimal?)null : (decimal)pRec.dLow;

            quote.Open   = (decimal)pRec.dOpen;
            quote.Volume = pRec.lVolume;
            quote.Time   = pRec.UTCDateTime;
        }
Exemple #10
0
        protected override bool OnStart(out string operationResultMessage)
        {
            bool constructResult = Construct();

            // MBTrading API is COM, and often fails to release itself, so make sure we shall not hang.
            SeppukuWatchdog.Activate();

            MBTradingConnectionManager manager = _manager;

            if (manager == null)
            {
                operationResultMessage = "Manager not created.";
                return(false);
            }

            base.StatusSynchronizationSource = manager;

            lock (this)
            {
                if (manager.OperationalState != OperationalStateEnum.Initialized &&
                    manager.OperationalState != OperationalStateEnum.Constructed)
                {
                    operationResultMessage = "The MBTrading Adapter can only be started once each application session. Restart the Open Forex Platform to start it again.";
                    return(false);
                }

                ChangeOperationalState(OperationalStateEnum.Initializing);
            }

            if (manager.Login(Username, Password) == false)
            {
                operationResultMessage = "Failed to log in to MBT.";
                SystemMonitor.OperationError(operationResultMessage);
                return(false);
            }
            else
            {
                operationResultMessage = string.Empty;

                StartSources();
                return(true);
            }
        }
        public DataHistoryUpdate GetDataHistoryUpdate(DataSessionInfo session, DataHistoryRequest request)
        {
            MBTradingConnectionManager manager = _manager;

            if (manager != null)
            {
                DataHistoryOperation operation = new DataHistoryOperation(session.Symbol.Name, request);
                if (manager.History.Place(operation) == false)
                {
                    SystemMonitor.OperationError("Failed to place data history operation.");
                    return(null);
                }

                if (operation.CompletionEvent.WaitOne(TimeSpan.FromSeconds(120)) == false)
                {
                    SystemMonitor.OperationError("Data history operation timed out.");
                    return(null);
                }

                return(operation.Responce);
            }

            return(null);
        }
        /// <summary>
        /// 
        /// </summary>
        public void UnInitialize()
        {
            try
            {
                if (_orderClient != null)
                {
                    // An exception is generated here, upon trying to unsubscribe these events, so we shall leave them be.
                    // the wrapper class around the actual COM does something and releases too early ??

                    // ALWAYS CONSUME ORDERS EVENTS AND OPERATIONS TROUGH THE _orderClient VARIABLE, NEVER like this "_commManager.OrderClient"

                    _orderClient.OnAccountLoaded -= new _IMbtOrderClientEvents_OnAccountLoadedEventHandler(_ordersClient_OnAccountLoaded);
                    _orderClient.OnBalanceUpdate -= new _IMbtOrderClientEvents_OnBalanceUpdateEventHandler(_ordersClient_OnBalanceUpdate);
                    _orderClient.OnLogonSucceed -= new _IMbtOrderClientEvents_OnLogonSucceedEventHandler(_ordersClient_OnLogonSucceed);
                    _orderClient.OnHistoryAdded -= new _IMbtOrderClientEvents_OnHistoryAddedEventHandler(_orderClient_OnHistoryAdded);
                    _orderClient.OnSubmit -= new _IMbtOrderClientEvents_OnSubmitEventHandler(_orderClient_OnSubmit);
                    _orderClient.OnAcknowledge -= new _IMbtOrderClientEvents_OnAcknowledgeEventHandler(_orderClient_OnAcknowledge);
                    _orderClient.OnPositionAdded -= new _IMbtOrderClientEvents_OnPositionAddedEventHandler(_orderClient_OnPositionAdded);

                    _orderClient.OnExecute -= new _IMbtOrderClientEvents_OnExecuteEventHandler(_orderClient_OnExecute);
                    _orderClient.OnReplacePlaced -= new _IMbtOrderClientEvents_OnReplacePlacedEventHandler(_orderClient_OnReplacePlaced);

                    _orderClient = null;
                }

                if (_timer != null)
                {
                    _timer.Dispose();
                    _timer = null;
                }

                if (_commManager != null)
                {
                    _commManager.OnAlertAdded -= new IMbtComMgrEvents_OnAlertAddedEventHandler(_commManager_OnAlertAdded);
                    _commManager = null;
                }
            }
            catch (Exception ex)
            {
                SystemMonitor.OperationError(ex.Message);
            }
            finally
            {
                _orderClient = null;
                _timer = null;
                _commManager = null;
                _manager = null;
                _adapter = null;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        public bool Initialize(MBTradingAdapter adapter, MBTradingConnectionManager manager, MbtComMgr communicationManager)
        {
            SystemMonitor.CheckError(_messageLoopOperator.InvokeRequred == false, "Init must better be called on message loop method.");

            StatusSynchronizationEnabled = true;
            StatusSynchronizationSource = manager;

            try
            {
                _adapter = adapter;
                _commManager = communicationManager;
                _orderClient = _commManager.OrderClient;

                // *Never* subscribe to COM events of a property, always make sure to hold the object alive
                // http://www.codeproject.com/Messages/2189754/Re-Losing-COM-events-handler-in-Csharp-client.aspx

                // *** ALWAYS CONSUME ORDERS EVENTS AND OPERATIONS TROUGH THE _orderClient VARIABLE, NEVER like this "_commManager.OrderClient"
                _commManager.OnAlertAdded += new IMbtComMgrEvents_OnAlertAddedEventHandler(_commManager_OnAlertAdded);

                _manager = manager;

                _orderClient.SilentMode = true;

                _timer = new Timer(TimerUpdate, null, 10000, 1000);

                _orderClient.OnAccountLoaded += new _IMbtOrderClientEvents_OnAccountLoadedEventHandler(_ordersClient_OnAccountLoaded);
                _orderClient.OnBalanceUpdate += new _IMbtOrderClientEvents_OnBalanceUpdateEventHandler(_ordersClient_OnBalanceUpdate);
                _orderClient.OnLogonSucceed += new _IMbtOrderClientEvents_OnLogonSucceedEventHandler(_ordersClient_OnLogonSucceed);
                _orderClient.OnHistoryAdded += new _IMbtOrderClientEvents_OnHistoryAddedEventHandler(_orderClient_OnHistoryAdded);
                _orderClient.OnSubmit += new _IMbtOrderClientEvents_OnSubmitEventHandler(_orderClient_OnSubmit);
                _orderClient.OnAcknowledge += new _IMbtOrderClientEvents_OnAcknowledgeEventHandler(_orderClient_OnAcknowledge);
                _orderClient.OnPositionAdded += new _IMbtOrderClientEvents_OnPositionAddedEventHandler(_orderClient_OnPositionAdded);

                _orderClient.OnExecute += new _IMbtOrderClientEvents_OnExecuteEventHandler(_orderClient_OnExecute);
                _orderClient.OnReplacePlaced += new _IMbtOrderClientEvents_OnReplacePlacedEventHandler(_orderClient_OnReplacePlaced);

            }
            catch (Exception ex)
            {
                SystemMonitor.OperationError(ex.Message);
                return false;
            }

            return true;
        }
        bool Construct()
        {
            if (_manager != null)
            {
                return false;
            }

            StatusSynchronizationEnabled = true;

            lock (this)
            {
                _manager = new MBTradingConnectionManager(this);
                if (_manager.Quotes != null)
                {
                    _manager.Quotes.QuoteUpdateEvent += new MBTradingQuote.QuoteUpdateDelegate(Quotes_QuoteUpdateEvent);
                }

                DataSourceStub.Initialize(this);
                OrderExecutionStub.Initialize(_manager.Orders);

                foreach (string symbol in EquitiesSymbols)
                {
                    DataSourceStub.AddSuggestedSymbol(new Symbol(string.Empty, symbol));
                }

                foreach (string symbol in ForexSymbols)
                {
                    DataSourceStub.AddSuggestedSymbol(new Symbol("FX", symbol));
                }
            }

            return true;
        }
 protected void DisposeManager()
 {
     if (_manager != null)
     {
         _manager.Dispose();
         _manager = null;
     }
 }
Exemple #16
0
        /// <summary>
        /// Make sure to call on Invoke'd thread.
        /// </summary>
        /// <param name="account"></param>
        void PerformUpdate(MbtAccount account, bool updateAccount, bool updateOrders, bool updatePositions)
        {
            //SystemMonitor.CheckError(_messageLoopOperator.InvokeRequred == false, "Invoke must not be required in baseMethod call.");

            MbtOrderClient             orderClient = _orderClient;
            MBTradingConnectionManager manager     = _manager;
            MBTradingQuote             quotes      = null;

            if (orderClient == null || manager == null)
            {
                return;
            }

            quotes = manager.Quotes;
            if (quotes == null)
            {
                return;
            }

            AccountInfo info;
            Dictionary <string, OrderInfo> pendingOrderInfos = new Dictionary <string, OrderInfo>();
            List <PositionInfo>            positionsInfos    = new List <PositionInfo>();

            lock (this)
            {
                if (updateOrders)
                {
                    // We need to send up only the latest of each orders histories, since prev ones are for previous states.
                    foreach (MbtOrderHistory history in _orderClient.OrderHistories)
                    {
                        Order.UpdateTypeEnum updateType;
                        OrderInfo?           orderInfo = ConvertToOrderInfo(history, out updateType);
                        if (orderInfo.HasValue)
                        {
                            pendingOrderInfos[orderInfo.Value.Id] = orderInfo.Value;
                        }
                    }

                    // Make sure open orders orderInfo is always on top.
                    foreach (MbtOpenOrder pOrd in _orderClient.OpenOrders)
                    {
                        OrderInfo?orderInfo = ConvertToOrderInfo(pOrd);
                        if (orderInfo.HasValue)
                        {
                            pendingOrderInfos[orderInfo.Value.Id] = orderInfo.Value;
                        }
                    }
                }

                if (updatePositions)
                {
                    foreach (MbtPosition position in _orderClient.Positions)
                    {
                        PositionInfo?positionInfo = ConvertToPositionInfo(position);
                        if (positionInfo.HasValue)
                        {
                            positionsInfos.Add(positionInfo.Value);
                        }
                    }
                }

                if (_accountInfo.HasValue)
                {
                    info = _accountInfo.Value;
                }
                else
                {
                    info      = new AccountInfo();
                    info.Guid = Guid.NewGuid();
                }

                ConvertAccount(account, ref info);

                _accountInfo = info;
            }

            MBTradingAdapter adapter = _adapter;

            if (adapter != null)
            {
                OrderExecutionSourceStub stub = adapter.OrderExecutionSourceStub;
                if (stub != null)
                {
                    if (updateAccount)
                    {
                        stub.UpdateAccountInfo(_accountInfo.Value);
                    }

                    if (updateOrders)
                    {
                        stub.UpdateOrdersInfo(_accountInfo.Value,
                                              GeneralHelper.GenerateSingleValueArray <Order.UpdateTypeEnum>(pendingOrderInfos.Count, Order.UpdateTypeEnum.Update),
                                              GeneralHelper.EnumerableToArray <OrderInfo>(pendingOrderInfos.Values));
                    }

                    if (updatePositions)
                    {
                        stub.UpdatePositionsInfo(_accountInfo.Value, positionsInfos.ToArray());
                    }
                }
            }
        }
        /// <summary>
        /// 
        /// </summary>
        internal bool Initialize(MBTradingConnectionManager manager, MbtQuotes quotesClient)
        {
            SystemMonitor.CheckError(_messageLoopOperator.InvokeRequred == false, "Init must better be called on message loop method.");

            _manager = manager;
            if (_quotesClient != null)
            {
                return false;
            }

            _quotesClient = quotesClient;
            return true;
        }