public void EditPendingOrderResponse(PendingOrder order, RequestStatus status, string detailMessage)
 {
     if (status == RequestStatus.OK)
         logMessage(string.Format("Счет {0}: ордер {1} успешно изменен",
                                  order.AccountID, order));
     else
         logMessage(string.Format("Счет {0}: ошибка редактирования ордера {1}: {2}",
                                  order.AccountID, order, status));
 }
 public bool ProcessPendingOrders(PendingOrder[] ordList)
 {
     if (onPendingOrdersReceived != null)
     {
         onPendingOrdersReceived(ordList);
         return true;
     }
     return false;
 }
Пример #3
0
 public PendingOrder(PendingOrder o)
 {
     ID = o.ID;
     PriceSide = o.PriceSide;
     AccountID = o.AccountID;
     PriceFrom = o.PriceFrom;
     PriceTo = o.PriceTo;
     TimeFrom = o.TimeFrom;
     TimeTo = o.TimeTo;
     Symbol = o.Symbol;
     Volume = o.Volume;
     Side = o.Side;
     Magic = o.Magic;
     comment = o.comment;
     expertComment = o.expertComment;
     StopLoss = o.StopLoss;
     TakeProfit = o.TakeProfit;
     PairOCO = o.PairOCO;
     CloseReason = o.CloseReason;
     TimeClosed = o.TimeClosed;
     PriceClosed = o.PriceClosed;
     trailingLevels = o.trailingLevels.ToArray();
     trailingTargets = o.trailingTargets.ToArray();
 }
Пример #4
0
 private void OnPendingOrdersReceived(PendingOrder[] ordList)
 {
     try
     {
         var charts = Charts;
         for (var j = 0; j < charts.Count; j++)
             charts[j].UpdatePendingOrdersListAsynch(ordList.Where(o => o.Symbol == charts[j].chart.Symbol).ToArray());
     }
     // ReSharper disable EmptyGeneralCatchClause
     catch
     // ReSharper restore EmptyGeneralCatchClause
     {// окно может быть еще не сформировано, когда в него попадет список ордеров
     }
 }
Пример #5
0
 /// <summary>
 /// Вызывается на торговых событиях установка снятие ордера, изменение параметров, срабатывание ордера
 /// </summary>
 /// <param name="order"></param>
 public virtual void OnTradeEvent(PendingOrder order)
 {
     TerminalLog.Instance.SaveRobotLog(string.Format("робот {0}: срабатывание отложенного ордера {1}, {2}, статус {3}, side = {4}",
         TypeName, order.ID, order.Symbol, order.Status, order.Side));
 }
Пример #6
0
 /// <summary>
 /// Change parameters for pending order
 /// </summary>
 /// <param name="ord"></param>
 /// <returns></returns>
 protected RequestStatus ModifyPendingOrder(PendingOrder ord)
 {
     return robotContext.SendEditPendingRequest(protectedContext.MakeProtectedContext(), ord);
 }
