Beispiel #1
0
        /// <summary>
        /// Open orders in position management
        /// </summary>
        public bool CancelPending(string openOrderId, out string operationResultMessage)
        {
            ISourceOrderExecution provider = _orderProvider;

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

            Order order = provider.TradeEntities.GetOrderById(openOrderId);

            if (order.State != OrderStateEnum.Submitted)
            {
                operationResultMessage = "Order state not 'submitted', so not able to cancel as a pending order";
                return(false);
            }

            ActiveOrder activeOrder = order as ActiveOrder;

            if (null != activeOrder)
            {
                return(activeOrder.Cancel(out operationResultMessage));
            }

            PassiveOrder passiveOrder = order as PassiveOrder;

            if (null != passiveOrder)
            {
                return(passiveOrder.CloseOrCancel(null, null, out operationResultMessage));
            }

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

            operationResultMessage = string.Empty;
            executionInfo          = PositionExecutionInfo.Empty;

            ISourceOrderExecution provider = _provider;

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

            _isProcessing = true;

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

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

            _isProcessing = false;

            return(result);
        }
        public bool RemoveProvider(ISourceOrderExecution provider)
        {
            bool result = _providers.Remove(provider);

            UpdateUI();
            return(result);
        }
Beispiel #4
0
        /// <summary>
        /// This may contain a few operations on active orders, in order to match the rule "no opposing active orders"
        /// </summary>
        public virtual string ExecuteMarketBalanced(int volumeModification, decimal?desiredPrice, decimal?slippage, TimeSpan timeOut,
                                                    out PositionExecutionInfo executionInfo, out string operationResultMessage)
        {
            executionInfo = PositionExecutionInfo.Empty;

            ISourceOrderExecution provider = _orderProvider;

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

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

            traceMessage += GenerateConditionsInfo();

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

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

            return(string.Empty);
        }
        /// <summary>
        ///
        /// </summary>
        protected override void OnRecalculateParameters(ISourceOrderExecution provider, bool fullRecalculation)
        {
            SystemMonitor.CheckError(provider.SupportsActiveOrderManagement, "Wrong position type for this provider.");

            Order[] orders = provider.TradeEntities.GetOrdersBySymbol(Symbol);
            lock (this)
            {
                _info.Volume            = 0;
                _info.PendingBuyVolume  = 0;
                _info.PendingSellVolume = 0;
                _info.Result            = 0;

                foreach (ActiveOrder order in GeneralHelper.SafeChildTypeIteration <Order, ActiveOrder>(orders))
                {
                    if (order.State == OrderStateEnum.Executed)
                    {
                        _info.Volume += order.CurrentDirectionalVolume;
                        _info.Result += order.GetResult(Order.ResultModeEnum.Currency);
                    }
                    else if (order.State == OrderStateEnum.Submitted)
                    {
                        if (order.IsBuy)
                        {
                            _info.PendingBuyVolume += order.CurrentVolume;
                        }
                        else
                        {
                            _info.PendingSellVolume += order.CurrentVolume;
                        }
                    }
                }
            }
        }
Beispiel #6
0
        public virtual void Dispose()
        {
            //if (_tradeEntities != null)
            //{
            //    _tradeEntities.UnInitialize();
            //    _tradeEntities = null;
            //}

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

            _dataDelivery = null;
            _manager      = null;

            if (_provider != null)
            {
                _provider.AccountInfoUpdateEvent       -= new AccountInfoUpdateDelegate(_provider_AccountInfoUpdateEvent);
                _provider.OperationalStateChangedEvent -= new OperationalStateChangedDelegate(_provider_OperationalStatusChangedEvent);

                _provider = null;
            }
        }
Beispiel #7
0
        /// <summary>
        /// Will create the corresponding order, based to the passed in order information.
        /// Used to create corresponding orders to ones already existing in the platform.
        /// </summary>
        public override bool AdoptInfo(OrderInfo info)
        {
            base.AdoptInfo(info);

            ISourceOrderExecution executionProvider = _executionProvider;

            if (executionProvider == null || SessionInfo.HasValue == false)
            {
                return(false);
            }

            decimal lotSize = SessionInfo.Value.LotSize;

            lock (this)
            {
                //if (orderInfo.CurrentProfit.HasValue)
                //{
                //    _currentRawResult = orderInfo.CurrentProfit.Value / lotSize;
                //}
                //else
                //{
                //    _currentRawResult = 0;
                //}

                if (info.CurrentProfit.HasValue)
                {
                    _orderMaximumResultAchieved = info.CurrentProfit.Value / lotSize;
                }

                _localOpenTime = null;
            }

            return(true);
        }
        /// <summary>
        ///
        /// </summary>
        ActiveOrder ObtainManipulationOrder(ISourceOrderExecution provider, OrderTypeEnum orderType, int minVolume,
                                            out bool suitableOrdersAvailable)
        {
            suitableOrdersAvailable = false;

            lock (provider.TradeEntities)
            {
                foreach (ActiveOrder activeOrder in provider.TradeEntities.GetOrdersByStateUnsafe(OrderStateEnum.Executed))
                {
                    if (activeOrder.Symbol == Symbol &&
                        minVolume <= activeOrder.CurrentVolume &&
                        (activeOrder.Type == orderType))
                    {// Found a opposing order, close it.
                        suitableOrdersAvailable = true;

                        lock (_activeSelectedOrders)
                        {
                            if (_activeSelectedOrders.Contains(activeOrder) == false)
                            {// Only if this order is not currently processed, take it for processing.
                                _activeSelectedOrders.Add(activeOrder);
                                return(activeOrder);
                            }
                        }
                    }
                }
            }

            return(null);
        }
Beispiel #9
0
 /// <summary>
 ///
 /// </summary>
 public virtual void Dispose()
 {
     _manager           = null;
     _executionProvider = null;
     _quoteProvider     = null;
     _dataSourceId      = ComponentId.Empty;
 }
