/// <summary>
        ///
        /// </summary>
        public bool UnSubscribeSymbolSession(string symbol)
        {
            if (IsInitialized == false)
            {
                return(false);
            }

            lock (this)
            {
                if (_sessions.Remove(symbol) == false)
                {
                    return(false);
                }
            }

            bool result = true;

            _messageLoopOperator.Invoke(delegate()
            {
                MbtQuotes client = _quotesClient;
                if (client == null)
                {
                    result = false;
                    return;
                }

                client.UnadviseSymbol(this, symbol, (int)enumQuoteServiceFlags.qsfLevelOne);
            });

            return(result);
        }
Esempio n. 2
0
        bool OrderExecutionSourceStub.IImplementation.ExecuteMarketOrder(AccountInfo accountInfo, Symbol symbol, OrderTypeEnum orderType, int volume, Decimal?allowedSlippage, Decimal?desiredPrice,
                                                                         Decimal?takeProfit, Decimal?stopLoss, string comment, out OrderInfo?orderPlaced, out string operationResultMessage)
        {
            string operationResultMessageCopy = string.Empty;

            PlaceOrderOperation operation = null;

            GeneralHelper.GenericReturnDelegate <bool> operationDelegate = delegate()
            {
                string submitResult = DoSubmitOrder(accountInfo, symbol, orderType, volume, allowedSlippage, desiredPrice,
                                                    takeProfit, stopLoss, comment, out operation, out operationResultMessageCopy);

                return(string.IsNullOrEmpty(submitResult) == false);
            };

            orderPlaced = null;

            object result;

            if (_messageLoopOperator.Invoke(operationDelegate, TimeSpan.FromSeconds(5), out result) == false)
            {// Timed out.
                operationResultMessage = "Timeout placing order.";
                return(false);
            }

            if ((bool)result == false)
            {// Operation error.
                operationResultMessage = operationResultMessageCopy;
                return(false);
            }

            object operationResult;

            if (operation.WaitResult <object>(TimeSpan.FromSeconds(60), out operationResult) == false)
            {
                operationResultMessage = "Order place timeout.";
                return(false);
            }

            orderPlaced = (OrderInfo?)operationResult;

            if (operationResult == null || orderPlaced.HasValue == false)
            {
                operationResultMessage = "Order place failed.";
                return(false);
            }

            // Operation OK.
            operationResultMessage = string.Empty;
            orderPlaced            = operation.OrderResponce;

            if (orderPlaced.HasValue == false)
            {
                return(false);
            }

            return(true);
        }
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public bool Login(string username, string password)
        {
            bool result = false;

            if (OperationalState == OperationalStateEnum.Disposed)
            {
                return(false);
            }

            _messageLoopOperator.Invoke(delegate()
            {
                // This is a slow blocking call, make sure to execute outside of lock.
                MbtComMgr manager     = new MbtComMgr();
                _communicationManager = manager;
                //_communicationManager.OnLogonSucceed += new IMbtComMgrEvents_OnLogonSucceedEventHandler(_communicationManager_OnLogonSucceed);

                _orderClient            = _communicationManager.OrderClient;
                _orderClient.SilentMode = true;

                //_quotes.Initialize(_communicationManager.Quotes);
                //_history.Initialize(_communicationManager.HistMgr);
                ///_orders.Initialize(_adapter, this, _communicationManager);

                //_communicationManager.OnAlertAdded += new IMbtComMgrEvents_OnAlertAddedEventHandler(_communicationManager_OnAlertAdded);
                _communicationManager.EnableSplash(false);

                ChangeOperationalState(OperationalStateEnum.Initialized);
                _communicationManager.EnableSplash(false);
                _communicationManager.SilentMode = true;

                result = _communicationManager.DoLogin(HostId, username, password, "");
            }, TimeSpan.FromSeconds(25));

            return(result);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="symbol">Pass empty or null to extract all positions.</param>
        public List <PositionInfo> GetPositions(/*string requestedSymbol*/)
        {
            List <PositionInfo> result = new List <PositionInfo>();

            GeneralHelper.DefaultDelegate delegateInstance = delegate()
            {
                try
                {
                    result = Managed_ProcessPositions();
                }
                catch (Exception ex)
                {
                    SystemMonitor.OperationError("Failed to process FXCM positions.", ex);
                }
            };

            BackgroundMessageLoopOperator messageLoopOperator = _messageLoopOperator;

            if (messageLoopOperator != null)
            {
                messageLoopOperator.Invoke(delegateInstance, TimeSpan.FromSeconds(60));
            }

            return(result);
        }
        /// <summary>
        /// Perform logout.
        /// </summary>
        public bool Logout()
        {
            ChangeOperationalState(OperationalStateEnum.NotOperational);

            GeneralHelper.DefaultDelegate del = delegate()
            {
                if (_core != null && _desk.IsLoggedIn())
                {
                    Managed_Unsubscribe();

                    _desk.Logout();

                    _desk = null;
                    _core = null;
                }
            };

            BackgroundMessageLoopOperator messageLoopOperator = _messageLoopOperator;

            if (messageLoopOperator == null || messageLoopOperator.Invoke(del, TimeSpan.FromSeconds(180)) == false)
            {
                return(false);
            }

            return(true);
        }
        /// <summary>
        ///
        /// </summary>
        public List <AccountInfo> GetAvailableAccounts(int advisedDecimalsPrecision)
        {
            List <AccountInfo> result = new List <AccountInfo>();

            TradeDeskAut desk = _desk;

            if (desk == null)
            {
                return(result);
            }

            GeneralHelper.DefaultDelegate delegateInstance = delegate()
            {
                try
                {
                    // Perform update.
                    TableAut accountsTable = (FXCore.TableAut)desk.FindMainTable("accounts");
                    foreach (RowAut item in (RowsEnumAut)accountsTable.Rows)
                    {
                        string id = (string)item.CellValue("AccountID");

                        if (string.IsNullOrEmpty(id))
                        {
                            SystemMonitor.OperationWarning("Account with null/empty id found.");
                            continue;
                        }

                        AccountInfo info = new AccountInfo();
                        // Have the accounts with default empty Guids.
                        //info.Guid = Guid.Empty;
                        info.Id = id;

                        info.Name       = "FXCM." + (string)item.CellValue("AccountName");
                        info.Balance    = Math.Round(new decimal((double)item.CellValue("Balance")), advisedDecimalsPrecision);
                        info.Equity     = Math.Round(new decimal((double)item.CellValue("Equity")), advisedDecimalsPrecision);
                        info.Margin     = Math.Round(new decimal((double)item.CellValue("UsableMargin")), advisedDecimalsPrecision);
                        info.Profit     = Math.Round(new decimal((double)item.CellValue("GrossPL")), advisedDecimalsPrecision);
                        info.FreeMargin = Math.Round(new decimal((double)item.CellValue("UsableMargin")), advisedDecimalsPrecision);
                        info.Company    = "FXCM";
                        info.Server     = this._serviceUrl;

                        result.Add(info);
                    }
                }
                catch (Exception ex)
                {
                    SystemMonitor.OperationError(GeneralHelper.GetExceptionMessage(ex));
                }
            };

            BackgroundMessageLoopOperator messageLoopOperator = _messageLoopOperator;

            if (messageLoopOperator != null)
            {
                messageLoopOperator.Invoke(delegateInstance, TimeSpan.FromSeconds(60));
            }

            return(result);
        }
        /// <summary>
        /// Perform a login.
        /// </summary>
        public bool Login(string username, string password, string serviceUrl, string accountType, out string operationResultMessage)
        {
            _messageLoopOperator.Start();

            if (OperationalState != OperationalStateEnum.Initialized &&
                OperationalState != OperationalStateEnum.Initializing &&
                OperationalState != OperationalStateEnum.Constructed)
            {
                operationResultMessage = "Login already started.";
                return(false);
            }

            this._serviceUrl = serviceUrl;

            string operationResultMessageCopy = string.Empty;

            ChangeOperationalState(OperationalStateEnum.Initializing);

            object result = false;

            GeneralHelper.GenericReturnDelegate <bool> del = delegate()
            {
                if (_core == null)
                {
                    _core = new FXCore.CoreAutClass();
                    _desk = (FXCore.TradeDeskAut)_core.CreateTradeDesk("trader");
                }

                try
                {
                    _desk.Login(username, password, serviceUrl, accountType);

                    Managed_Subscribe();

                    SystemMonitor.Report("FXCM Service subscribed.");
                    ChangeOperationalState(OperationalStateEnum.Operational);
                }
                catch (Exception exception)
                {
                    operationResultMessageCopy = "Failed to log in [" + exception.Message + "].";
                    SystemMonitor.OperationError(operationResultMessageCopy);
                    ChangeOperationalState(OperationalStateEnum.NotOperational);
                }

                return(_desk.IsLoggedIn());
            };

            if (_messageLoopOperator.Invoke(del, TimeSpan.FromSeconds(180), out result) == false || (bool)result == false)
            {
                ChangeOperationalState(OperationalStateEnum.NotOperational);
                operationResultMessage = operationResultMessageCopy;
                return(false);
            }

            operationResultMessage = operationResultMessageCopy;
            return((bool)result);
        }
Esempio n. 8
0
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public bool Login(string username, string password)
        {
            bool result = false;

            if (OperationalState != OperationalStateEnum.Initialized &&
                OperationalState != OperationalStateEnum.Initializing &&
                OperationalState != OperationalStateEnum.Constructed)
            {
                return(false);
            }

            _messageLoopOperator.Start();

            _messageLoopOperator.Invoke(delegate()
            {
                try
                {
                    // *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

                    if (_communicationManager == null)
                    {
                        // This is a slow blocking call, make sure to execute outside of lock.
                        MbtComMgr manager     = new MbtComMgr();
                        _communicationManager = manager;
                        _communicationManager.OnLogonSucceed += new IMbtComMgrEvents_OnLogonSucceedEventHandler(_communicationManager_OnLogonSucceed);
                    }

                    lock (this)
                    {
                        _quotes.Initialize(this, _communicationManager.Quotes);
                        _history.Initialize(_communicationManager.HistMgr);
                        _orders.Initialize(_adapter, this, _communicationManager);

                        _communicationManager.OnAlertAdded += new IMbtComMgrEvents_OnAlertAddedEventHandler(_communicationManager_OnAlertAdded);
                        _communicationManager.EnableSplash(false);
                    }

                    ChangeOperationalState(OperationalStateEnum.Initialized);
                    _communicationManager.EnableSplash(false);
                    _communicationManager.SilentMode = true;

                    result = _communicationManager.DoLogin(HostId, username, password, "");
                }
                catch (Exception ex)
                {
                    SystemMonitor.OperationError(ex.Message);
                    result = false;
                    throw;
                }
            }, TimeSpan.FromSeconds(25));

            return(result);
        }
Esempio n. 9
0
        /// <summary>
        /// Submit an order.
        /// </summary>
        public string SubmitOrder(AccountInfo account, Symbol symbol, OrderTypeEnum orderType, int volume,
                                  decimal?allowedSlippage, decimal?desiredPrice, decimal?takeProfit, decimal?stopLoss,
                                  string comment, out string operationResultMessage)
        {
            operationResultMessage = string.Empty;
            string operationResultMessageCopy = string.Empty;
            object orderId, psd;
            bool   isBuy = OrderInfo.TypeIsBuy(orderType);

            GeneralHelper.GenericReturnDelegate <string> operationDelegate = delegate()
            {
                _manager.Desk.OpenTrade(account.Id, symbol.Name, isBuy,
                                        _adapter.DefaultLotSize, (double)desiredPrice.Value,
                                        (string)_adapter.GetInstrumentData(symbol.Name, "QuoteID"),
                                        0,
                                        stopLoss.HasValue ? (double)stopLoss.Value : 0,
                                        takeProfit.HasValue ? (double)takeProfit.Value : 0,
                                        0, out orderId, out psd);

                return(orderId.ToString());
            };

            object result;

            if (_messageLoopOperator.Invoke(operationDelegate, TimeSpan.FromSeconds(8), out result) == false)
            {            // Timed out.
                operationResultMessage = "Timeout submiting order.";
                return(null);
            }

            if (string.IsNullOrEmpty((string)result))
            {            // Operation error.
                operationResultMessage = operationResultMessageCopy;
                return(null);
            }

            // Return the ID of the submitted order.
            return((string)result);
        }
        /// <summary>
        ///
        /// </summary>
        public List <DataBar> GetHistory(string forexPair, string period, DateTime lowerBound, DateTime upperBound)
        {
            bool           keepIterating          = true;
            List <DataBar> candlestickHistoryList = new List <DataBar>();

            GeneralHelper.DefaultDelegate delegateInstance = delegate()
            {
                TradeDeskAut desk = _desk;
                if (desk == null)
                {
                    return;
                }

                FXCore.IMarketRateEnumAut japaneseCandlestick;
                while (keepIterating)
                {
                    japaneseCandlestick = (FXCore.IMarketRateEnumAut)desk.GetPriceHistoryUTC(forexPair, period, lowerBound, upperBound, -1, false, true);

                    foreach (FXCore.IMarketRateAut marketRate in japaneseCandlestick)
                    {
                        DataBar dataBar = new DataBar(marketRate.StartDate, new decimal(marketRate.AskOpen),
                                                      new decimal(marketRate.AskHigh), new decimal(marketRate.AskLow), new decimal(marketRate.AskClose), 0);

                        candlestickHistoryList.Add(dataBar);

                        lowerBound = marketRate.StartDate;
                    }

                    Thread.Sleep(100);

                    int i = japaneseCandlestick.Size;

                    keepIterating = i > 1 && upperBound.CompareTo(lowerBound) >= 0;

                    lowerBound.AddTicks(1);
                }
            };

            BackgroundMessageLoopOperator messageLoopOperator = _messageLoopOperator;

            if (messageLoopOperator != null)
            {
                messageLoopOperator.Invoke(delegateInstance, TimeSpan.FromSeconds(60));
            }

            return(candlestickHistoryList);
        }
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public bool Login(string username, string password, string serviceUrl, string accountType)
        {
            if (OperationalState != OperationalStateEnum.Initialized &&
                OperationalState != OperationalStateEnum.Initializing &&
                OperationalState != OperationalStateEnum.Constructed)
            {
                return(false);
            }

            object result = false;

            GeneralHelper.GenericReturnDelegate <bool> del = delegate()
            {
                if (_core == null)
                {
                    _core = new FXCore.CoreAutClass();
                    _desk = (FXCore.TradeDeskAut)_core.CreateTradeDesk("trader");
                }

                lock (this)
                {
                    _orders.Initialize(_adapter, this);
                }

                ChangeOperationalState(OperationalStateEnum.Initializing);

                try
                {
                    _desk.Login(username, password, serviceUrl, accountType);
                    Subscribe();
                    ChangeOperationalState(OperationalStateEnum.Operational);
                }
                catch (Exception exception)
                {
                    SystemMonitor.OperationError("Failed to log in [" + exception.Message + "].");
                    ChangeOperationalState(OperationalStateEnum.NotOperational);
                }

                return(_desk.IsLoggedIn());
            };

            _messageLoopOperator.Invoke(del, TimeSpan.FromSeconds(180), out result);

            return((bool)result);
        }
Esempio n. 12
0
        public bool StartOperation(OperationInformation operationInformation)
        {
            DataHistoryOperation operation = (DataHistoryOperation)operationInformation;

            bool result = true;

            _messageLoopOperator.Invoke(delegate()
            {// Placing the request on the stolen main application thread, since we need the requestMessage pump for this to work properly.
                MbtHistMgr historyClient = _historyClient;
                if (historyClient == null)
                {
                    result = false;
                    return;
                }

                if (operation.Request.IsMinuteBased == false && operation.Request.IsDayBased == false)
                {
                    result = false;
                    return;
                }

                int?time = GetConvertedTime(operation);

                if (operation.Request.IsDayBased)
                {
                    MbtHistDayBar histBar;
                    histBar = historyClient.CreateHistDayBar();
                    histBar.Clear();
                    histBar.SendRequest(operation.Symbol, Int32.Parse(operation.Id), time.Value,
                                        new DateTime(0), new DateTime(0), operation.Request.MaxValuesRetrieved.HasValue ? operation.Request.MaxValuesRetrieved.Value : int.MaxValue, true);
                }
                else if (operation.Request.IsMinuteBased)
                {
                    MbtHistMinBar histBar = historyClient.CreateHistMinBar();
                    histBar.Clear();
                    histBar.SendRequest(operation.Symbol, Int32.Parse(operation.Id), time.Value,
                                        new DateTime(0), new DateTime(0), operation.Request.MaxValuesRetrieved.HasValue ? operation.Request.MaxValuesRetrieved.Value : int.MaxValue, true);
                }
            });

            return(result);
        }
        public object GetInstrumentData(string forexPair, string columnName)
        {
            object columnData = null;

            GeneralHelper.DefaultDelegate delegateInstance = delegate()
            {
                TradeDeskAut desk = _desk;
                if (desk == null)
                {
                    return;
                }

                FXCore.TableAut offersTable = (FXCore.TableAut)desk.FindMainTable("offers");
                if (offersTable == null)
                {
                    return;
                }

                switch (forexPair)
                {
                case "EUR/USD":
                    columnData = offersTable.CellValue(1, columnName);
                    break;

                case "USD/JPY":
                    columnData = offersTable.CellValue(2, columnName);
                    break;

                case "GBP/USD":
                    columnData = offersTable.CellValue(3, columnName);
                    break;

                case "USD/CHF":
                    columnData = offersTable.CellValue(4, columnName);
                    break;

                case "EUR/CHF":
                    columnData = offersTable.CellValue(5, columnName);
                    break;

                case "AUD/USD":
                    columnData = offersTable.CellValue(6, columnName);
                    break;

                case "USD/CAD":
                    columnData = offersTable.CellValue(7, columnName);
                    break;

                case "NZD/USD":
                    columnData = offersTable.CellValue(8, columnName);
                    break;

                case "EUR/GBP":
                    columnData = offersTable.CellValue(9, columnName);
                    break;

                case "EUR/JPY":
                    columnData = offersTable.CellValue(10, columnName);
                    break;

                case "GBP/JPY":
                    columnData = offersTable.CellValue(11, columnName);
                    break;

                case "GBP/CHF":
                    columnData = offersTable.CellValue(12, columnName);
                    break;
                }
            };

            BackgroundMessageLoopOperator messageLoopOperator = _messageLoopOperator;

            if (messageLoopOperator != null)
            {
                messageLoopOperator.Invoke(delegateInstance, TimeSpan.FromSeconds(60));
            }

            return(columnData);
        }
        /// <summary>
        ///
        /// </summary>
        public OrderInfo?SubmitOrder(AccountInfo accountInfo, Symbol symbol, OrderTypeEnum orderType, int volume,
                                     decimal?allowedSlippage, decimal?desiredPrice, decimal?takeProfit, decimal?stopLoss, out string operationResultMessage)
        {
            OrderInfo?order = null;

            operationResultMessage = string.Empty;
            string operationResultMessageCopy = string.Empty;

            GeneralHelper.DefaultDelegate delegateInstance = delegate()
            {
                try
                {
                    TradeDeskAut desk = _desk;
                    if (desk == null)
                    {
                        return;
                    }

                    bool   isBuy     = OrderInfo.TypeIsBuy(orderType);
                    double realValue = isBuy ? (double)GetInstrumentData(symbol.Name, "Ask") : (double)GetInstrumentData(symbol.Name, "Bid");

                    object orderId, psd;
                    object ocoStopOrderId = null, ocoProfitOrderId = null;

                    desk.CreateFixOrder(desk.FIX_OPENMARKET,
                                        "",
                                        realValue,
                                        realValue,
                                        (string)GetInstrumentData(symbol.Name, "QuoteID"),
                                        accountInfo.Id,
                                        symbol.Name,
                                        isBuy,
                                        volume,
                                        "",
                                        out orderId,
                                        out psd);

                    order = new OrderInfo(orderId.ToString(), symbol, orderType,
                                          OrderStateEnum.Executed, volume, new decimal(realValue), null,
                                          null, null, null, null, null, null, null, null, null, "ok", "1");

                    //check bid value...
                    if (stopLoss.HasValue)
                    {
                        double dValue = Decimal.ToDouble(stopLoss.Value);

                        desk.CreateFixOrder(desk.FIX_ENTRYSTOP,
                                            "",
                                            dValue,
                                            dValue,
                                            (string)GetInstrumentData(symbol.Name, "QuoteID"),
                                            accountInfo.Id,
                                            symbol.Name,
                                            !isBuy,
                                            volume,
                                            "",
                                            out ocoStopOrderId,
                                            out psd);
                    }

                    if (takeProfit.HasValue)
                    {
                        double dValue = Decimal.ToDouble(takeProfit.Value);

                        desk.CreateFixOrder(desk.FIX_ENTRYLIMIT,
                                            "",
                                            dValue,
                                            dValue,
                                            (string)GetInstrumentData(symbol.Name, "QuoteID"),
                                            accountInfo.Id,
                                            symbol.Name,
                                            !isBuy,
                                            volume,
                                            "",
                                            out ocoProfitOrderId,
                                            out psd);
                    }

                    //Create OCO.
                    if (stopLoss.HasValue && takeProfit.HasValue)
                    {
                        bool creationOk = true;
                        FXCore.OrdersIDEnumAut group = new FXCore.OrdersIDEnumAut();
                        group.Add((string)ocoProfitOrderId);
                        group.Add((string)ocoStopOrderId);
                        object _result = null;
                        object ocoid   = null;
                        desk.CreateOCO(group, out _result, out ocoid);

                        FXCore.OrdersBatchResultEnumAut result = (FXCore.OrdersBatchResultEnumAut)_result;
                        for (int i = 1; i <= result.Count; i++)
                        {
                            FXCore.OrderBatchResultAut res = (FXCore.OrderBatchResultAut)result.Item(i);
                            creationOk = creationOk && res.Success;

                            if (!creationOk)
                            {
                                //Ups throw an exception!!!  But what about the current order.
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    operationResultMessageCopy = GeneralHelper.GetExceptionMessage(ex);
                    SystemMonitor.OperationError(operationResultMessageCopy);
                }
            };

            BackgroundMessageLoopOperator messageOperator = _messageLoopOperator;

            if (messageOperator != null)
            {
                messageOperator.Invoke(delegateInstance, TimeSpan.FromSeconds(120));
            }
            operationResultMessage = operationResultMessageCopy;

            return(order);
        }