Пример #7
0
        private void MakePending(int side)
        {
            var priceVal = tbPrice.Text.Replace(",", ".").ToFloatUniformSafe();
            if (!priceVal.HasValue)
            {
                MessageBox.Show(Localizer.GetString("MessagePriceNotProvided"));
                tbPrice.Focus();
                return;
            }
            var price = priceVal.Value;
            if (price <= 0)
            {
                MessageBox.Show(Localizer.GetString("MessagePriceMustBePositive"));
                tbPrice.Text = "";
                tbPrice.Focus();
                return;
            }

            if (lastQuote == null)
            {
                MessageBox.Show(Localizer.GetString("MessageNoQuote"));
                return;
            }

            // создать новый отложенный ордер
            var volm = cbVolume.Text.Replace(" ", "").ToInt();
            var orderType = PendingOrderType.Limit;
            if ((side == 1 && lastQuote.ask < price) || (side == -1 && lastQuote.bid > price))
                orderType = PendingOrderType.Stop;
            var orderOCO = (PendingOrder)cbOrderOCO.SelectedItem;
            var orderOCOId = orderOCO == null ? (int?)null : orderOCO.ID;

            float?[] trailingLevels;
            float?[] trailTargets;
            GetTrailingLevels(side, out trailingLevels, out trailTargets);

            var order = new PendingOrder
                            {
                                AccountID = AccountStatus.Instance.accountID,
                                Symbol = Ticker,
                                Magic = tbMagic.Text.ToIntSafe(),
                                Volume = volm,
                                Side = side,
                                PriceSide = orderType,
                                PriceFrom = price,
                                PriceTo = tbPriceTo.Text.Replace(",", ".").ToFloatUniformSafe(),
                                TimeFrom = cbStartFrom.Checked ? dpTimeFrom.Value : (DateTime?) null,
                                TimeTo = cbEndTime.Checked ? dpTimeTo.Value : (DateTime?) null,
                                StopLoss = tbSL.Text.Replace(",", ".").ToFloatUniformSafe(),
                                TakeProfit = tbTP.Text.Replace(",", ".").ToFloatUniformSafe(),
                                PairOCO = orderOCOId > 0 ? orderOCO.ID : (int?)null,
                                Comment = tbComment.Text,
                                ExpertComment = tbExpertComment.Text,
                                // трейлинг
                                TrailLevel1 = trailingLevels[0],
                                TrailLevel2 = trailingLevels[1],
                                TrailLevel3 = trailingLevels[2],
                                TrailLevel4 = trailingLevels[3],
                                TrailTarget1 = trailTargets[0],
                                TrailTarget2 = trailTargets[1],
                                TrailTarget3 = trailTargets[2],
                                TrailTarget4 = trailTargets[3],
                            };

            MainForm.Instance.SendNewPendingOrderRequestSafe(RequestUniqueId.Next(), order);
        }
Пример #8
0
        /// <summary>
        /// асинхронно обновить отложенные ордера
        /// </summary>        
        public void UpdatePendingOrdersListAsynch(PendingOrder[] ordList)
        {
            if (!updateCompleted.WaitOne(WaitFormUpdateInterval)) return;

            var del = new UpdatePendingOrdersListDel(UpdatePendingOrdersList);
            try
            {
                Invoke(del, (object)ordList);
            }
            catch (InvalidOperationException) { }
        }
 public RequestStatus SendEditPendingRequest(ProtectedOperationContext secCtx, PendingOrder ord)
 {
     throw new NotImplementedException();
 }
Пример #10
0
 public void CallShowWindowEditPendingOrder(PendingOrder order)
 {
     if (onShowWindowEditPendingOrder != null)
         onShowWindowEditPendingOrder(order);
 }