Beispiel #10
0
        public void ClosePosition()
        {
            Position position = this.Position;

            if (position != null)
            {
                ISourceOrderExecution provider = this.Position.OrderExecutionProvider;
                if (provider != null)
                {
                    for (int i = this.WorkingOrderIds.Count - 1; i >= 0; i--)
                    {
                        string orderId = this.WorkingOrderIds[i];

                        if (!string.IsNullOrEmpty(orderId))
                        {
                            Order order = provider.TradeEntities.GetOrderById(orderId);

                            if (order != null)
                            {
                                order.Close();
                            }
                        }
                    }
                    this.WorkingOrderIds.Clear();
                }
            }
        }
        /// <summary>
        /// 
        /// </summary>
        protected override string OnExecuteMarket(ISourceOrderExecution provider, OrderTypeEnum orderType, int volume, 
            decimal? price, decimal? slippage, decimal? takeProfit, decimal? stopLoss, TimeSpan timeOut,
            out PositionExecutionInfo executionInfo, out string operationResultMessage)
        {
            SystemMonitor.CheckError(provider.SupportsActiveOrderManagement, "Wrong position type for this provider.");

            executionInfo = PositionExecutionInfo.Empty;

            IQuoteProvider quoteProvider = _manager.ObtainQuoteProvider(_dataDelivery.SourceId, Symbol);
            if (quoteProvider == null)
            {
                operationResultMessage = "Failed to establish quote provider for [" + _dataDelivery.SourceId.Name + ", " + Symbol.Name + "].";
                SystemMonitor.Error(operationResultMessage);
                return string.Empty;
            }

            price = ProcessPrice(quoteProvider, orderType, price);

            // New order shall be created.
            ActiveOrder order = new ActiveOrder(_manager, provider, quoteProvider, _dataDelivery.SourceId, Symbol, true);

            OrderInfo? infoReference;

            // Using the extended operationTimeOut to 40 seconds.
            bool result = provider.SynchronousExecute(provider.DefaultAccount.Info, order, _info.Symbol,
                orderType, volume, slippage, price, takeProfit, stopLoss, string.Empty, TimeSpan.FromSeconds(40), out infoReference, out operationResultMessage);

            if (result && infoReference.HasValue)
            {
                OrderInfo infoAssign = infoReference.Value;
                if (infoAssign.Type == OrderTypeEnum.UNKNOWN)
                {
                    infoAssign.Type = orderType;
                }

                if (infoAssign.Volume == int.MinValue
                    || infoAssign.Volume == int.MaxValue)
                {// Volume was not retrieved by integration.
                    infoAssign.Volume = volume;
                }

                if (infoAssign.OpenPrice.HasValue)
                {
                    executionInfo = new PositionExecutionInfo(infoReference.Value.Id, _dataDelivery.SourceId, provider.SourceId, Symbol,
                        infoAssign.Type, infoAssign.OpenPrice.Value, volume, volume,
                        infoAssign.OpenTime, PositionExecutionInfo.ExecutionResultEnum.Success);
                }
                else
                {
                    SystemMonitor.Error("Received execution result, but price not assigned.");
                }

                order.AdoptInfo(infoAssign);

                provider.TradeEntities.AddOrder(order);
                return infoReference.Value.Id;
            }

            return string.Empty;
        }
Beispiel #12
0
        /// <summary>
        ///
        /// </summary>
        void RecalculateParameters(bool fullRecalculation)
        {
            if (fullRecalculation)
            {
                ISourceOrderExecution provider = _orderProvider;
                if (provider == null || Symbol.IsEmpty)
                {
                    Symbol symbol = Symbol;
                    _info        = PositionInfo.Empty;
                    _info.Symbol = symbol;

                    return;
                }

                OnRecalculateParameters(provider, fullRecalculation);
            }

            lock (this)
            {
                if (_price.HasValue)
                {
                    _info.MarketValue = _price * Volume;
                }
            }

            if (UpdateEvent != null)
            {
                UpdateEvent(this);
            }
        }
        /// <summary>
        ///
        /// </summary>
        protected override string OnSubmit(ISourceOrderExecution provider, OrderTypeEnum orderType, int volume, decimal?price,
                                           decimal?slippage, decimal?takeProfit, decimal?stopLoss, out string operationResultMessage)
        {
            SystemMonitor.CheckError(provider.SupportsActiveOrderManagement, "Wrong position type for this provider.");

            IQuoteProvider quotes = _manager.ObtainQuoteProvider(_dataDelivery.SourceId, Symbol);

            ActiveOrder order = new ActiveOrder(_manager, provider, quotes,
                                                _dataDelivery.SourceId, Symbol, true);

            price = ProcessPrice(quotes, orderType, price);

            string id = provider.SubmitOrder(provider.DefaultAccount.Info, order, _info.Symbol,
                                             orderType, volume, slippage, price, takeProfit, stopLoss, string.Empty, out operationResultMessage);

            if (string.IsNullOrEmpty(id))
            {
                return(string.Empty);
            }

            OrderInfo info = new OrderInfo(id, Symbol, orderType, OrderStateEnum.Submitted, volume,
                                           price, null, null, null, null, null, null, null, null, null, null, string.Empty, null);

            order.AdoptInfo(info);
            provider.TradeEntities.AddOrder(order);

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

            ISourceOrderExecution provider = _orderProvider;

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

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

            traceMessage += GenerateConditionsInfo();

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

            _isProcessing = true;

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

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

            _isProcessing = false;

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

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

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

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

            traceMessage += GenerateConditionsInfo();

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

            return(OnSubmit(provider, orderType, volume, price, slippage, takeProfit, stopLoss, out operationResultMessage));
        }
Beispiel #16
0
        /// <summary>
        /// Change order execution related parameters.
        /// </summary>
        /// <param name="remoteStopLoss">Applicable to open or pending orders only, pass null to skip, decimal.MinValue (or zero) to signify no value.</param>
        /// <param name="remoteTakeProfit">Applicable to open or pending orders only, pass null to skip, decimal.MinValue (or zero) to signify no value.</param>
        /// <param name="operationResultMessage">Applicable ONLY to pending order. Pass null otherwise or to leave unchanged.</param>
        /// <returns></returns>
        public bool ModifyRemoteParameters(decimal?remoteStopLoss, decimal?remoteTakeProfit, decimal?remoteTargetOpenPrice,
                                           out string operationResultMessage)
        {
            if (this.IsOpenOrPending == false)
            {
                operationResultMessage = "Wrong order state.";
                return(false);
            }

            if (State != OrderStateEnum.Submitted && remoteTargetOpenPrice.HasValue)
            {
                operationResultMessage = "Wrong order state for this operation (operation only applicable to pending orders).";
                return(false);
            }

            if (remoteStopLoss == StopLoss && TakeProfit == remoteTakeProfit)
            {
                // remoteTargetOpenPrice only counts if you do it on a pending order.
                if ((State == OrderStateEnum.Submitted && remoteTargetOpenPrice == OpenPrice) ||
                    (State != OrderStateEnum.Submitted))
                {// No changes needed.
                    operationResultMessage = "No changes needed.";
                    return(true);
                }
            }

            operationResultMessage = "Session not assigned.";
            ISourceOrderExecution executionProvider = _executionProvider;
            string modifiedId;

            if (executionProvider == null || OrderExecutionProvider.ModifyOrder(Account.Info, this, remoteStopLoss, remoteTakeProfit, remoteTargetOpenPrice,
                                                                                out modifiedId, out operationResultMessage) == false)
            {
                return(false);
            }

            //lock (this)
            //{
            //    //_info.Id = modifiedId;
            //    if (remoteStopLoss.HasValue)
            //    {
            //        _info.StopLoss = remoteStopLoss;
            //    }

            //    if (remoteTakeProfit.HasValue)
            //    {
            //        _info.TakeProfit = remoteTakeProfit;
            //    }

            //    if (remoteTargetOpenPrice.HasValue)
            //    {
            //        _info.OpenPrice = remoteTargetOpenPrice.Value;
            //    }
            //}

            //RaiseOrderUpdatedEvent(UpdateTypeEnum.Modified);

            return(true);
        }
