protected override void Orders_OrderUpdatedEvent(ITradeEntityManagement provider, AccountInfo account, Order[] orders, ActiveOrder.UpdateTypeEnum[] updatesType)
        {
            base.Orders_OrderUpdatedEvent(provider, account, orders, updatesType);

            // Run in a separate thread since it takes time to request from server.
            //GeneralHelper.FireAndForget(new GeneralHelper.GenericReturnDelegate<bool>(Update));
        }
        public void UnInitialize()
        {
            if (_dataProvider != null)
            {
                _dataProvider.QuoteUpdateEvent -= new QuoteProviderUpdateDelegate(_dataProvider_QuoteUpdateEvent);
                _dataProvider = null;
            }

            _order = null;
        }
 /// <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;
 }
 protected virtual void Orders_OrderUpdatedEvent(ITradeEntityManagement provider, AccountInfo account, Order[] orders, Order.UpdateTypeEnum[] updatesType)
 {
 }
        /// <summary>
        /// NON UI Thread.
        /// </summary>
        //protected void DoObtainAllOrders(bool showError)
        //{
        //foreach (ExpertSession session in _sessions.ToArray())
        //{
        //    if (session.OrderExecutionProvider == null ||
        //        session.OrderExecutionProvider.OperationalState != OperationalStateEnum.Operational)
        //    {
        //        continue;
        //    }
        //    string operationResultMessage;
        //    if (session.OrderExecutionProvider.DefaultAccount != null &&
        //        session.OrderExecutionProvider.DefaultAccount.SynchronizeOrders(null, out operationResultMessage) == false)
        //    {
        //        if (showError)
        //        {
        //            MessageBox.Show("Failed to obtain orders session [" + session.Info.Name + "] [" + operationResultMessage + "].", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        //        }
        //        else
        //        {
        //            SystemMonitor.OperationError("Failed to obtain orders session [" + session.Info.Name + "] [" + operationResultMessage + "].");
        //        }
        //    }
        //}
        //WinFormsHelper.BeginFilteredManagedInvoke(this, new GeneralHelper.DefaultDelegate( delegate() { toolStripButtonObtainOrders.Enabled = true; }));
        //}
        protected ListViewItem SetItemAsOrder(ListViewItem item, Order order, AccountInfo account)
        {
            if (item.Tag != order)
            {
                item.Tag = order;
            }

            if (item.UseItemStyleForSubItems != false)
            {
                item.UseItemStyleForSubItems = false;
            }

            OrderStateEnum orderState = order.State;
            string groupName = string.Format("{0} Orders, Server [{1}] Company [{2}] Account [{3} / {4}]", orderState.ToString().ToUpper(), account.Server, account.Company, account.Name, account.Id);

            ListViewGroup group = listViewOrders.Groups[groupName];
            if (group == null)
            {
                group = new ListViewGroup(groupName, groupName);

                if (orderState == OrderStateEnum.Executed)
                {// Insert group at top of list.
                    listViewOrders.Groups.Insert(0, group);
                }
                else if (orderState == OrderStateEnum.Submitted)
                {// ...
                    listViewOrders.Groups.Insert(0, group);
                }
                else
                {
                    listViewOrders.Groups.Add(group);
                }
            }

            if (item.Group != group)
            {
                item.Group = group;
            }

            if (order.IsBuy)
            {
                int index = order.State == OrderStateEnum.Executed ? 0 : 2;
                if (item.ImageIndex != index)
                {
                    item.ImageIndex = index;
                }
            }
            else
            {
                int index = order.State == OrderStateEnum.Executed ? 1 : 3;
                if (item.ImageIndex != index)
                {
                    item.ImageIndex = index;
                }
            }

            while(item.SubItems.Count < 12)
            {
                item.SubItems.Add("");
            }

            //if (order.Type == OrderTypeEnum.UNKNOWN)
            //{// Order type not established yet.
            //    item.SubItems[0].Text = "NA";
            //    return item;
            //}

            string id = order.Id;
            if (id == null)
            {
                id = string.Empty;
            }

            if (item.SubItems[0].Text != id)
            {
                item.SubItems[0].Text = id;
            }

            if (item.SubItems[1].Text != order.Symbol.Name)
            {
                item.SubItems[1].Text = order.Symbol.Name;
            }

            if (order.IsOpenOrPending)
            {
                if (item.SubItems[2].Text != (GeneralHelper.GetShortDateTime(order.OpenTime)))
                {
                    item.SubItems[2].Text = (GeneralHelper.GetShortDateTime(order.OpenTime));
                }
            }
            else
            {
                if (item.SubItems[2].Text != (GeneralHelper.GetShortDateTime(order.OpenTime) + " to " + GeneralHelper.GetShortDateTime(order.CloseTime)))
                {
                    item.SubItems[2].Text = (GeneralHelper.GetShortDateTime(order.OpenTime) + " to " + GeneralHelper.GetShortDateTime(order.CloseTime));
                }
            }

            if (item.SubItems[3].Text != (order.Type.ToString()))
            {
                item.SubItems[3].Text = (order.Type.ToString());
            }

            if (item.SubItems[4].Text != (GeneralHelper.ToString(order.CurrentVolume)))
            {
                item.SubItems[4].Text = GeneralHelper.ToString(order.CurrentVolume);
            }

            if (item.SubItems[5].Text != GeneralHelper.ToString(order.OpenPrice))
            {
                item.SubItems[5].Text = GeneralHelper.ToString(order.OpenPrice);
            }

            string closePriceValue = GeneralHelper.ToString(order.ClosePrice);
            if (item.SubItems[6].Text != closePriceValue)
            {
                item.SubItems[6].Text = closePriceValue;
            }

            if (item.SubItems[7].Text != GeneralHelper.ToString(order.StopLoss))
            {
                item.SubItems[7].Text = GeneralHelper.ToString(order.StopLoss);
            }

            if (item.SubItems[8].Text != GeneralHelper.ToString(order.TakeProfit))
            {
                item.SubItems[8].Text = GeneralHelper.ToString(order.TakeProfit);
            }

            if (item.SubItems[9].Text != ("-"))
            {
                item.SubItems[9].Text = ("-");
            }

            decimal? currentResultPips = order.GetResult(Order.ResultModeEnum.Pips);
            decimal? currentResultBaseCurrency = order.GetResult(Order.ResultModeEnum.Currency);

            string resultString;

            if (currentResultBaseCurrency.HasValue == false ||
                currentResultBaseCurrency.HasValue == false)
            {
                resultString = "NaN";
            }
            else
            {
                resultString = currentResultPips.Value.ToString("0.#") + "p / " + currentResultBaseCurrency.Value.ToString("0.#");
            }

            if (item.SubItems[10].Text != resultString)
            {
                item.SubItems[10].Text = resultString;
            }

            if (currentResultPips < 0)
            {
                if (item.SubItems[10].BackColor != Color.MistyRose)
                {
                    item.SubItems[10].BackColor = Color.MistyRose;
                }
            }
            else
            {
                if (item.SubItems[10].BackColor != Color.Transparent)
                {
                    item.SubItems[10].BackColor = Color.Transparent;
                }
            }

            if (item.SubItems[11].Text != "-")
            {
                item.SubItems[11].Text = ("-");
            }

            return item;
        }
 /// <summary>
 /// NON UI Thread.
 /// </summary>
 public void SelectOrder(Order order)
 {
     if (this.IsHandleCreated)
     {
         WinFormsHelper.BeginFilteredManagedInvoke(this, new GeneralHelper.GenericDelegate<Order>(DoSelectOrder), order);
     }
 }
        /// <summary>
        /// An order has been received an update containing critical modification of its information,
        /// so handle this here and show to user.
        /// </summary>
        void management_OrdersCriticalInformationChangedEvent(ITradeEntityManagement provider, AccountInfo account, Order order, OrderInfo updateInfo)
        {
            // Compose the critical update message instantly, as otherwise it is wrong since the order gets instantly updated after this call.
            string criticalUpdateMessage = string.Empty;
            if (order.OpenPrice.HasValue && updateInfo.OpenPrice.HasValue && order.OpenPrice.Value != updateInfo.OpenPrice.Value)
            {
                criticalUpdateMessage = string.Format("Open Price Difference [{0}], Existing [{1}], New [{2}].", order.OpenPrice - updateInfo.OpenPrice, order.OpenPrice.ToString(), updateInfo.OpenPrice) + Environment.NewLine;
            }

            if (order.ClosePrice.HasValue && updateInfo.ClosePrice.HasValue && order.ClosePrice.Value != updateInfo.ClosePrice.Value)
            {
                criticalUpdateMessage += string.Format("Close Price Difference [{0}], Existing [{1}], New [{2}].", order.ClosePrice - updateInfo.ClosePrice, order.ClosePrice.ToString(), updateInfo.ClosePrice) + Environment.NewLine;
            }

            WinFormsHelper.BeginManagedInvoke(this, delegate()
            {
                if (toolStripButtonPopupNotifications.Checked == false)
                {
                    return;
                }

                if (string.IsNullOrEmpty(criticalUpdateMessage) == false)
                {
                    string message = "Account [" + account.Name + "] Order Id[" + order.Id + "] Critical Information Updated" + Environment.NewLine + criticalUpdateMessage;
                    NotificationForm form = new NotificationForm();
                    form.labelMessage.Text = message;
                    form.Text = "Critical Order Update";
                    form.TopMost = true;
                    form.Show();

                    //MessageBox.Show("Critical Order Update", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            });
        }
 void executor_OrderUpdatedEvent(IOrderSink executor, AccountInfo account, string[] previousOrdersIds, OrderInfo[] orderInfos, Order.UpdateTypeEnum[] updatesType)
 {
     //RaiseSeriesValuesUpdated(true);
 }
        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();
            }
        }
        public bool CancelPendingOrder(AccountInfo account, Order order, out string modifiedId, out string operationResultMessage)
        {
            decimal closingPrice;
            DateTime closingDateTime;
            if (DoCloseOrder(account, order, -1, 0, out closingPrice, out closingDateTime, out modifiedId, out operationResultMessage))
            {
                RaiseOrderUpdateEvent(account, string.Empty, order.Info, ActiveOrder.UpdateTypeEnum.Canceled);
                return true;
            }

            return false;
        }
 public void UpdateOrdersInfo(AccountInfo account, Order.UpdateTypeEnum[] updatesType, OrderInfo[] ordersInfo)
 {
     lock (this)
     {// Will only add it once, the remaining will just return false.
         if (_subscribers.Count > 0)
         {
             // Establish account subscribers and deliver them the update.
             this.SendRespondingToMany(_subscribers, new OrdersInformationUpdateResponseMessage(account, ordersInfo, updatesType, true));
         }
     }
 }
 /// <summary>
 /// 
 /// </summary>
 public void UpdateOrderInfo(AccountInfo account, Order.UpdateTypeEnum updateType, OrderInfo orderInfo)
 {
     UpdateOrdersInfo(account, new Order.UpdateTypeEnum[] { updateType }, new OrderInfo[] { orderInfo });
 }
        void _executor_OrderUpdatedEvent(IOrderSink providerSink, AccountInfo accountInfo, string[] previousOrdersIds, 
            OrderInfo[] ordersInfos, Order.UpdateTypeEnum[] updatesType)
        {
            ISourceOrderExecution provider = _provider;

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

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

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

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

                Order order = GetOrderById(ordersInfos[i].Id);
                if (order == null)
                {// Create new order based on incoming information.

                    if (provider.SupportsActiveOrderManagement)
                    {
                        order = new ActiveOrder(_manager, provider, _delivery.SourceId, true);
                    }
                    else
                    {
                        order = new PassiveOrder(_manager, _delivery.SourceId, provider.SourceId);
                    }

                    order.AdoptInfo(ordersInfos[i]);

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

                    OrderInfo info = ordersInfos[i];

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

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

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

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

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

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

            if (updatedOrders.Count > 0 && OrdersUpdatedEvent != null)
            {
                OrdersUpdatedEvent(this, accountInfo, updatedOrders.ToArray(), updatedOrdersUpdateTypes.ToArray() );
            }
        }
 void order_OrderUpdatedEvent(Order order, Order.UpdateTypeEnum updateType)
 {
     if (OrdersUpdatedEvent != null)
     {
         OrdersUpdatedEvent(this, _provider.DefaultAccount.Info, new Order[] { order }, new Order.UpdateTypeEnum[] { updateType });
     }
 }
 /// <summary>
 /// 
 /// </summary>
 public bool RemoveOrder(Order order)
 {
     RemoveOrders(new Order[] { order });
     return true;
 }
        /// <summary>
        /// Helper.
        /// </summary>
        bool DoCloseOrder(AccountInfo account, Order order, decimal? allowedSlippage, decimal? desiredPrice, out decimal closingPrice,
            out DateTime closingTime, out string modifiedId, out string operationResultMessage)
        {
            TracerHelper.Trace(this.Name);

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

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

            allowedSlippage = ProcessSlippage(allowedSlippage);

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

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

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

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

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

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

            operationResultMessage = response.OperationResultMessage;
            return false;
        }
        public override bool TrySelect(System.Drawing.Drawing2D.Matrix transformationMatrix, PointF drawingSpaceSelectionPoint, float absoluteSelectionMargin, bool canLoseSelection)
        {
            if (base.TrySelect(transformationMatrix, drawingSpaceSelectionPoint, absoluteSelectionMargin, canLoseSelection))
            {
                return true;
            }

            ISourceOrderExecution provider = _orderExecutionProvider;

            List<Order> orders = new List<Order>();

            if (provider != null && provider.TradeEntities != null && _dataProvider != null)
            {// Try select orders.
                lock (provider.TradeEntities)
                {
                    orders.AddRange(provider.TradeEntities.GetOrdersBySymbol(_dataProvider.SessionInfo.Symbol));
                }
            }

            lock (this)
            {
                foreach (Order order in orders)
                {
                    if (_ordersArrows.ContainsKey(order))
                    {
                        if (_ordersArrows[order].Contains(drawingSpaceSelectionPoint))
                        {
                            GeneralHelper.FireAndForget(SelectedOrderChangedEvent, _selectedOrder, order);
                            _selectedOrder = order;
                            break;
                        }
                    }
                }
            }

            return false;
        }
        public bool CloseOrder(AccountInfo account, Order order, decimal? allowedSlippage, decimal? desiredPrice, out decimal closingPrice, out DateTime closingTime, out string modifiedId, out string operationResultMessage)
        {
            if (DoCloseOrder(account, order, allowedSlippage, desiredPrice, out closingPrice,
                out closingTime, out modifiedId, out operationResultMessage))
            {
                RaiseOrderUpdateEvent(account, string.Empty, order.Info, ActiveOrder.UpdateTypeEnum.Closed);
                return true;
            }

            return false;
        }
        void DrawOrder(GraphicsWrapper g, ref PointF updatedImageDrawingPoint, Order order, float itemWidth, float itemMargin,
            float yToXScaling, DataBar orderBarData, float lastBarX, bool drawOpening)
        {
            Image image = _imageUp;
            Brush brush = Brushes.Green;
            Pen dashedPen = _buyDashedPen;
            Pen pen = Pens.GreenYellow;
            if (order.IsBuy == false)
            {
                image = _imageDown;
                brush = Brushes.Red;
                pen = Pens.Red;
                dashedPen = _sellDashedPen;
            }

            if (drawOpening == false)
            {
                image = _imageCross;
            }

            if (order.OpenPrice.HasValue == false)
            {
                SystemMonitor.OperationError("Order with no open price assigned for drawing.", TracerItem.PriorityEnum.Low);
                return;
            }

            float price = (float)order.OpenPrice.Value;
            if (drawOpening == false)
            {
                if (order.ClosePrice.HasValue == false)
                {
                    return;
                }

                price = (float)order.ClosePrice.Value;
            }

            if (drawOpening && _showPendingOrdersTracing &&
                (order is ActiveOrder && order.State == OrderStateEnum.Executed)
                && _dataProvider.Quotes.Bid.HasValue
                && _dataProvider.Quotes.Ask.HasValue)
            {// Open orders tracking line.
                PointF point1 = new PointF(updatedImageDrawingPoint.X + itemWidth / 2f, updatedImageDrawingPoint.Y + price);
                float sellPrice = (float)_dataProvider.Quotes.Bid;
                if (order.IsBuy == false)
                {
                    sellPrice = (float)_dataProvider.Quotes.Ask;
                }
                PointF point2 = new PointF(lastBarX - itemWidth / 2f, updatedImageDrawingPoint.Y + sellPrice);
                g.DrawLine(dashedPen, point1, point2);
            }

            //if (drawOpening && _showClosedOrdersTracing && order.IsOpen == false)
            //{// Closed order tracking.
            // Close order tracing is implemented in main draw function.
            //}

            if (_showOrderSpot)
            {
                PointF basePoint = new PointF(updatedImageDrawingPoint.X, updatedImageDrawingPoint.Y + price);
                float height = (yToXScaling * itemWidth);
                if (order.IsBuy == false)
                {
                    height = -height;
                }

                if (drawOpening)
                {
                    g.FillPolygon(brush, new PointF[] { basePoint, new PointF(basePoint.X + itemWidth, basePoint.Y),
                        new PointF(basePoint.X + (itemWidth / 2f), basePoint.Y + height) });
                    g.DrawPolygon(Pens.White, new PointF[] { basePoint, new PointF(basePoint.X + itemWidth, basePoint.Y),
                        new PointF(basePoint.X + (itemWidth / 2f), basePoint.Y + height) });

                    float drawToLeft = (float)(1.5 * itemWidth);
                    float drawToRight = (float)(2.5 * itemWidth);

                    // Take profit level.
                    if (order.TakeProfit.HasValue
                        && order.TakeProfit.Value != 0)
                    {
                        g.DrawLine(pen, updatedImageDrawingPoint.X - drawToLeft, updatedImageDrawingPoint.Y + (float)order.TakeProfit,
                            updatedImageDrawingPoint.X + drawToRight, updatedImageDrawingPoint.Y + (float)order.TakeProfit);

                        g.DrawLine(pen, updatedImageDrawingPoint.X + itemWidth / 2f, updatedImageDrawingPoint.Y + (float)order.TakeProfit,
                            updatedImageDrawingPoint.X + itemWidth / 2f, updatedImageDrawingPoint.Y + (float)order.TakeProfit - height);
                    }

                    // Stop loss level.
                    if (order.StopLoss.HasValue
                        && order.StopLoss.Value != 0)
                    {
                        g.DrawLine(pen, updatedImageDrawingPoint.X - drawToLeft, updatedImageDrawingPoint.Y + (float)order.StopLoss,
                            updatedImageDrawingPoint.X + drawToRight, updatedImageDrawingPoint.Y + (float)order.StopLoss);

                        g.DrawLine(pen, updatedImageDrawingPoint.X + itemWidth / 2f, updatedImageDrawingPoint.Y + (float)order.StopLoss,
                            updatedImageDrawingPoint.X + itemWidth / 2f, updatedImageDrawingPoint.Y + (float)order.StopLoss + height);
                    }
                }
                else
                {
                    g.DrawRectangle(Pens.White, basePoint.X, basePoint.Y,
                        itemWidth, yToXScaling * itemWidth);
                }

            }

            float imageHeight = 2 * (yToXScaling * itemWidth);
            if (_showOrderArrow)
            {
                float x = updatedImageDrawingPoint.X - (itemWidth / 2f);
                float y = updatedImageDrawingPoint.Y + (float)orderBarData.Low - (yToXScaling * itemWidth);
                float width = 2 * itemWidth;
                float height = -imageHeight;
                GraphicsWrapper.NormalizedRectangle(ref x, ref y, ref width, ref height);
                RectangleF rectange = new RectangleF(x, y, width, height);

                // Draw up image.
                g.DrawImage(image, rectange.X, rectange.Y, rectange.Width, rectange.Height);

                if (order == _selectedOrder)
                {// This is selected order.
                    g.DrawRectangle(Pens.White, rectange);
                }

                _ordersArrows[order] = rectange;

                updatedImageDrawingPoint.Y -= 1.2f * imageHeight;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        public bool DecreaseOrderVolume(AccountInfo account, Order order, decimal volumeDecreasal, decimal? allowedSlippage, 
            decimal? desiredPrice, out decimal decreasalPrice, out string modifiedId, out string operationResultMessage)
        {
            TracerHelper.Trace(this.Name);
            modifiedId = order.Id;
            decreasalPrice = decimal.MinValue;

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

            allowedSlippage = ProcessSlippage(allowedSlippage);

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

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

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

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

            CloseOrderVolumeResponseMessage responseMessage = (CloseOrderVolumeResponseMessage)response;

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

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

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

            return true;
        }
 void management_OrderUpdatedEvent(ITradeEntityManagement provider, AccountInfo account, Order[] orders, Order.UpdateTypeEnum[] updatesType)
 {
     //RaiseSeriesValuesUpdated(true);
 }
        public bool IncreaseOrderVolume(AccountInfo account, Order order, decimal volumeIncrease, decimal? allowedSlippage, decimal? desiredPrice, out decimal increasalPrice, out string modifiedId, out string operationResultMessage)
        {
            operationResultMessage = "Remote Order Execution Provider does not support volume increase.";
            allowedSlippage = ProcessSlippage(allowedSlippage);

            SystemMonitor.OperationError(operationResultMessage);
            increasalPrice = 0;
            modifiedId = string.Empty;
            return false;
        }
 void management_OrderUpdatedEvent(ITradeEntityManagement provider, AccountInfo account, Order[] orders, Order.UpdateTypeEnum[] updateType)
 {
     WinFormsHelper.BeginFilteredManagedInvoke(this, UpdateUI);
 }
        public bool ModifyOrder(AccountInfo account, Order order, decimal? stopLoss, decimal? takeProfit, 
            decimal? targetOpenPrice, out string modifiedId, out string operationResultMessage)
        {
            TracerHelper.Trace(this.Name);
            modifiedId = order.Id;

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

            ModifyOrderMessage message = new ModifyOrderMessage(account, order.Symbol, order.Id, stopLoss, takeProfit, targetOpenPrice, null);
            message.PerformSynchronous = true;

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

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

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

            ModifyOrderResponseMessage castedResponseMessage = (ModifyOrderResponseMessage)responseMessage;
            SystemMonitor.CheckError(string.IsNullOrEmpty(castedResponseMessage.OrderModifiedId) == false, "Modified not assigned.");
            modifiedId = castedResponseMessage.OrderModifiedId;
            operationResultMessage = "Order modified.";

            RaiseOrderUpdateEvent(account, castedResponseMessage.OrderId, order.Info, ActiveOrder.UpdateTypeEnum.Modified);

            return true;
        }
 protected void DoSelectOrder(Order order)
 {
     listViewOrders.SelectedItems.Clear();
     foreach (ListViewItem item in listViewOrders.Items)
     {
         if (item.Tag == order)
         {
             item.Selected = true;
         }
     }
 }
        /// <summary>
        /// 
        /// </summary>
        public string SubmitOrder(AccountInfo account, Order order, Symbol symbol, OrderTypeEnum orderType,
            int volume, decimal? allowedSlippage, decimal? desiredPrice, decimal? takeProfit, decimal? stopLoss, 
            string comment, out string operationResultMessage)
        {
            TracerHelper.Trace(this.Name);

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

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

            allowedSlippage = ProcessSlippage(allowedSlippage);

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

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

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

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

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

            SubmitOrderResponseMessage responseMessage = (SubmitOrderResponseMessage)response;
            operationResultMessage = "Order submited.";

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

            return responseMessage.OrderId;
        }
        bool IsOrderVisible(Order order)
        {
            if (_orderFilterStates.Count == 0)
            {
                return true;
            }

            foreach(OrderStateEnum state in _orderFilterStates)
            {
                if (order.State == state)
                {
                    return true;
                }
            }

            return false;
        }
 /// <summary>
 /// Redefine for the operationTimeOut, by providing the DefaultTimeOut.
 /// </summary>
 public bool SynchronousExecute(AccountInfo account, Order order, Symbol symbol, OrderTypeEnum orderType,
     int volume, decimal? allowedSlippage, decimal? desiredPrice, decimal? takeProfit, decimal? stopLoss,
     string comment, out OrderInfo? info, out string operationResultMessage)
 {
     return SynchronousExecute(account, order, symbol, orderType,
         volume, allowedSlippage, desiredPrice, takeProfit, stopLoss,
         comment, this.DefaultTimeOut, out info, out operationResultMessage);
 }
        /// <summary>
        /// Convert history to order orderInfo.
        /// </summary>
        /// <param name="OrderInfo"></param>
        /// <returns></returns>
        OrderInfo? ConvertToOrderInfo(MbtOrderHistory pHist, out Order.UpdateTypeEnum updateType)
        {
            updateType = Order.UpdateTypeEnum.Update;

            if (string.IsNullOrEmpty(pHist.Event))
            {
                return null;
            }

            OrderInfo info = new OrderInfo(pHist.Token);

            string eventInfo = pHist.Event.ToLower();

            if (eventInfo.Contains("enter") || (eventInfo.Contains("session") && eventInfo.Contains("open")))
            {// "Enter", "Session open" events skipped.
                return null;
            }

            if (eventInfo.Contains("live"))
            {
                info.State = OrderStateEnum.Submitted;
            }
            else if (eventInfo.Contains("executed"))
            {
                info.State = OrderStateEnum.Executed;
            }
            else if (eventInfo.Contains("suspended"))
            {
                info.State = OrderStateEnum.Suspended;
            }
            else if (eventInfo == "cancel"
                    || (eventInfo.Contains("cancel") && eventInfo.Contains("reject"))
                    || (eventInfo.Contains("order") && eventInfo.Contains("reject"))
                    || (eventInfo.Contains("order") && eventInfo.Contains("cancel")))
            {// Order Reject or Cancel.
                info.State = OrderStateEnum.Canceled;
                updateType = Order.UpdateTypeEnum.Canceled;
            }
            else if (eventInfo.Contains("suspended"))
            {// Suspended
                info.State = OrderStateEnum.Suspended;
                updateType = Order.UpdateTypeEnum.Modified;
            }

            string eventMessage = pHist.Message;

            Symbol? symbol = TryObtainSymbol(pHist.Symbol);
            if (symbol.HasValue == false)
            {
                return null;
            }

            info.Tag = pHist.OrderNumber;
            info.OpenPrice = (decimal)pHist.Price;
            info.StopLoss = (decimal)pHist.StopLimit;
            info.TakeProfit = (decimal)pHist.StopLimit;
            info.OpenTime = ConvertDateTime(pHist.Date + " " + pHist.Time);
            info.Volume = pHist.Quantity;

            info.Symbol = symbol.Value;

            info.Type = ConvertFromMBTOrderType(pHist.OrderType, pHist.BuySell);
            if (info.Type == OrderTypeEnum.UNKNOWN)
            {
                SystemMonitor.OperationWarning("Failed to recognize order type [" + pHist.OrderType.ToString() + "].");
                //return null;
            }

            return info;
        }
        /// <summary>
        /// Main SynchronousExecute method.
        /// </summary>
        public bool SynchronousExecute(AccountInfo account, Order order, Symbol symbol, OrderTypeEnum orderType, 
            int volume, decimal? allowedSlippage, decimal? desiredPrice, decimal? takeProfit, decimal? stopLoss, 
            string comment, TimeSpan operationTimeOut, out OrderInfo? info, out string operationResultMessage)
        {
            TracerHelper.Trace(this.Name);

            info = null;
            operationResultMessage = string.Empty;

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

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

            allowedSlippage = ProcessSlippage(allowedSlippage);

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

            request.PerformSynchronous = true;

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

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

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

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

            ExecuteMarketOrderResponseMessage responseMessage = (ExecuteMarketOrderResponseMessage)response;
            operationResultMessage = "Order opened.";

            info = responseMessage.Info;

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

            return true;
        }