Пример #11
0
        public override string ActivateScript(string ticker)
        {
            if (!AccountStatus.Instance.isAuthorized)
            {
                MessageBox.Show("Не авторизован");
                return "Не авторизован";
            }
            var account = AccountStatus.Instance.AccountData;
            if (account == null)
            {
                MessageBox.Show("Не авторизован");
                return "Не авторизован";
            }

            var equity = account.Equity;
            if (equity <= 0)
            {
                MessageBox.Show("На счете отсутствуют денежные средства");
                return "На счете отсутствуют денежные средства";
            }

            var dealSide = side;
            decimal? sl = null, tp = null;
            float? trailLevel = null, trailTarget = null;

            // предполагаемая цена входа
            var quotes = QuoteStorage.Instance.ReceiveAllData();
            QuoteData currentQuote;
            quotes.TryGetValue(ticker, out currentQuote);
            var reqPrice = currentQuote == null
                               ? 0
                               : Side == DealType.Buy
                                     ? currentQuote.ask
                                     : currentQuote.bid;

            if (OrderType == ScriptOrderType.Отложенный && currentQuote == null)
            {
                return "Отложенный ордер не создан - нет котировки " + ticker;
            }

            // для отложенного ордера обязательно запросим цену
            decimal priceEnter = 0;
            float dealPrice = 0;
            if (RequestSide || OrderType == ScriptOrderType.Отложенный)
            {
                var dlg = new ScriptPartDepoFormDialog(
                    (int) side,
                    currentQuote == null ? (float?)null : currentQuote.bid,
                    OrderType == ScriptOrderType.Отложенный) { TradeTicker = ticker };
                if (dlg.ShowDialog() == DialogResult.Cancel) return "Отменен";
                priceEnter = dlg.Price ?? 0;
                sl = dlg.SL;
                tp = dlg.TP;
                dealSide = (DealType)dlg.Side;

                if (dlg.Trailing != null && dlg.Trailing.Length == 2 && (dlg.Trailing[0] != 0 || dlg.Trailing[1] != 0))
                {
                    if (currentQuote == null)
                    {
                        var msg = string.Format("Нет котировки \"{0}\" для расчета пп трейлинга", ticker);
                        MessageBox.Show(msg);
                        return msg;
                    }

                    var trailPrice = dlg.Trailing[0];
                    dealPrice =
                        OrderType == ScriptOrderType.Отложенный ? (float)priceEnter : (dealSide == DealType.Buy ? currentQuote.ask : currentQuote.bid);
                    var trailPips = DalSpot.Instance.GetPointsValue(ticker, ((int) dealSide)*(trailPrice - dealPrice));

                    // преобразовать цену в пп от входа
                    trailLevel = trailPips;
                    trailTarget = dlg.Trailing[1];
                }
            }

            // объем в валюте депозита
            var volumeDepo = equity * leverage;
            var volumeBase = volumeDepo;

            // из объема депо пересчитать в объем базовой валюты
            var depoCurx = AccountStatus.Instance.AccountData.Currency;

            bool inverse, pairsEqual;
            var tickerTrans = DalSpot.Instance.FindSymbol(ticker, true, depoCurx,
                out inverse, out pairsEqual);
            if (!pairsEqual)
            {
                QuoteData quote;
                quotes.TryGetValue(tickerTrans, out quote);
                if (quote == null)
                {
                    var msgError = string.Format(
                        "Невозможно рассчитать объем - отсутствует котировка \"{0}\"", tickerTrans);
                    MessageBox.Show(msgError);
                    return msgError;
                }
                var priceTrans = inverse ? 1 / quote.bid : quote.ask;
                volumeBase /= (decimal)priceTrans;
            }

            // округлить объем
            var lotSize = DalSpot.Instance.GetMinStepLot(ticker, account.Group);
            volumeBase = MarketOrder.RoundDealVolume((int)volumeBase, VolumeRound,
                                                   lotSize.a, lotSize.b);
            if (volumeBase == 0)
            {
                var msgError = string.Format(
                    "Рассчетный объем входа ({0}) меньше допустимого ({1})",
                    volumeBase, lotSize.a);
                MessageBox.Show(msgError);
                return msgError;
            }

            // проверить количество входов (по тикеру либо вообще)
            var ordersCount =
                DealCounting == DealCountingType.ОбщийУчет
                    ? MarketOrdersStorage.Instance.MarketOrders.Count
                    : MarketOrdersStorage.Instance.MarketOrders.Count(o => o.Symbol == ticker);

            if (ordersCount >= dealsMax)
            {
                var msgError =
                    DealCounting == DealCountingType.ОбщийУчет
                    ? string.Format(
                        "Уже открыто {0} сделок из {1} макс.", ordersCount, dealsMax)
                    : string.Format(
                        "По \"{0}\" уже открыто {1} сделок из {2} макс.",
                            ticker, ordersCount, dealsMax);
                MessageBox.Show(msgError);
                return msgError;
            }

            // подтверждение
            var confirmPrice = dealPrice;
            if (confirmPrice == 0)
                confirmPrice = (dealSide == DealType.Buy ? currentQuote.ask : currentQuote.bid);

            if (confirmTrade)
                if (MessageBox.Show(string.Format("Будет совершена {0} {1} {2} по {3}. Продолжить?",
                    dealSide == DealType.Buy ? "покупка" : "продажа",
                    volumeBase.ToStringUniformMoneyFormat(), depoCurx,
                    confirmPrice.ToStringUniformPriceFormat()),
                    "Подтверждение", MessageBoxButtons.YesNo) == DialogResult.No)
                    return "отменено пользователем";

            // таки войти в рынок
            if (OrderType == ScriptOrderType.Рыночный)
                MainForm.Instance.SendNewOrderRequestSafe(
                    RequestUniqueId.Next(),
                    AccountStatus.Instance.accountID,
                    new MarketOrder
                        {
                            Volume = (int)volumeBase,
                            Side = (int)dealSide,
                            Symbol = ticker,
                            StopLoss = (float?)sl,
                            TakeProfit = (float?)tp,
                            TrailLevel1 = trailLevel,
                            TrailTarget1 = trailTarget
                        },
                        priceEnter, 0, Contract.Entity.OrderType.Market);
            else
            {
                // создать отложенник
                var orderType = PendingOrderType.Limit;
                if (((int)dealSide == 1 && currentQuote.ask < (float)priceEnter) ||
                    ((int)dealSide == -1 && currentQuote.bid > (float)priceEnter))
                    orderType = PendingOrderType.Stop;
                var pendingOrder = new PendingOrder
                    {
                        AccountID = AccountStatus.Instance.accountID,
                        Symbol = ticker,
                        Volume = (int)volumeBase,
                        Side = (int)dealSide,
                        PriceSide = orderType,
                        PriceFrom = (float)priceEnter,
                        StopLoss = (float?)sl,
                        TakeProfit = (float?)tp,
                        TrailLevel1 = trailLevel,
                        TrailTarget1 = trailTarget
                    };

                MainForm.Instance.SendNewPendingOrderRequestSafe(RequestUniqueId.Next(), pendingOrder);
            }

            return "Сделка с фиксированным плечом (" + dealSide + " " + ticker + ") совершена";
        }
 public RequestStatus SendDeletePendingOrderRequest(ProtectedOperationContext ctx, PendingOrder order, PendingOrderStatus status,
                                                    int? positionID, string closeReason)
 {
     throw new NotImplementedException();
 }
 public void NewPendingOrderResponse(PendingOrder order, RequestStatus status, string detailMessage)
 {
     PutResponse(status, detailMessage, order, string.Empty, order.AccountID, TradeSharpClientResponseType.NewPendingOrder);
 }