Beispiel #17
0
 /// <summary>
 ///
 /// </summary>
 public PassiveOrder(ISourceManager manager, ComponentId dataSourceId, ComponentId orderExecutionSourceId)
 {
     SystemMonitor.CheckError(dataSourceId.IsEmpty == false && orderExecutionSourceId.IsEmpty == false, "Source Id not available to order.");
     _manager               = manager;
     _dataSourceId          = dataSourceId;
     _orderExectionSourceId = orderExecutionSourceId;
     _executionProvider     = manager.ObtainOrderExecutionProvider(orderExecutionSourceId, dataSourceId);
 }
 /// <summary>
 /// 
 /// </summary>
 public PassiveOrder(ISourceManager manager, ComponentId dataSourceId, ComponentId orderExecutionSourceId)
 {
     SystemMonitor.CheckError(dataSourceId.IsEmpty == false && orderExecutionSourceId.IsEmpty == false, "Source Id not available to order.");
     _manager = manager;
     _dataSourceId = dataSourceId;
     _orderExectionSourceId = orderExecutionSourceId;
     _executionProvider = manager.ObtainOrderExecutionProvider(orderExecutionSourceId, dataSourceId);
 }
        /// <summary>
        /// Startup initialization procedure, called only once in the lifecycle of an object
        /// (only after initial construction, not upon serialization-deserialization).
        /// </summary>
        /// <param name="dataProvider"></param>
        /// <param name="orderExectionProvider"></param>
        public bool SetInitialParameters(ISessionDataProvider dataProvider, ISourceOrderExecution orderExectionProvider)
        {
            SystemMonitor.CheckThrow(_sessionDataProvider == null && _orderExecutionProvider == null, "Session already initialized.");
            _sessionDataProvider    = dataProvider;
            _orderExecutionProvider = orderExectionProvider;

            return(true);
        }
 /// <summary>
 /// Detailed constructor.
 /// </summary>
 public ModifyOrderControl(ModeEnum mode, ActiveOrder order)
 {
     InitializeComponent();
     _provider = order.OrderExecutionProvider;
     _mode = mode;
     _order = order;
     _dataProvider = order.QuoteProvider;
     _dataProvider.QuoteUpdateEvent += new QuoteProviderUpdateDelegate(_dataProvider_QuoteUpdateEvent);
     _session = order.SessionInfo.Value;
 }
Beispiel #21
0
 /// <summary>
 /// Detailed constructor.
 /// </summary>
 public ModifyOrderControl(ModeEnum mode, Order order)
 {
     InitializeComponent();
     _provider     = order.OrderExecutionProvider;
     _mode         = mode;
     _order        = order;
     _dataProvider = order.QuoteProvider;
     _dataProvider.QuoteUpdateEvent += new QuoteProviderUpdateDelegate(_dataProvider_QuoteUpdateEvent);
     _session = order.SessionInfo.Value;
 }
Beispiel #22
0
        /// <summary>
        /// Initialization.
        /// </summary>
        public bool Initialize()
        {
            SystemMonitor.CheckThrow(State == OrderStateEnum.UnInitialized, "Order already initialized.");

            ISourceOrderExecution executionProvider = _executionProvider;

            _quoteProvider.QuoteUpdateEvent += new QuoteProviderUpdateDelegate(Quote_QuoteUpdateEvent);

            State = OrderStateEnum.Initialized;
            return(true);
        }
        /// <summary>
        ///
        /// </summary>
        public void Initialize(ISessionDataProvider dataProvider, ISourceOrderExecution orderExecutionProvider)
        {
            if (dataProvider == null)
            {
                return;
            }

            lock (this)
            {
                _dataProvider = dataProvider;
                if (_dataProvider != null)
                {
                    _dataProvider.CurrentDataBarProviderChangedEvent += new DataProviderUpdateDelegate(_dataProvider_CurrentDataBarProviderChangedEvent);
                    CurrentDataBarProvider = _dataProvider.DataBars;

                    if (_dataProvider.Quotes != null)
                    {
                        _dataProvider.Quotes.QuoteUpdateEvent += new QuoteProviderUpdateDelegate(Quotes_QuoteUpdateEvent);
                    }
                }

                _orderExecutionProvider = orderExecutionProvider;
                if (_orderExecutionProvider != null)
                {
                    IOrderSink executor = _orderExecutionProvider;
                    if (executor != null)
                    {
                        executor.OrdersUpdatedEvent += new OrdersUpdateDelegate(executor_OrderUpdatedEvent);
                    }

                    ITradeEntityManagement management = _orderExecutionProvider.TradeEntities;
                    if (management != null)
                    {
                        management.OrdersAddedEvent   += new OrderManagementOrdersUpdateDelegate(management_OrdersAddedEvent);
                        management.OrdersRemovedEvent += new OrderManagementOrdersUpdateDelegate(management_OrdersRemovedEvent);
                        management.OrdersUpdatedEvent += new OrderManagementOrdersUpdateTypeDelegate(management_OrderUpdatedEvent);
                    }
                }

                ComponentResourceManager resources = new ComponentResourceManager(typeof(ProviderTradeChartSeries));
                _imageDown  = ((Image)(resources.GetObject("imageDown")));
                _imageUp    = ((Image)(resources.GetObject("imageUp")));
                _imageCross = ((Image)(resources.GetObject("imageCross")));

                _buyDashedPen.DashPattern = new float[] { 5, 5 };
                _buyDashedPen.DashStyle   = System.Drawing.Drawing2D.DashStyle.Custom;

                _priceLevelPen.DashPattern = new float[] { 3, 3 };
                _priceLevelPen.DashStyle   = System.Drawing.Drawing2D.DashStyle.Custom;

                _sellDashedPen.DashPattern = new float[] { 5, 5 };
                _sellDashedPen.DashStyle   = System.Drawing.Drawing2D.DashStyle.Custom;
            }
        }
        /// <summary>
        /// Constructor, allows direct order initialization.
        /// </summary>
        /// <param name="session"></param>
        /// <param name="initialize">Initialize order on construction. If init fails, exception will occur.</param>
        public ActiveOrder(ISourceManager manager, ISourceOrderExecution executionProvider,
            ComponentId dataSourceId, bool initialize)
            : base(manager, executionProvider, dataSourceId)
        {
            State = OrderStateEnum.UnInitialized;

            if (initialize)
            {
                SystemMonitor.CheckThrow(Initialize());
            }
        }
Beispiel #25
0
        /// <summary>
        /// Constructor, allows direct order initialization.
        /// </summary>
        /// <param name="session"></param>
        /// <param name="initialize">Initialize order on construction. If init fails, exception will occur.</param>
        public ActiveOrder(ISourceManager manager, ISourceOrderExecution executionProvider,
                           ComponentId dataSourceId, bool initialize)
            : base(manager, executionProvider, dataSourceId)
        {
            State = OrderStateEnum.UnInitialized;

            if (initialize)
            {
                SystemMonitor.CheckThrow(Initialize());
            }
        }
        public bool AddProvider(ISourceOrderExecution provider)
        {
            if (_providers.Contains(provider))
            {
                return(false);
            }

            _providers.Add(provider);
            UpdateUI();

            return(true);
        }
Beispiel #27
0
        /// <summary>
        ///
        /// </summary>
        public bool SetInitialParameters(ISourceManager manager,
                                         ISourceOrderExecution provider,
                                         ISourceDataDelivery dataDelivery, Symbol symbol)
        {
            _manager       = manager;
            _orderProvider = provider;
            _dataDelivery  = dataDelivery;

            _info.Symbol = symbol;

            return(true);
        }
        /// <summary>
        ///
        /// </summary>
        protected override string OnExecuteMarket(ISourceOrderExecution provider, OrderTypeEnum orderType, int volume,
                                                  decimal?price, decimal?slippage, decimal?takeProfit, decimal?stopLoss, TimeSpan timeOut,
                                                  out PositionExecutionInfo executionInfo, out string operationResultMessage)
        {
            SystemMonitor.CheckError(provider.SupportsActiveOrderManagement == false, "Wrong position type for this provider.");

            executionInfo = PositionExecutionInfo.Empty;
            PassiveOrder order;

            lock (this)
            {
                order = new PassiveOrder(_manager, _dataDelivery.SourceId, provider.SourceId);
            }

            OrderInfo?infoReference;

            bool result = provider.SynchronousExecute(provider.DefaultAccount.Info, order, _info.Symbol,
                                                      orderType, volume, slippage, price, takeProfit, stopLoss, string.Empty, out infoReference, out operationResultMessage);

            if (result && infoReference.HasValue)
            {
                OrderInfo infoAssign = infoReference.Value;
                if (infoAssign.Type == OrderTypeEnum.UNKNOWN)
                {
                    infoAssign.Type = orderType;
                }

                if (infoAssign.Volume == int.MinValue ||
                    infoAssign.Volume == int.MaxValue)
                {// Volume was not retrieved by integration.
                    infoAssign.Volume = volume;
                }

                if (infoAssign.OpenPrice.HasValue)
                {
                    executionInfo = new PositionExecutionInfo(infoReference.Value.Id, _dataDelivery.SourceId, provider.SourceId, Symbol,
                                                              infoAssign.Type, infoAssign.OpenPrice.Value, volume, volume,
                                                              infoAssign.OpenTime, PositionExecutionInfo.ExecutionResultEnum.Success);
                }
                else
                {
                    SystemMonitor.Error("Received execution result, but price not assigned.");
                }

                order.AdoptInfo(infoAssign);

                provider.TradeEntities.AddOrder(order);

                return(infoReference.Value.Id);
            }

            return(string.Empty);
        }
        public bool AddProvider(ISourceOrderExecution provider)
        {
            if (_providers.Contains(provider))
            {
                return false;
            }

            _providers.Add(provider);
            UpdateUI();

            return true;
        }
        /// <summary>
        /// 
        /// </summary>
        protected override string OnExecuteMarket(ISourceOrderExecution provider, OrderTypeEnum orderType, int volume, 
            decimal? price, decimal? slippage, decimal? takeProfit, decimal? stopLoss, TimeSpan timeOut, 
            out PositionExecutionInfo executionInfo, out string operationResultMessage)
        {
            SystemMonitor.CheckError(provider.SupportsActiveOrderManagement == false, "Wrong position type for this provider.");

            executionInfo = PositionExecutionInfo.Empty;
            PassiveOrder order;
            lock (this)
            {
                order = new PassiveOrder(_manager, _dataDelivery.SourceId, provider.SourceId);
            }

            OrderInfo? infoReference;

            bool result = provider.SynchronousExecute(provider.DefaultAccount.Info, order, _info.Symbol,
                orderType, volume, slippage, price, takeProfit, stopLoss, string.Empty, out infoReference, out operationResultMessage);

            if (result && infoReference.HasValue)
            {
                OrderInfo infoAssign = infoReference.Value;
                if (infoAssign.Type == OrderTypeEnum.UNKNOWN)
                {
                    infoAssign.Type = orderType;
                }

                if (infoAssign.Volume == int.MinValue
                    || infoAssign.Volume == int.MaxValue)
                {// Volume was not retrieved by integration.
                    infoAssign.Volume = volume;
                }

                if (infoAssign.OpenPrice.HasValue)
                {
                    executionInfo = new PositionExecutionInfo(infoReference.Value.Id, _dataDelivery.SourceId, provider.SourceId, Symbol,
                        infoAssign.Type, infoAssign.OpenPrice.Value, volume, volume,
                        infoAssign.OpenTime, PositionExecutionInfo.ExecutionResultEnum.Success);
                }
                else
                {
                    SystemMonitor.Error("Received execution result, but price not assigned.");
                }

                order.AdoptInfo(infoAssign);

                provider.TradeEntities.AddOrder(order);

                return infoReference.Value.Id;
            }

            return string.Empty;
        }
Beispiel #31
0
        /// <summary>
        /// Initialize execution account with its owner provider.
        /// </summary>
        /// <param name="session"></param>
        public bool SetInitialParameters(ISourceManager manager, ISourceOrderExecution orderExecutionProvider, ISourceDataDelivery dataDelivery)
        {
            SystemMonitor.CheckError(_provider == null, "Order account already initialized.");

            _manager = manager;
            //why is the provider not ready
            _provider     = orderExecutionProvider;
            _dataDelivery = dataDelivery;

            SystemMonitor.CheckWarning(_manager != null && _provider != null && _dataDelivery != null, "Account not properly initialized.");

            return(true);
        }