Пример #14
0
        public void CheckPendingOrder(PendingOrder order, Dictionary<string, QuoteData> curPrices)
        {
            // проверка на зафлаживание
            if (pendingFloodTimes.ContainsKey(order.ID))
            {
                var time = pendingFloodTimes[order.ID];
                if (DateTime.Now < time) return;
                    pendingFloodTimes.Remove(order.ID);
            }
            // отменить устаревший ордер)
            if (order.TimeTo.HasValue)
                if (DateTime.Now > order.TimeTo)
                {
                    //var pairCancel = curPrices.ContainsKey(order.Symbol) ? curPrices[order.Symbol] : null;
                    //var priceCancel = pairCancel == null ? 0 : order.Side > 0 ? pairCancel.Bid : pairCancel.Ask;
                    proxyTrade.SendDeletePendingOrderRequest(ProtectedOperationContext.MakeServerSideContext(),
                        order, PendingOrderStatus.Отменен, null, "Экспирация");
                    return;
                }
            // получить текущую котировку
            if (!curPrices.ContainsKey(order.Symbol))
            {
                if ((DateTime.Now - timeStarted).TotalMilliseconds > MinMillsToReportError)
                    floodSafeLogger.LogMessageFormatCheckFlood(LogEntryType.Debug, MsgNoQuoteMagic, 5 * 60 * 1000,
                                           "CheckOrder: нет котировки по {0} для отлож. ордера #{1}",
                                           order.Symbol, order.ID);
                return;
            }
            var pricePair = curPrices[order.Symbol];
            var price = order.Side > 0 ? pricePair.ask : pricePair.bid;

            // проверить нахождение в рамках цены и времени
            if (order.TimeFrom.HasValue)
                if (DateTime.Now < order.TimeFrom) return;
            // цена...
            var orderFires = false;
            if (order.Side > 0 && ((PendingOrderPriceSide)order.PriceSide) == PendingOrderPriceSide.Limit)
            {
                if (price <= order.PriceFrom && (order.PriceTo == null ? true : price >= order.PriceTo)) orderFires = true;
            }
            else
                if (order.Side < 0 && ((PendingOrderPriceSide)order.PriceSide) == PendingOrderPriceSide.Limit)
                {
                    if (price >= order.PriceFrom && (order.PriceTo == null ? true : price <= order.PriceTo)) orderFires = true;
                }
                else
                    if (order.Side > 0 && ((PendingOrderPriceSide)order.PriceSide) == PendingOrderPriceSide.Stop)
                    {
                        if (price >= order.PriceFrom && (order.PriceTo == null ? true : price <= order.PriceTo)) orderFires = true;
                    }
                    else
                    {
                        if (price <= order.PriceFrom && (order.PriceTo == null ? true : price >= order.PriceTo)) orderFires = true;
                    }
            if (!orderFires) return;
            Logger.InfoFormat("Активация отлож. ордера #{0} ({1} {2} at {3}), цена {4}",
                order.ID, (DealType)order.Side, order.PriceSide,
                order.PriceFrom.ToStringUniformPriceFormat(true),
                price.ToStringUniformPriceFormat(true));

            // активировать ордер
            var orderMarket = new MarketOrder
                {
                    AccountID = order.AccountID,
                    Magic = order.Magic,
                    Symbol = order.Symbol,
                    Volume = order.Volume,
                    Side = order.Side,
                    StopLoss = order.StopLoss,
                    TakeProfit = order.TakeProfit,
                    Comment = string.Format("по ордеру #{0}", order.ID)
                };

            var reqStatus = proxyTrade.SendNewOrderRequest(
                    ProtectedOperationContext.MakeServerSideContext(),
                    RequestUniqueId.Next(),
                    orderMarket,
                    OrderType.Market,
                    0, 0); // проскальзывание
            if (reqStatus == RequestStatus.OK)
            {
                // удалить парный ордер
                if (order.PairOCO.HasValue && order.PairOCO > 0)
                {
                    List<PendingOrder> orders;
                    try
                    {
                        proxyAccount.GetPendingOrders(order.AccountID, out orders);
                        var orderPair = orders == null ? null : orders.FirstOrDefault(o => o.ID == order.PairOCO.Value);
                        if (orderPair != null)
                            proxyTrade.SendDeletePendingOrderRequest(ProtectedOperationContext.MakeServerSideContext(),
                                orderPair, PendingOrderStatus.Отменен, null, "OCO");
                    }
                    catch (Exception ex)
                    {
                        Logger.ErrorFormat("Ошибка удаления парного ордера {0} для ордера {1}: {2}",
                            order.PairOCO, order, ex);
                    }
                }

                // удалить ордер
                proxyTrade.SendDeletePendingOrderRequest(ProtectedOperationContext.MakeServerSideContext(),
                    order, PendingOrderStatus.Исполнен, null, "Активирован");
            }
            else
            {
                Logger.ErrorFormat("Ошибка активации отлож. ордера #{0}: {1}", order.ID, reqStatus);
                // удалить ордер
                proxyTrade.SendDeletePendingOrderRequest(ProtectedOperationContext.MakeServerSideContext(),
                    order, PendingOrderStatus.Отменен, null, "Отменен");

                // зафлаживание
                var nextTime = DateTime.Now.AddMilliseconds(PendingFloodTimeoutMils);
                if (pendingFloodTimes.ContainsKey(order.ID))
                    pendingFloodTimes[order.ID] = nextTime;
                else
                    pendingFloodTimes.Add(order.ID, nextTime);
            }
        }
 public static string MakeOrderTitle(PendingOrder order)
 {
     return string.Empty;
 }
Пример #16
0
 public void EditPendingOrderResponse(PendingOrder order, RequestStatus status, string detailMessage)
 {
     ShowMsgWindowSafe(new AccountEvent(
         Localizer.GetString("MessageNotificationPendingChangedTitle"),
         string.Format(Localizer.GetString("MessageNotificationPendingChangedBodyFmt"),
         order.ID, order.Symbol, order.AccountID), AccountEventCode.PendingOrderModified));
 }
Пример #17
0
 /// <summary>
 /// Вызывается на торговых событиях установка снятие ордера, изменение параметров, срабатывание ордера
 /// </summary>
 /// <param name="order"></param>
 public override void OnTradeEvent(PendingOrder order)
 {
 }
Пример #18
0
        public void NewPendingOrderResponse(PendingOrder order, RequestStatus status, string detailMessage)
        {
            var accountEvent = new AccountEvent(
                string.Format(Localizer.GetString("MessageNotificationPendingPlacedTitleFmt"), order.ID),

                string.Format(Localizer.GetString("MessageNotificationPendingPlacedBodyFmt"),
                    order.Side > 0 ? "BUY" : "SELL",
                    order.Volume, order.Symbol, order.PriceFrom, order.ID, order.AccountID), AccountEventCode.PendingOrder);
            ShowMsgWindowSafe(accountEvent);
            // проиграть звук - торговый ордер
            EventSoundPlayer.Instance.PlayEvent(VocalizedEvent.TradeResponse);
        }