Beispiel #32
0
        ///// <summary>
        ///// Will try to asynchronously reverse the given execution info position part.
        ///// Similar to the ExecuteMarketReverse baseMethod, only this is not synchronous.
        ///// </summary>
        //public virtual string SubmitReverse(PositionExecutionInfo orderInfo, decimal? slippage, bool manipulateExistingOrders, out string operationResultMessage)
        //{
        //    if (orderInfo.IsEmpty || orderInfo.Result != PositionExecutionInfo.ExecutionResultEnum.Success)
        //    {
        //        operationResultMessage = "Execution info not properly assigned for reversal.";
        //        return string.Empty;
        //    }

        //    OrderTypeEnum orderType = OrderTypeEnum.UNKNOWN;
        //    if (orderInfo.OrderType == OrderTypeEnum.BUY_MARKET)
        //    {
        //        orderType = OrderTypeEnum.SELL_MARKET;
        //    }
        //    else if (orderInfo.OrderType == OrderTypeEnum.SELL_MARKET)
        //    {
        //        orderType = OrderTypeEnum.BUY_MARKET;
        //    }
        //    else
        //    {
        //        operationResultMessage = "Only market position can be reversed.";
        //        SystemMonitor.OperationError(operationResultMessage);
        //        return string.Empty;
        //    }

        //    return Submit(orderType, (int)orderInfo.ExecutedVolume,
        //        null, slippage, null, null, manipulateExistingOrders, out operationResultMessage);
        //}

        ///// <summary>
        ///// Will try to synchronously execute a reverse of the given execution info.
        ///// This is a suitable replacement for a specific "order close", i.e. allowing
        ///// you to reverse a specific previous execution on this position.
        ///// </summary>
        ///// <param name="orderInfo"></param>
        ///// <param name="allowExistingActiveOrdersManipulation">Is the operation allowed to close a matching existing order, or should we always open a new one. This is suitable for Active orders brokers, that dissallow hedged orders at the same time.</param>
        ///// <returns></returns>
        //public virtual string ExecuteMarketReverse(PositionExecutionInfo orderInfo, decimal? slippage, TimeSpan timeOut, bool manipulateExistingOrders,
        //    out PositionExecutionInfo newExecutionInfo, out string operationResultMessage)
        //{
        //    newExecutionInfo = PositionExecutionInfo.Empty;

        //    if (orderInfo.IsEmpty == false && orderInfo.Result == PositionExecutionInfo.ExecutionResultEnum.Success)
        //    {
        //        OrderTypeEnum orderType = OrderTypeEnum.UNKNOWN;
        //        if (orderInfo.OrderType == OrderTypeEnum.BUY_MARKET)
        //        {
        //            orderType = OrderTypeEnum.SELL_MARKET;
        //        }
        //        else if (orderInfo.OrderType == OrderTypeEnum.SELL_MARKET)
        //        {
        //            orderType = OrderTypeEnum.BUY_MARKET;
        //        }
        //        else
        //        {
        //            operationResultMessage = "Only market position can be reversed.";
        //            SystemMonitor.OperationError(operationResultMessage);
        //            return string.Empty;
        //        }

        //        return ExecuteMarket(orderType, (int)orderInfo.ExecutedVolume, null, slippage, null, null, timeOut, out newExecutionInfo, out operationResultMessage);
        //    }
        //    else
        //    {
        //        operationResultMessage = "Can not reverse execution info with result [" + orderInfo.Result.ToString() + "], no action taken.";
        //        SystemMonitor.OperationError(operationResultMessage);
        //        return string.Empty;
        //    }
        //}

        /// <summary>
        ///
        /// </summary>
        protected virtual bool OnExecuteMarketBalanced(ISourceOrderExecution provider, int volumeModification, decimal?desiredPrice,
                                                       decimal?slippage, TimeSpan timeOut, out PositionExecutionInfo executionInfo, out string operationResultMessage)
        {
            OrderTypeEnum orderType = OrderTypeEnum.BUY_MARKET;

            if (volumeModification < 0)
            {
                orderType = OrderTypeEnum.SELL_MARKET;
            }

            return(string.IsNullOrEmpty(ExecuteMarket(orderType, Math.Abs(volumeModification), desiredPrice, slippage, null, null,
                                                      timeOut, out executionInfo, out operationResultMessage)) == false);
        }
        public void Dispose()
        {
            if (_sessionDataProvider != null)
            {
                _sessionDataProvider.Dispose();
                _sessionDataProvider = null;
            }

            if (_orderExecutionProvider != null)
            {
                _orderExecutionProvider = null;
            }
        }