Пример #19
0
 public override RequestStatus SendEditPendingRequest(ProtectedOperationContext secCtx, PendingOrder ord)
 {
     return proxyTrade.proxy.SendEditPendingRequest(secCtx, ord);
 }
 public RequestStatus SendNewPendingOrderRequest(ProtectedOperationContext ctx, int requestUniqueId, PendingOrder order)
 {
     throw new NotImplementedException();
 }
Пример #21
0
        private void LoadPendingOrderData()
        {
            RequestStatus status;
            List<PendingOrder> actualPos;
            try
            {
                status = TradeSharpAccount.Instance.proxy.GetPendingOrders(AccountStatus.Instance.accountID, out actualPos);
            }
            catch (Exception ex)
            {
                Logger.Error("OrderDlg::GetPendingOrders proxy error", ex);
                return;
            }
            if (status != RequestStatus.OK) return;
            var pos = actualPos.FirstOrDefault(p => p.ID == orderId);
            if (pos == null)
            {
                Logger.ErrorFormat("OrderDlg::GetPendingOrders - not found ({0})", orderId);
                return;
            }
            pendingOrder = pos;

            Ticker = pos.Symbol;
            orderSide = pos.Side;
            cbVolume.Text = pos.Volume.ToStringUniformMoneyFormat();
            tbSL.Text = pos.StopLoss.ToStringUniformPriceFormat("", true);
            tbTP.Text = pos.TakeProfit.ToStringUniformPriceFormat("", true);
            tbComment.Text = pos.Comment;
            tbExpertComment.Text = pos.ExpertComment;
            Text = string.Format("Отл. ордер №{0} {1} {2} price={3}",
                                    pos.ID, pos.Side > 0 ? "BUY" : "SELL", pos.Symbol, pos.PriceFrom);
            cbCurx.SelectedIndex = cbCurx.Items.IndexOf(pos.Symbol);
            tbMagic.Text = pos.Magic.HasValue ? pos.Magic.Value.ToString() : "";
            tbPrice.Text = pos.PriceFrom.ToStringUniformPriceFormat(true);

            // трейлинг
            LoadTrailingLevels(pos.trailingLevels, pos.trailingTargets);

            // доп параметры
            if (pos.TimeFrom.HasValue)
            {
                cbStartFrom.Checked = true;
                dpTimeFrom.Value = pos.TimeFrom.Value;
            }
            else
                cbStartFrom.Checked = false;
            if (pos.TimeTo.HasValue)
            {
                cbEndTime.Checked = true;
                dpTimeTo.Value = pos.TimeTo.Value;
            }
            else
                cbEndTime.Checked = false;
            if (pos.PriceTo.HasValue)
            {
                cbPriceTo.Checked = true;
                tbPriceTo.Text = pos.PriceTo.Value.ToStringUniformPriceFormat(true);
            }

            // стоп-лимит
            var orderCaption = string.Format("{0} {1}",
                                             pos.Side > 0 ? "BUY" : "SELL",
                                             pos.PriceSide == PendingOrderType.Stop ? "STOP" : "LIMIT");

            // кнопки
            var inactBtn = pos.Side > 0 ? btnSellMarket : btnBuyMarket;
            btnBuyMarket.Enabled = false;
            btnSellMarket.Enabled = false;
            inactBtn.Enabled = true;
            if (pos.Side > 0) btnBuyMarket.buttonCaption = orderCaption;
            else btnSellMarket.buttonCaption = orderCaption;
            inactBtn.textLeftColor = SystemColors.InactiveCaptionText;
            inactBtn.textRightColor = SystemColors.InactiveCaptionText;
            inactBtn.captionColor = SystemColors.ControlText;
            inactBtn.buttonCaption = "Отменить";
        }
Пример #22
0
 public override RequestStatus SendDeletePendingOrderRequest(ProtectedOperationContext ctx,
     PendingOrder order, PendingOrderStatus status, int? positionId, string closeReason)
 {
     return proxyTrade.proxy.SendDeletePendingOrderRequest(ctx, order, status, positionId, closeReason);
 }
Пример #23
0
        private void SetupGridPendingOrders()
        {
            var blank = new PendingOrder();
            gridPendingOrders.MultiSelectEnabled = true;
            gridPendingOrders.Columns.Add(new FastColumn(blank.Property(p => p.ID), "#")
                {
                    SortOrder = FastColumnSort.Ascending,
                });
            gridPendingOrders.Columns.Add(new FastColumn(blank.Property(p => p.Volume), Localizer.GetString("TitleSum"))
                {
                    FormatString = "n0"
                });
            gridPendingOrders.Columns.Add(new FastColumn(blank.Property(p => p.Symbol), Localizer.GetString("TitleSymbol")));
            gridPendingOrders.Columns.Add(new FastColumn(blank.Property(p => p.Side), Localizer.GetString("TitleDeal"))
                {
                    formatter = (s => (int) s > 0 ? "BUY" : "SELL")
                });
            gridPendingOrders.Columns.Add(new FastColumn(blank.Property(p => p.PriceSide), Localizer.GetString("TitleType"))
                {
                    formatter = (s => (int) s == 1 ? "STOP" : "LIMIT")
                });
            gridPendingOrders.Columns.Add(new FastColumn(blank.Property(p => p.PriceFrom), Localizer.GetString("TitlePrice"))
                {
                    formatter = p => ((float) p).ToStringUniformPriceFormat(true)
                });
            gridPendingOrders.Columns.Add(new FastColumn(blank.Property(p => p.StopLoss), "S/L") {FormatString = "f5"});
            gridPendingOrders.Columns.Add(new FastColumn(blank.Property(p => p.TakeProfit), "T/P") {FormatString = "f5"});
            gridPendingOrders.Columns.Add(new FastColumn(blank.Property(p => p.PriceTo), Localizer.GetString("TitleLimit")) {FormatString = "f5"});
            gridPendingOrders.Columns.Add(new FastColumn(blank.Property(p => p.TimeFrom), Localizer.GetString("TitleStart"))
                {
                    FormatString = "dd.MM.yyyy HH:mm:ss",
                });
            gridPendingOrders.Columns.Add(new FastColumn(blank.Property(p => p.TimeTo), Localizer.GetString("TitleCompletion"))
                {
                    FormatString = "dd.MM.yyyy HH:mm:ss",
                });
            gridPendingOrders.Columns.Add(new FastColumn(blank.Property(p => p.Magic), "Magic"));
            gridPendingOrders.Columns.Add(new FastColumn(blank.Property(p => p.Comment), Localizer.GetString("TitleCommentShort")));
            gridPendingOrders.Columns.Add(new FastColumn(blank.Property(p => p.ExpertComment), Localizer.GetString("TitleRobotCommentShort")));
            gridPendingOrders.Columns.Add(new FastColumn(blank.Property(p => p.PairOCO), "OCO"));
            gridPendingOrders.Columns.Add(new FastColumn(blank.Property(p => p.Status), Localizer.GetString("TitleStatus")));

            gridPendingOrders.SelectionChanged += GridPendingOrdersSelectionChanged;
            gridPendingOrders.DoubleClick += GridPendingOrdersDoubleClick;
            gridPendingOrders.ColorAltCellBackground = Color.FromArgb(230, 230, 230);
            gridPendingOrders.MinimumTableWidth = gridPendingOrders.Columns.Count * DefaultColumnWidth;

            gridPendingOrders.ColumnSettingsChanged += OnGridPendingOrdersColumnSettingsChange;
            // применить настройки из файла настроек
            var sets = GridSettings.EnsureSettings(GridSettings.ListAccountPendingOrders);
            sets.ApplyToGrid(gridPendingOrders);
        }
Пример #24
0
 public override RequestStatus SendNewPendingOrderRequest(
     ProtectedOperationContext ctx,
     int requestUniqueId,
     PendingOrder order)
 {
     return proxyTrade.proxy.SendNewPendingOrderRequest(ctx, requestUniqueId, order);
 }
Пример #25
0
 public abstract RequestStatus SendDeletePendingOrderRequest(ProtectedOperationContext ctx,
     PendingOrder order, PendingOrderStatus status, int? positionId, string closeReason);