Beispiel #34
0
        /// <summary>
        /// Initialization.
        /// </summary>
        public bool Initialize()
        {
            SystemMonitor.CheckThrow(State == OrderStateEnum.UnInitialized, "Order already initialized.");

            ISourceOrderExecution executionProvider = _executionProvider;

            if (Symbol.IsEmpty == false && QuoteProvider != null)
            {// This will only work for deserialized orders, or ones that already have adopted info.
                QuoteProvider.QuoteUpdateEvent += new QuoteProviderUpdateDelegate(Quote_QuoteUpdateEvent);
            }

            State = OrderStateEnum.Initialized;
            return(true);
        }
        public void UnInitialize()
        {
            if (_provider != null)
            {
                _provider.TradeEntities.PositionsUpdatedEvent -= new PositionsUpdateDelegate(TradeEntities_PositionsUpdatedEvent);
                _provider.TradeEntities.PositionsAddedEvent   -= new PositionsUpdateDelegate(TradeEntities_PositionsAddedEvent);
                _provider.TradeEntities.PositionsRemovedEvent -= new PositionsUpdateDelegate(TradeEntities_PositionsRemovedEvent);
                _provider.PositionsUpdateEvent -= new PositionUpdateDelegate(_provider_PositionUpdateEvent);
            }

            _manager      = null;
            _provider     = null;
            _dataDelivery = null;
        }
        /// <summary>
        ///
        /// </summary>
        public bool SetInitialParameters(ISourceManager manager, ISourceOrderExecution provider,
                                         ISourceDataDelivery delivery)
        {
            //SystemMonitor.CheckError(_provider == null, "OrderExecutionProvider already assigned.");

            _manager  = manager;
            _provider = provider;
            _delivery = delivery;

            if (_provider == null)
            {
                SystemMonitor.Warning("Failed to properly initialize entity keeper.");
            }

            return(true);
        }
        /// <summary>
        /// Constructor, allows direct order initialization.
        /// </summary>
        /// <param name="session"></param>
        /// <param name="initialize">Initialize order on construction. If init fails, exception will occur.</param>
        public ActiveOrder(ISourceManager manager, ISourceOrderExecution executionProvider,
            IQuoteProvider quoteProvider, ComponentId dataSourceId, Symbol symbol, bool initialize)
        {
            _manager = manager;
            _symbol = symbol;

            _dataSourceId = dataSourceId;

            _executionProvider = executionProvider;
            _quoteProvider = quoteProvider;

            State = OrderStateEnum.UnInitialized;

            if (initialize)
            {
                SystemMonitor.CheckThrow(Initialize());
            }
        }
        /// <summary>
        /// 
        /// </summary>
        public void Initialize(ISourceAndExpertSessionManager manager, ISourceDataDelivery dataDelivery, ISourceOrderExecution provider)
        {
            _manager = manager;
            _provider = provider;
            _dataDelivery = dataDelivery;

            if (_provider != null)
            {
                _provider.TradeEntities.PositionsUpdatedEvent += new PositionsUpdateDelegate(TradeEntities_PositionsUpdatedEvent);
                _provider.TradeEntities.PositionsAddedEvent += new PositionsUpdateDelegate(TradeEntities_PositionsAddedEvent);
                _provider.TradeEntities.PositionsRemovedEvent += new PositionsUpdateDelegate(TradeEntities_PositionsRemovedEvent);
                _provider.PositionsUpdateEvent += new PositionUpdateDelegate(_provider_PositionUpdateEvent);
            }

            UpdateUI();

            if (listView.Items.Count > 0 && listView.SelectedItems.Count == 0)
            {
                listView.Items[0].Selected = true;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        public bool SetInitialParameters(ISourceManager manager,
            ISourceOrderExecution provider, 
            ISourceDataDelivery dataDelivery, Symbol symbol)
        {
            _manager = manager;
            _provider = provider;
            _dataDelivery = dataDelivery;

            _info.Symbol = symbol;

            return true;
        }
        /// <summary>
        /// Register ISourceOrderExecution.
        /// </summary>
        protected bool AddElement(ComponentId id, ISourceOrderExecution provider)
        {
            if (id.IsEmpty || provider == null)
            {
                SystemMonitor.Warning("Invalid Id or order execution provider instance.");
                return false;
            }

            lock (this)
            {
                if (_orderExecutionProviders.ContainsKey(id))
                {
                    SystemMonitor.Warning("Failed to add order execution provider, since already added with this Id.");
                    return false;
                }

                _orderExecutionProviders.Add(id, provider);
            }

            return true;
        }
        /// <summary>
        /// 
        /// </summary>
        protected override void OnRecalculateParameters(ISourceOrderExecution provider, bool fullRecalculation)
        {
            decimal pendingVolume = 0;
            Order[] orders = provider.TradeEntities.GetOrdersBySymbol(Symbol);
            foreach (PassiveOrder order in orders)
            {
                if (order.State == OrderStateEnum.Submitted)
                {
                    pendingVolume += order.CurrentVolume;
                }
            }

            lock (this)
            {
                _info.PendingBuyVolume = pendingVolume;
            }
        }
Beispiel #42
0
 /// <summary>
 /// Constructor.
 /// </summary>
 public Order(ISourceManager manager, ISourceOrderExecution executionProvider, ComponentId dataSourceId)
 {
     _manager = manager;
     _executionProvider = executionProvider;
     _dataSourceId = dataSourceId;
 }
Beispiel #43
0
 /// <summary>
 /// 
 /// </summary>
 public virtual void Dispose()
 {
     _manager = null;
     _executionProvider = null;
     _quoteProvider = null;
     _dataSourceId = ComponentId.Empty;
 }
        /// <summary>
        /// 
        /// </summary>
        protected override void OnRecalculateParameters(ISourceOrderExecution provider, bool fullRecalculation)
        {
            SystemMonitor.CheckError(provider.SupportsActiveOrderManagement, "Wrong position type for this provider.");

            Order[] orders = provider.TradeEntities.GetOrdersBySymbol(Symbol);
            lock (this)
            {
                _info.Volume = 0;
                _info.PendingBuyVolume = 0;
                _info.PendingSellVolume = 0;
                _info.Result = 0;

                foreach (ActiveOrder order in GeneralHelper.SafeChildTypeIteration<Order, ActiveOrder>(orders))
                {
                    if (order.State == OrderStateEnum.Executed)
                    {
                        _info.Volume += order.CurrentDirectionalVolume;
                        _info.Result += order.GetResult(Order.ResultModeEnum.Currency);
                    }
                    else if (order.State == OrderStateEnum.Submitted)
                    {
                        if (order.IsBuy)
                        {
                            _info.PendingBuyVolume += order.CurrentVolume;
                        }
                        else
                        {
                            _info.PendingSellVolume += order.CurrentVolume;
                        }
                    }
                }
            }
        }
 protected abstract void OnRecalculateParameters(ISourceOrderExecution provider, bool fullRecalculation);
        /// <summary>
        /// 
        /// </summary>
        protected override string OnSubmit(ISourceOrderExecution provider, OrderTypeEnum orderType, int volume, 
            decimal? price, decimal? slippage, decimal? takeProfit, decimal? stopLoss, out string operationResultMessage)
        {
            PassiveOrder order = new PassiveOrder(_manager, _dataDelivery.SourceId, provider.SourceId);

            string id = provider.SubmitOrder(provider.DefaultAccount.Info, order, _info.Symbol,
                orderType, volume, slippage, price, takeProfit, stopLoss, string.Empty, out operationResultMessage);

            if (string.IsNullOrEmpty(id))
            {
                return string.Empty;
            }

            if (order.Info.State != OrderStateEnum.Executed)
            {// It is possible that the submit executes the order instantly, so make sure this is not the case.
                OrderInfo info = new OrderInfo(id, Symbol, orderType, OrderStateEnum.Submitted, volume,
                    price, null, null, null, null, null, null, null, null, null, null, string.Empty, null);
                order.AdoptInfo(info);
            }

            provider.TradeEntities.AddOrder(order);

            return id;
        }
 public void Dispose()
 {
     _manager = null;
     _orderProvider = null;
     _dataDelivery = null;
 }
        /// <summary>
        /// 
        /// </summary>
        protected override bool OnExecuteMarketBalanced(ISourceOrderExecution provider, int volumeModification, decimal? desiredPrice, 
            decimal? slippage, TimeSpan timeOut, out PositionExecutionInfo executionInfo, out string operationResultMessage)
        {
            if (_manipulateExistingOrders == false)
            {
                return base.OnExecuteMarketBalanced(provider, volumeModification, desiredPrice, slippage, timeOut, out executionInfo, out operationResultMessage);
            }

            OrderTypeEnum orderType = OrderTypeEnum.BUY_MARKET;
            if (volumeModification < 0)
            {
                orderType = OrderTypeEnum.SELL_MARKET;
                volumeModification = Math.Abs(volumeModification);
            }

            executionInfo = PositionExecutionInfo.Empty;
            int originalVolumeModification = volumeModification;

            List<KeyValuePair<double, decimal>> closePrices = new List<KeyValuePair<double, decimal>>();

            bool suitableOrdersAvailable;

            ActiveOrder orderSelected = ObtainManipulationOrder(provider, GetReverseOrderType(orderType), Math.Abs(originalVolumeModification),
                out suitableOrdersAvailable);

            if (orderSelected != null && volumeModification > 0)
            {
                if (volumeModification >= orderSelected.CurrentVolume)
                {
                    int orderVolume = orderSelected.CurrentVolume;
                    if (orderSelected.Close(slippage, null))
                    {
                        volumeModification -= orderVolume;
                        if (orderSelected.ClosePrice.HasValue)
                        {
                            closePrices.Add(new KeyValuePair<double, decimal>(orderVolume, orderSelected.ClosePrice.Value));
                        }
                        else
                        {
                            SystemMonitor.Error("Order [{" + orderSelected.Id + "}] closed but close price not assigned.");
                        }
                    }
                    else
                    {
                        ReleaseManipulationOrder(orderSelected);
                        operationResultMessage = "Failed to close corresponding reverse active order.";
                        return false;
                    }
                }
                else
                {
                    if (orderSelected.DecreaseVolume(volumeModification, slippage, null))
                    {
                        volumeModification = 0;
                    }
                }

                ReleaseManipulationOrder(orderSelected);
                orderSelected = null;
            }

            if (suitableOrdersAvailable && volumeModification > 0
                && originalVolumeModification == volumeModification)
            {// Complete failure to close anything, and there are some suitable.
                executionInfo = PositionExecutionInfo.Empty;
                operationResultMessage = "Suitable reverse market orders are available, but currently manipulated, so hedging rules forbid reverse orders placement at this moment.";
                return false;
            }

            if (volumeModification > 0)
            {// We need to execute one more in the reverse direction.
                PositionExecutionInfo marketExecutionInfo;
                string tmp;

                string executionResult = ExecuteMarket(orderType, volumeModification, null, slippage, null, null,
                    timeOut, out marketExecutionInfo, out tmp);

                if (string.IsNullOrEmpty(executionResult) == false)
                {// Success.
                    volumeModification -= (int)marketExecutionInfo.VolumeExecuted;
                    if (marketExecutionInfo.ExecutedPrice.HasValue)
                    {
                        closePrices.Add(new KeyValuePair<double, decimal>(marketExecutionInfo.VolumeExecuted, marketExecutionInfo.ExecutedPrice.Value));
                    }
                    else
                    {
                        SystemMonitor.Error("MarketExecutionInfo for a valid execution [{" + executionResult + "}] does not have ExecutedPrice assigned.");
                    }
                }
                else
                {
                    operationResultMessage = tmp;
                    return false;
                }
            }

            // Calculate the close price, combination from the operations.
            decimal closePrice = 0;
            double totalVolume = 0;

            if (FinancialHelper.CalculateAveragePrice(closePrices, out closePrice, out totalVolume) == false)
            {
                SystemMonitor.Error("Failed to calculate average price for market balanced execution.");
                closePrice = 0;
            }

            if (volumeModification > 0)
            {// Failure.
                if (originalVolumeModification == volumeModification)
                {// Complete failure.
                    executionInfo = PositionExecutionInfo.Empty;
                    operationResultMessage = "Failed to execute market operation.";
                    return false;
                }
                else
                {// Partial execution success.
                    executionInfo = new PositionExecutionInfo(Guid.NewGuid().ToString(), _dataDelivery.SourceId, provider.SourceId, Symbol, orderType,
                        closePrice, originalVolumeModification, originalVolumeModification - volumeModification, DateTime.Now, PositionExecutionInfo.ExecutionResultEnum.PartialSuccess);
                }
            }
            else
            {// Success.
                executionInfo = new PositionExecutionInfo(Guid.NewGuid().ToString(), _dataDelivery.SourceId, provider.SourceId, Symbol, orderType,
                    closePrice, originalVolumeModification, originalVolumeModification, DateTime.Now, PositionExecutionInfo.ExecutionResultEnum.Success);
            }

            operationResultMessage = string.Empty;
            return true;
        }
        /// <summary>
        /// 
        /// </summary>
        public bool SetInitialParameters(ISourceManager manager, ISourceOrderExecution provider,
            ISourceDataDelivery delivery)
        {
            //SystemMonitor.CheckError(_provider == null, "OrderExecutionProvider already assigned.");

            _manager = manager;
            _provider = provider;
            _delivery = delivery;

            if (_provider == null)
            {
                SystemMonitor.Warning("Failed to properly initialize entity keeper.");
            }

            return true;
        }
 public void Dispose()
 {
     _manager = null;
     _provider = null;
     _delivery = null;
 }
        ///// <summary>
        ///// Will try to asynchronously reverse the given execution info position part.
        ///// Similar to the ExecuteMarketReverse baseMethod, only this is not synchronous.
        ///// </summary>
        //public virtual string SubmitReverse(PositionExecutionInfo orderInfo, decimal? slippage, bool manipulateExistingOrders, out string operationResultMessage)
        //{
        //    if (orderInfo.IsEmpty || orderInfo.Result != PositionExecutionInfo.ExecutionResultEnum.Success)
        //    {
        //        operationResultMessage = "Execution info not properly assigned for reversal.";
        //        return string.Empty;
        //    }
        //    OrderTypeEnum orderType = OrderTypeEnum.UNKNOWN;
        //    if (orderInfo.OrderType == OrderTypeEnum.BUY_MARKET)
        //    {
        //        orderType = OrderTypeEnum.SELL_MARKET;
        //    }
        //    else if (orderInfo.OrderType == OrderTypeEnum.SELL_MARKET)
        //    {
        //        orderType = OrderTypeEnum.BUY_MARKET;
        //    }
        //    else
        //    {
        //        operationResultMessage = "Only market position can be reversed.";
        //        SystemMonitor.OperationError(operationResultMessage);
        //        return string.Empty;
        //    }
        //    return Submit(orderType, (int)orderInfo.ExecutedVolume,
        //        null, slippage, null, null, manipulateExistingOrders, out operationResultMessage);
        //}
        ///// <summary>
        ///// Will try to synchronously execute a reverse of the given execution info.
        ///// This is a suitable replacement for a specific "order close", i.e. allowing
        ///// you to reverse a specific previous execution on this position.
        ///// </summary>
        ///// <param name="orderInfo"></param>
        ///// <param name="allowExistingActiveOrdersManipulation">Is the operation allowed to close a matching existing order, or should we always open a new one. This is suitable for Active orders brokers, that dissallow hedged orders at the same time.</param>
        ///// <returns></returns>
        //public virtual string ExecuteMarketReverse(PositionExecutionInfo orderInfo, decimal? slippage, TimeSpan timeOut, bool manipulateExistingOrders,
        //    out PositionExecutionInfo newExecutionInfo, out string operationResultMessage)
        //{
        //    newExecutionInfo = PositionExecutionInfo.Empty;
        //    if (orderInfo.IsEmpty == false && orderInfo.Result == PositionExecutionInfo.ExecutionResultEnum.Success)
        //    {
        //        OrderTypeEnum orderType = OrderTypeEnum.UNKNOWN;
        //        if (orderInfo.OrderType == OrderTypeEnum.BUY_MARKET)
        //        {
        //            orderType = OrderTypeEnum.SELL_MARKET;
        //        }
        //        else if (orderInfo.OrderType == OrderTypeEnum.SELL_MARKET)
        //        {
        //            orderType = OrderTypeEnum.BUY_MARKET;
        //        }
        //        else
        //        {
        //            operationResultMessage = "Only market position can be reversed.";
        //            SystemMonitor.OperationError(operationResultMessage);
        //            return string.Empty;
        //        }
        //        return ExecuteMarket(orderType, (int)orderInfo.ExecutedVolume, null, slippage, null, null, timeOut, out newExecutionInfo, out operationResultMessage);
        //    }
        //    else
        //    {
        //        operationResultMessage = "Can not reverse execution info with result [" + orderInfo.Result.ToString() + "], no action taken.";
        //        SystemMonitor.OperationError(operationResultMessage);
        //        return string.Empty;
        //    }
        //}
        /// <summary>
        /// 
        /// </summary>
        protected virtual bool OnExecuteMarketBalanced(ISourceOrderExecution provider, int volumeModification, decimal? desiredPrice,
            decimal? slippage, TimeSpan timeOut, out PositionExecutionInfo executionInfo, out string operationResultMessage)
        {
            OrderTypeEnum orderType = OrderTypeEnum.BUY_MARKET;
            if (volumeModification < 0)
            {
                orderType = OrderTypeEnum.SELL_MARKET;
            }

            return string.IsNullOrEmpty(ExecuteMarket(orderType, Math.Abs(volumeModification), desiredPrice, slippage, null, null,
                timeOut, out executionInfo, out operationResultMessage)) == false;
        }
        /// <summary>
        /// 
        /// </summary>
        public void Initialize(ISessionDataProvider dataProvider, ISourceOrderExecution orderExecutionProvider)
        {
            if (dataProvider == null)
            {
                return;
            }

            lock (this)
            {
                _dataProvider = dataProvider;
                if (_dataProvider != null)
                {
                    _dataProvider.CurrentDataBarProviderChangedEvent += new DataProviderUpdateDelegate(_dataProvider_CurrentDataBarProviderChangedEvent);
                    CurrentDataBarProvider = _dataProvider.DataBars;

                    if (_dataProvider.Quotes != null)
                    {
                        _dataProvider.Quotes.QuoteUpdateEvent += new QuoteProviderUpdateDelegate(Quotes_QuoteUpdateEvent);
                    }
                }

                _orderExecutionProvider = orderExecutionProvider;
                if (_orderExecutionProvider != null)
                {
                    IOrderSink executor = _orderExecutionProvider;
                    if (executor != null)
                    {
                        executor.OrdersUpdatedEvent += new OrdersUpdateDelegate(executor_OrderUpdatedEvent);
                    }

                    ITradeEntityManagement management = _orderExecutionProvider.TradeEntities;
                    if (management != null)
                    {
                        management.OrdersAddedEvent += new OrderManagementOrdersUpdateDelegate(management_OrdersAddedEvent);
                        management.OrdersRemovedEvent += new OrderManagementOrdersUpdateDelegate(management_OrdersRemovedEvent);
                        management.OrdersUpdatedEvent += new OrderManagementOrdersUpdateTypeDelegate(management_OrderUpdatedEvent);
                    }
                }

                ComponentResourceManager resources = new ComponentResourceManager(typeof(ProviderTradeChartSeries));
                _imageDown = ((Image)(resources.GetObject("imageDown")));
                _imageUp = ((Image)(resources.GetObject("imageUp")));
                _imageCross = ((Image)(resources.GetObject("imageCross")));

                _buyDashedPen.DashPattern = new float[] { 5, 5 };
                _buyDashedPen.DashStyle = System.Drawing.Drawing2D.DashStyle.Custom;

                _priceLevelPen.DashPattern = new float[] { 3, 3 };
                _priceLevelPen.DashStyle = System.Drawing.Drawing2D.DashStyle.Custom;

                _sellDashedPen.DashPattern = new float[] { 5, 5 };
                _sellDashedPen.DashStyle = System.Drawing.Drawing2D.DashStyle.Custom;
            }
        }
 /// <summary>
 /// 
 /// </summary>
 protected abstract string OnSubmit(ISourceOrderExecution provider, OrderTypeEnum orderType, int volume, decimal? price, 
     decimal? slippage, decimal? takeProfit, decimal? stopLoss, out string operationResultMessage);
        public void UnInitialize()
        {
            lock (this)
            {
                _ordersArrows.Clear();
                GeneralHelper.FireAndForget(SelectedOrderChangedEvent, _selectedOrder, null);
                _selectedOrder = null;

                CurrentDataBarProvider = null;
                if (_dataProvider != null)
                {
                    if (_dataProvider.Quotes != null)
                    {
                        _dataProvider.Quotes.QuoteUpdateEvent += new QuoteProviderUpdateDelegate(Quotes_QuoteUpdateEvent);
                    }

                    _dataProvider.CurrentDataBarProviderChangedEvent -= new DataProviderUpdateDelegate(_dataProvider_CurrentDataBarProviderChangedEvent);
                    _dataProvider = null;
                }

                if (_orderExecutionProvider != null)
                {
                    IOrderSink executor = _orderExecutionProvider;
                    ITradeEntityManagement management = _orderExecutionProvider.TradeEntities;

                    if (executor != null)
                    {
                        executor.OrdersUpdatedEvent -= new OrdersUpdateDelegate(executor_OrderUpdatedEvent);
                    }

                    if (management != null)
                    {
                        management.OrdersAddedEvent -= new OrderManagementOrdersUpdateDelegate(management_OrdersAddedEvent);
                        management.OrdersRemovedEvent -= new OrderManagementOrdersUpdateDelegate(management_OrdersRemovedEvent);
                        management.OrdersUpdatedEvent -= new OrderManagementOrdersUpdateTypeDelegate(management_OrderUpdatedEvent);
                    }

                    _orderExecutionProvider = null;
                }

                _buyDashedPen.Dispose();
                _sellDashedPen.Dispose();
            }
        }
        /// <summary>
        /// 
        /// </summary>
        protected override string OnSubmit(ISourceOrderExecution provider, OrderTypeEnum orderType, int volume, decimal? price,
            decimal? slippage, decimal? takeProfit, decimal? stopLoss, out string operationResultMessage)
        {
            SystemMonitor.CheckError(provider.SupportsActiveOrderManagement, "Wrong position type for this provider.");

            IQuoteProvider quotes = _manager.ObtainQuoteProvider(_dataDelivery.SourceId, Symbol);

            ActiveOrder order = new ActiveOrder(_manager, provider, quotes,
                _dataDelivery.SourceId, Symbol, true);

            price = ProcessPrice(quotes, orderType, price);

            string id = provider.SubmitOrder(provider.DefaultAccount.Info, order, _info.Symbol,
                orderType, volume, slippage, price, takeProfit, stopLoss, string.Empty, out operationResultMessage);

            if (string.IsNullOrEmpty(id))
            {
                return string.Empty;
            }

            OrderInfo info = new OrderInfo(id, Symbol, orderType, OrderStateEnum.Submitted, volume,
                price, null, null, null, null, null, null, null, null, null, null, string.Empty, null);

            order.AdoptInfo(info);
            provider.TradeEntities.AddOrder(order);

            return id;
        }
        public virtual void Dispose()
        {
            //if (_tradeEntities != null)
            //{
            //    _tradeEntities.UnInitialize();
            //    _tradeEntities = null;
            //}

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

            _dataDelivery = null;
            _manager = null;

            if (_provider != null)
            {
                _provider.AccountInfoUpdateEvent -= new AccountInfoUpdateDelegate(_provider_AccountInfoUpdateEvent);
                _provider.OperationalStateChangedEvent -= new OperationalStateChangedDelegate(_provider_OperationalStatusChangedEvent);

                _provider = null;
            }
        }
        /// <summary>
        /// Initialize execution account with its owner provider.
        /// </summary>
        /// <param name="session"></param>
        public bool SetInitialParameters(ISourceManager manager, ISourceOrderExecution orderExecutionProvider, ISourceDataDelivery dataDelivery)
        {
            SystemMonitor.CheckError(_provider == null, "Order account already initialized.");

            _manager = manager;
            //why is the provider not ready
            _provider = orderExecutionProvider;
            _dataDelivery = dataDelivery;

            SystemMonitor.CheckWarning(_manager != null && _provider != null && _dataDelivery != null, "Account not properly initialized.");

            return true;
        }
        /// <summary>
        /// 
        /// </summary>
        ActiveOrder ObtainManipulationOrder(ISourceOrderExecution provider, OrderTypeEnum orderType, int minVolume, 
            out bool suitableOrdersAvailable)
        {
            suitableOrdersAvailable = false;

            lock (provider.TradeEntities)
            {
                foreach (ActiveOrder activeOrder in provider.TradeEntities.GetOrdersByStateUnsafe(OrderStateEnum.Executed))
                {
                    if (activeOrder.Symbol == Symbol
                        && minVolume <= activeOrder.CurrentVolume
                        && (activeOrder.Type == orderType))
                    {// Found a opposing order, close it.

                        suitableOrdersAvailable = true;

                        lock (_activeSelectedOrders)
                        {
                            if (_activeSelectedOrders.Contains(activeOrder) == false)
                            {// Only if this order is not currently processed, take it for processing.
                                _activeSelectedOrders.Add(activeOrder);
                                return activeOrder;
                            }
                        }
                    }
                }
            }

            return null;
        }
 public bool RemoveProvider(ISourceOrderExecution provider)
 {
     bool result = _providers.Remove(provider);
     UpdateUI();
     return result;
 }
 /// <summary>
 /// 
 /// </summary>
 protected abstract string OnExecuteMarket(ISourceOrderExecution provider, OrderTypeEnum orderType, int volume, 
     decimal? price, decimal? slippage, decimal? takeProfit, decimal? stopLoss, TimeSpan timeOut,
     out PositionExecutionInfo executionInfo, out string operationResultMessage);