Пример #26
0
        private void UpdatePendingOrdersList(PendingOrder[] ordList)
        {
            if (!startupFinished) return;
            if (!updateCompleted.WaitOne()) return; //UpdateQuoteTimeout)) return;
            updateCompleted.Reset();
            try
            {
                var flagRedrawOrders = false;
                if (ordList != null)
                    flagRedrawOrders = chart.ProcessPendingOrders(ordList);
                if (flagRedrawOrders) // перерисовать
                    chart.RedrawChartSafe();

            }
            finally
            {
                updateCompleted.Set();
            }
        }
Пример #27
0
 public abstract RequestStatus SendEditPendingRequest(ProtectedOperationContext secCtx, PendingOrder ord);
Пример #28
0
 /// <summary>
 /// Delete pending order request
 /// </summary>
 /// <param name="order"></param>
 /// <returns></returns>
 protected RequestStatus DeletePendingOrder(PendingOrder order)
 {
     return robotContext.SendDeletePendingOrderRequest(protectedContext.MakeProtectedContext(), order,
         PendingOrderStatus.Отменен, null, "Отменен роботом");
 }
Пример #29
0
 public abstract RequestStatus SendNewPendingOrderRequest(ProtectedOperationContext ctx,
                                                          int requestUniqueId, PendingOrder order);
Пример #30
0
        /// <summary>
        /// Send pending order
        /// </summary>
        /// <param name="magic"></param>
        /// <param name="symbol"></param>
        /// <param name="volume"></param>
        /// <param name="side"></param>
        /// <param name="pendingOrdType"></param>
        /// <param name="targetPriceFrom"></param>
        /// <param name="targetPriceTo"></param>
        /// <param name="dateFrom"></param>
        /// <param name="dateTo"></param>
        /// <param name="stopPrice"></param>
        /// <param name="takePrice"></param>
        /// <param name="comment"></param>
        /// <returns></returns>
        protected RequestStatus NewPendingOrder(PendingOrder order)
        {
            order.AccountID = robotContext.AccountInfo.ID;

            return robotContext.SendNewPendingOrderRequest(
                protectedContext.MakeProtectedContext(),
                RequestUniqueId.Next(), order);
        }
Пример #31
0
        public bool OrdersAreSame(PendingOrder ord)
        {
            if (ID != ord.ID)
            {
                return(false);
            }
            if (PriceSide != ord.PriceSide)
            {
                return(false);
            }
            if (AccountID != ord.AccountID)
            {
                return(false);
            }
            if (PriceTo != ord.PriceTo)
            {
                return(false);
            }
            if (TimeFrom != ord.TimeFrom)
            {
                return(false);
            }
            if (TimeTo != ord.TimeTo)
            {
                return(false);
            }
            if (Symbol != ord.Symbol)
            {
                return(false);
            }
            if (Side != ord.Side)
            {
                return(false);
            }
            if (Magic != ord.Magic)
            {
                return(false);
            }
            if (Comment != ord.Comment)
            {
                return(false);
            }
            if (ExpertComment != ord.ExpertComment)
            {
                return(false);
            }
            if (StopLoss != ord.StopLoss)
            {
                return(false);
            }
            if (TakeProfit != ord.TakeProfit)
            {
                return(false);
            }
            if (PairOCO != ord.PairOCO)
            {
                return(false);
            }
            if (Status != ord.Status)
            {
                return(false);
            }
            if (CloseReason != ord.CloseReason)
            {
                return(false);
            }
            if (TimeClosed != ord.TimeClosed)
            {
                return(false);
            }
            if (PriceClosed != ord.PriceClosed)
            {
                return(false);
            }
            if (ord.TrailLevel1 != TrailLevel1 || ord.TrailLevel2 != TrailLevel2 ||
                ord.TrailLevel3 != TrailLevel3 ||
                ord.TrailLevel4 != TrailLevel4 || ord.TrailTarget1 != TrailTarget1 ||
                ord.TrailTarget2 != TrailTarget2 ||
                ord.TrailTarget3 != TrailTarget3 || ord.TrailTarget4 != TrailTarget4)
            {
                return(false);
            }

            return(true);
        }