Esempio n. 1
0
        public void SaveToFile()
        {
            List<StopOrder> orderList = new List<StopOrder>();
            StopOrder order = new StopOrder();

            order.Amount = 1;
            order.Currency = MtGoxCurrencySymbol.USD;
            order.ExecuteTime = System.DateTime.Now;
            order.OrderTime = System.DateTime.Now;
            order.Price = 2;
            order.Status = StopOrder.OrderStatus.Pending;
            order.Type = StopOrder.OrderType.SellStop;
            string folder = System.AppDomain.CurrentDomain.BaseDirectory.TrimEnd(new char[] { System.IO.Path.DirectorySeparatorChar });
            string fileName = Path.Combine(Path.GetDirectoryName(folder), "test.dat");
            StopOrder order1 = order;
            order1.Amount = 2;
            order1.Price = 4;
            orderList.Add(order);
            orderList.Add(order1);
            StopOrderHelper.SaveToFile(orderList, fileName);

            List<StopOrder> orderList2 = StopOrderHelper.LoadFromFile(fileName);
            Assert.AreEqual(orderList2.Count, 2);
            StopOrder order2 = orderList2[0];
            Assert.AreEqual(order.Amount, order2.Amount);
            Assert.AreEqual(order.Currency, order2.Currency);
            Assert.AreEqual(order.ExecuteTime, order2.ExecuteTime);
            Assert.AreEqual(order.OrderTime, order2.OrderTime);
            Assert.AreEqual(order.Price, order2.Price);
            Assert.AreEqual(order.Status, order2.Status);
            Assert.AreEqual(order.Type, order2.Type);
            //
            // TODO: Add test logic here
            //
        }
Esempio n. 2
0
        public async Task<long> CreateStopOrder(StopOrder stopOrder)
        {
            Transaction newStopOrderTransaction = new Transaction
            {
                ACTION = TransactionAction.NEW_STOP_ORDER,
                ACCOUNT = stopOrder.Account,
                CLASSCODE = stopOrder.ClassCode,
                SECCODE = stopOrder.SecCode,
                EXPIRY_DATE = "GTC",//до отмены
                STOPPRICE = stopOrder.ConditionPrice,
                PRICE = stopOrder.Price,
                QUANTITY = stopOrder.Quantity,
                STOP_ORDER_KIND = ConvertStopOrderType(stopOrder.StopOrderType),
                OPERATION = stopOrder.Operation == Operation.Buy?TransactionOperation.B : TransactionOperation.S
            };

            //todo: Not implemented
            //["OFFSET"]=tostring(SysFunc.toPrice(SecCode,MaxOffset)),
            //["OFFSET_UNITS"]="PRICE_UNITS",
            //["SPREAD"]=tostring(SysFunc.toPrice(SecCode,DefSpread)),
            //["SPREAD_UNITS"]="PRICE_UNITS",
            //["MARKET_STOP_LIMIT"]="YES",
            //["MARKET_TAKE_PROFIT"]="YES",
            //["STOPPRICE2"]=tostring(SysFunc.toPrice(SecCode,StopLoss)),
            //["EXECUTION_CONDITION"] = "FILL_OR_KILL",
    

            return await Quik.Trading.SendTransaction(newStopOrderTransaction);
        }
Esempio n. 3
0
        public void Execute()
        {
            List<StopOrder> orderList = new List<StopOrder>();
            StopOrder order = new StopOrder();

            order.Amount = 1;
            order.Currency = MtGoxCurrencySymbol.USD;
            order.ExecuteTime = System.DateTime.Now;
            order.OrderTime = System.DateTime.Now;
            order.Price = 2;
            order.Status = StopOrder.OrderStatus.Pending;
            order.Type = StopOrder.OrderType.SellStop;
            order.Execute(1.99, 1.98);
        }
Esempio n. 4
0
 internal void OnStopOrder(StopOrder stopOrder)
 {
     _stopOrders.Add(stopOrder);
     StopOrder?.Invoke(this, stopOrder);
 }
        /// <summary>
        /// Strategy enter/exit/filtering rules
        /// </summary>
        public override void OnNewBar()
        {
            decimal stopMargin = (int)this.GetInputParameter("Catastrophic Stop Loss ticks distance") * this.GetMainChart().Symbol.TickSize;

            int buySignal = (int)this.GetInputParameter("RSI Buy signal trigger level");
            int sellSignal = (int)this.GetInputParameter("RSI Sell signal trigger level");

            if (rsiIndicator.GetRSI()[1] <= buySignal && rsiIndicator.GetRSI()[0] > buySignal && this.GetOpenPosition() != 1)
            {
                if (this.GetOpenPosition() == 0)
                {
                    //BUY SIGNAL: Entering long and placing a catastrophic stop loss
                    MarketOrder buyOrder = new MarketOrder(OrderSide.Buy, 1, "Enter long position");
                    catastrophicStop = new StopOrder(OrderSide.Sell, 1, this.Bars.Close[0] - stopMargin, "Catastrophic stop long exit");

                    this.InsertOrder(buyOrder);
                    this.InsertOrder(catastrophicStop);
                }
                else if (this.GetOpenPosition() == -1)
                {
                    //BUY SIGNAL: Closing short position and cancelling the catastrophic stop loss order
                    MarketOrder exitShortOrder = new MarketOrder(OrderSide.Buy, 1, "Exit short position (reversal exit signal)");

                    this.InsertOrder(exitShortOrder);
                    this.CancelOrder(catastrophicStop);
                }
            }
            else if (rsiIndicator.GetRSI()[1] >= sellSignal && rsiIndicator.GetRSI()[0] < sellSignal && this.GetOpenPosition() != -1)
            {
                if (this.GetOpenPosition() == 0)
                {
                    //SELL SIGNAL: Entering short and placing a catastrophic stop loss
                    MarketOrder sellOrder = new MarketOrder(OrderSide.Sell, 1, "Enter short position");
                    catastrophicStop = new StopOrder(OrderSide.Buy, 1, this.Bars.Close[0] + stopMargin, "Catastrophic stop short exit");

                    this.InsertOrder(sellOrder);
                    this.InsertOrder(catastrophicStop);
                }
                else if (this.GetOpenPosition() == 1)
                {
                    //SELL SIGNAL: Closing long position and cancelling the catastrophic stop loss order
                    MarketOrder exitLongOrder = new MarketOrder(OrderSide.Sell, 1, "Exit long position (reversal exit signal)");

                    this.InsertOrder(exitLongOrder);
                    this.CancelOrder(catastrophicStop);
                }
            }
        }
Esempio n. 6
0
	public void OnStopOrderReceived (StopOrder a_order)
	{
		foreach(AUnitComponent each in _orderCallbacks)
		{
			if(each.enabled)
			{
				((IOrderCallbacks)each).OnStopOrderReceived(a_order);
			}
		}
	}
Esempio n. 7
0
 public SellStopOrder(StopOrder order) : base(order)
 {
 }
Esempio n. 8
0
		public Order StopOrder(OrderSide side, double qty, double stopPrice, string text)
		{
			SingleOrder singleOrder;
			if (side == OrderSide.Buy)
			{
				singleOrder = new StopOrder(this.sq_Instrument, Side.Buy, qty, stopPrice, text);
			}
			else
			{
				singleOrder = new StopOrder(this.sq_Instrument, Side.Sell, qty, stopPrice, text);
			}
			singleOrder.Strategy = this.strategyName;
			Order order = new Order(singleOrder);
			order.Portfolio = this.portfolio;
			Map.OQ_SQ_Order[order] = singleOrder;
			Map.SQ_OQ_Order[singleOrder] = order;
			return order;
		}
Esempio n. 9
0
 public void OnStopOrder(StopOrder stopOrder)
 {
     StopOrder?.Invoke(_quik, stopOrder);
 }
Esempio n. 10
0
        public void Invoke(IEvent @event)
        {
            if (@event == null)
            {
                Trace.WriteLine("Trace: ProcessCallbackMessage(). message = NULL");
                throw new ArgumentNullException(nameof(@event));
            }

            // TODO use as instead of assert+is+cast
            switch (@event.Name)
            {
            case EventName.AccountBalance:
                Trace.Assert(@event is Event <AccountBalance>);
                var accountBalance = ((Event <AccountBalance>)@event).Data;
                _quikEventsInvoker.OnAccountBalance(accountBalance);
                break;

            case EventName.AccountPosition:
                Trace.Assert(@event is Event <AccountPosition>);
                var accPos = ((Event <AccountPosition>)@event).Data;
                _quikEventsInvoker.OnAccountPosition(accPos);
                break;

            case EventName.AllTrade:
                Trace.Assert(@event is Event <AllTrade>);
                var allTrade = ((Event <AllTrade>)@event).Data;
                allTrade.LuaTimeStamp = @event.CreatedTime;
                _quikEventsInvoker.OnAllTrade(allTrade);
                break;

            case EventName.CleanUp:
                Trace.Assert(@event is Event <string>);
                _quikEventsInvoker.OnCleanUp();
                break;

            case EventName.Close:
                Trace.Assert(@event is Event <string>);
                _quikEventsInvoker.OnClose();
                break;

            case EventName.Connected:
                Trace.Assert(@event is Event <string>);
                _quikEventsInvoker.OnConnected();
                break;

            case EventName.DepoLimit:
                Trace.Assert(@event is Event <DepoLimitEx>);
                var dLimit = ((Event <DepoLimitEx>)@event).Data;
                _quikEventsInvoker.OnDepoLimit(dLimit);
                break;

            case EventName.DepoLimitDelete:
                Trace.Assert(@event is Event <DepoLimitDelete>);
                var dLimitDel = ((Event <DepoLimitDelete>)@event).Data;
                _quikEventsInvoker.OnDepoLimitDelete(dLimitDel);
                break;

            case EventName.Disconnected:
                Trace.Assert(@event is Event <string>);
                _quikEventsInvoker.OnDisconnected();
                break;

            case EventName.Firm:
                Trace.Assert(@event is Event <Firm>);
                var frm = ((Event <Firm>)@event).Data;
                _quikEventsInvoker.OnFirm(frm);
                break;

            case EventName.FuturesClientHolding:
                Trace.Assert(@event is Event <FuturesClientHolding>);
                var futPos = ((Event <FuturesClientHolding>)@event).Data;
                _quikEventsInvoker.OnFuturesClientHolding(futPos);
                break;

            case EventName.FuturesLimitChange:
                Trace.Assert(@event is Event <FuturesLimits>);
                var futLimit = ((Event <FuturesLimits>)@event).Data;
                _quikEventsInvoker.OnFuturesLimitChange(futLimit);
                break;

            case EventName.FuturesLimitDelete:
                Trace.Assert(@event is Event <FuturesLimitDelete>);
                var limDel = ((Event <FuturesLimitDelete>)@event).Data;
                _quikEventsInvoker.OnFuturesLimitDelete(limDel);
                break;

            case EventName.Init:
                // Этот callback никогда не будет вызван так как на момент получения вызова OnInit в lua скрипте
                // соединение с библиотекой QuikSharp не будет еще установлено. То есть этот callback не имеет смысла.
                break;

            case EventName.MoneyLimit:
                Trace.Assert(@event is Event <MoneyLimitEx>);
                var mLimit = ((Event <MoneyLimitEx>)@event).Data;
                _quikEventsInvoker.OnMoneyLimit(mLimit);
                break;

            case EventName.MoneyLimitDelete:
                Trace.Assert(@event is Event <MoneyLimitDelete>);
                var mLimitDel = ((Event <MoneyLimitDelete>)@event).Data;
                _quikEventsInvoker.OnMoneyLimitDelete(mLimitDel);
                break;

            case EventName.NegDeal:
                break;

            case EventName.NegTrade:
                break;

            case EventName.Order:
                Trace.Assert(@event is Event <Order>);
                var ord = ((Event <Order>)@event).Data;
                ord.LuaTimeStamp = @event.CreatedTime;
                _quikEventsInvoker.OnOrder(ord);
                break;

            case EventName.Param:
                Trace.Assert(@event is Event <Param>);
                var data = ((Event <Param>)@event).Data;
                _quikEventsInvoker.OnParam(data);
                break;

            case EventName.Quote:
                Trace.Assert(@event is Event <OrderBook>);
                var ob = ((Event <OrderBook>)@event).Data;
                ob.LuaTimeStamp = @event.CreatedTime;
                _quikEventsInvoker.OnQuote(ob);
                break;

            case EventName.Stop:
                Trace.Assert(@event is Event <string>);
                _quikEventsInvoker.OnStop(int.Parse(((Event <string>)@event).Data));
                break;

            case EventName.StopOrder:
                Trace.Assert(@event is Event <StopOrder>);
                StopOrder stopOrder = ((Event <StopOrder>)@event).Data;
                _quikEventsInvoker.OnStopOrder(stopOrder);
                break;

            case EventName.Trade:
                Trace.Assert(@event is Event <Trade>);
                var trade = ((Event <Trade>)@event).Data;
                trade.LuaTimeStamp = @event.CreatedTime;
                _quikEventsInvoker.OnTrade(trade);
                break;

            case EventName.TransReply:
                Trace.Assert(@event is Event <TransactionReply>);
                var trReply = ((Event <TransactionReply>)@event).Data;
                trReply.LuaTimeStamp = @event.CreatedTime;
                _quikEventsInvoker.OnTransReply(trReply);
                break;

            case EventName.Candle:
                Trace.Assert(@event is Event <Candle>);
                var candle = ((Event <Candle>)@event).Data;
                _quikEventsInvoker.OnCandle(candle);
                break;

            case EventName.Error:
                Trace.Assert(@event is Event <string>);
                var error = ((Event <string>)@event).Data;
                Trace.TraceError(error);
                _quikEventsInvoker.OnError(error);
                break;

            default:
                throw new EventTypeNotSupportedException($"Тип события: '{@event.Name}' не поддерживается.");
            }
        }
Esempio n. 11
0
        private void OnAddRow(int OpenID, int RowID, object Fields)
        {
            object[] fields = (object[])Fields;

            if (_all_trades_table != null && OpenID == _all_trades_table.ID)
            {
                if (RowID <= _allTrades_lastRowID)
                {
                    return;
                }
                _allTrades_lastRowID = RowID;

                string secboard = Convert.ToString(fields[5]).Trim();
                if (secboard != _secBoard)
                {
                    return;
                }

                string   ticker  = Convert.ToString(fields[6]).Trim();
                long     tradeNo = Convert.ToInt64(fields[2]);
                DateTime msktime = Convert.ToDateTime(fields[3]).AddHours(_addHours);
                if (msktime.TimeOfDay < _startSessionMskTime)
                {
                    msktime = new DateTime(msktime.Year, msktime.Month, msktime.Day, _startSessionMskTime.Hours, _startSessionMskTime.Minutes, _startSessionMskTime.Seconds);
                }
                if (msktime.TimeOfDay > _endSessionMskTime)
                {
                    msktime = new DateTime(msktime.Year, msktime.Month, msktime.Day, _endSessionMskTime.Hours, _endSessionMskTime.Minutes, _endSessionMskTime.Seconds);
                }

                int    lots  = Convert.ToInt32(fields[8]);
                double price = Convert.ToDouble(fields[9]);

                Common.Data.Instrum ins = _instrumTable.GetInstrum(ticker);
                if (ins == null)
                {
                    return;
                }

                _tickDispatcher.AddTick(new Tick(tradeNo, msktime, ins.InsID, lots, (decimal)price));
            }
            else if (_securities_table != null && OpenID == _securities_table.ID)
            {
                if (RowID <= _securities_lastRowID)
                {
                    return;
                }
                _securities_lastRowID = RowID;

                string secboard = Convert.ToString(fields[1]).Trim();
                if (secboard != _secBoard)
                {
                    return;
                }

                string  ticker    = Convert.ToString(fields[2]).Trim();
                string  name      = Convert.ToString(fields[3]).Trim();
                string  shortname = Convert.ToString(fields[4]).Trim();
                int     lotsize   = Convert.ToInt32(fields[13]);
                decimal pricestep = Convert.ToDecimal(fields[15]);
                int     decimals  = Convert.ToInt32(fields[17]);

                _instrumTable.SyncInstrum(ticker, shortname, name, lotsize, decimals, pricestep);
            }
            else if (_trdacc_table != null && OpenID == _trdacc_table.ID)
            {
                string account = Convert.ToString(fields[1]).Trim();
                string name    = Convert.ToString(fields[2]).Trim();
                _accountTable.AddAccount(account, name);
            }
            else if (_orders_table != null && OpenID == _orders_table.ID)
            {
                var ticker = Convert.ToString(fields[21]).Trim();
                var ins    = _instrumTable.GetInstrum(ticker);
                if (ins == null)
                {
                    return;
                }

                string accCode = Convert.ToString(fields[19]).Trim();
                var    acc     = _accountTable.GetAccount(accCode);
                if (acc == null)
                {
                    return;
                }

                Order order = new Order();
                order.OrderNo   = Convert.ToInt64(fields[1]);
                order.Time      = Convert.ToDateTime(fields[3]).AddHours(_addHours);
                order.InsID     = ins.InsID;
                order.AccountID = acc.AccountID;

                var bs = Convert.ToString(fields[12]).Trim();
                order.BuySell = bs == "B" ? BuySell.Buy : BuySell.Sell;

                order.LotCount = Convert.ToInt32(fields[25]);

                order.Price = Convert.ToDecimal(fields[23]);
                if (order.Price == 0)
                {
                    order.Price = null;
                }

                var status = Convert.ToString(fields[10]).Trim();
                if (status == "M")
                {
                    order.Status = OrderStatus.Trade;
                }
                else if (status == "C")
                {
                    order.Status = OrderStatus.EndTime;
                }
                else if (status == "N")
                {
                    order.Status = OrderStatus.Reject;
                }
                else if (status == "W")
                {
                    order.Status = OrderStatus.Remove;
                }
                else
                {
                    order.Status = OrderStatus.Active; // A, O
                }
                _orderTable.AddOrder(order);
            }
            else if (_stoporders_table != null && OpenID == _stoporders_table.ID)
            {
                string secboard = Convert.ToString(fields[4]).Trim();
                if (secboard != _secBoard)
                {
                    return;
                }

                var ticker = Convert.ToString(fields[5]).Trim();
                var ins    = _instrumTable.GetInstrum(ticker);
                if (ins == null)
                {
                    return;
                }

                string accCode = Convert.ToString(fields[21]).Trim();
                var    acc     = _accountTable.GetAccount(accCode);
                if (acc == null)
                {
                    return;
                }

                StopOrder so = new StopOrder();
                so.StopOrderNo = Convert.ToInt64(fields[3]);
                so.Time        = Convert.ToDateTime(fields[1]).AddHours(_addHours);
                so.InsID       = ins.InsID;
                so.AccountID   = acc.AccountID;

                var bs = Convert.ToString(fields[6]).Trim();
                so.BuySell = bs == "B" ? BuySell.Buy : BuySell.Sell;

                var st = Convert.ToString(fields[10]).Trim();
                so.StopType = StopOrderType.TakeProfit;
                if (st == "L")
                {
                    so.StopType = StopOrderType.StopLoss;
                }
                else if (st == "P")
                {
                    so.StopType = StopOrderType.TakeProfit;
                }

                so.AlertPrice = Convert.ToDecimal(fields[13]);

                so.Price = Convert.ToDecimal(fields[14]);
                if (so.Price == 0)
                {
                    so.Price = null;
                }

                so.LotCount = Convert.ToInt32(fields[15]);
                var status = Convert.ToString(fields[18]).Trim();
                if (status == "M")
                {
                    so.Status = StopOrderStatus.Order;
                }
                else if (status == "E")
                {
                    so.Status = StopOrderStatus.EndTime;
                }
                else if (status == "R")
                {
                    so.Status = StopOrderStatus.Reject;
                }
                else if (status == "W")
                {
                    so.Status = StopOrderStatus.Remove;
                }
                else
                {
                    so.Status = StopOrderStatus.Active; // A, O, space
                }
                so.EndTime = (DateTime?)fields[11];     // если время не указать, то сначала оно будет null, а потом сработает update, поменяется статус на Активный и время завершения установится на конец торговой сессии
                if (so.EndTime != null)
                {
                    so.EndTime = so.EndTime.Value.AddHours(_addHours);
                }
                _stopOrderTable.AddStopOrder(so, GetCurrentTime());
            }
            else if (_trades_table != null && OpenID == _trades_table.ID)
            {
                var ticker = Convert.ToString(fields[6]).Trim();
                var ins    = _instrumTable.GetInstrum(ticker);
                if (ins == null)
                {
                    return;
                }

                string accCode = Convert.ToString(fields[29]).Trim();
                var    acc     = _accountTable.GetAccount(accCode);
                if (acc == null)
                {
                    return;
                }

                long  orderNo = Convert.ToInt64(fields[2]);
                Order order   = _orderTable.GetOrder(orderNo);
                if (order == null)
                {
                    return;
                }

                Trade trade = new Trade();
                trade.TradeNo   = Convert.ToInt64(fields[1]);
                trade.OrderID   = order.OrderID;
                trade.Time      = Convert.ToDateTime(fields[3]).AddHours(_addHours);
                trade.InsID     = ins.InsID;
                trade.AccountID = acc.AccountID;
                var bs = Convert.ToString(fields[8]).Trim();
                trade.BuySell  = bs == "B" ? BuySell.Buy : BuySell.Sell;
                trade.LotCount = Convert.ToInt32(fields[9]);
                trade.Price    = Convert.ToDecimal(fields[10]);

                _tradeTable.AddTrade(trade);
            }
            else if (_holding_table != null && OpenID == _holding_table.ID)
            {
                var ticker = Convert.ToString(fields[5]).Trim();
                var ins    = _instrumTable.GetInstrum(ticker);
                if (ins == null)
                {
                    return;
                }

                var acc = _accountTable.GetDefaultAccount();
                if (acc == null)
                {
                    return;
                }

                int lots = Convert.ToInt32(fields[8]);
                _holdingTable.SetHolding(acc.AccountID, ins.InsID, lots);
            }
            else if (_positions_table != null && OpenID == _positions_table.ID)
            {
                string accCode = Convert.ToString(fields[2]).Trim();
                var    acc     = _accountTable.GetAccount(accCode);
                if (acc == null)
                {
                    return;
                }

                double  pos    = Convert.ToDouble(fields[11]);
                decimal curPos = (decimal)pos;
                _positionTable.SetPosition(acc.AccountID, curPos);
            }
        }
Esempio n. 12
0
 public void RemoveStopOrder(StopOrder so)
 {
     _engine.RemoveStopOrder(so);
 }
Esempio n. 13
0
        protected void SendStopOrder(PanelControl panel, bool autoStop = false, bool showInfo = false)
        {
            if (autoStop)
            {
                if (panel.LastSendStopOrder > DateTime.Now.AddSeconds(-5))
                {
                    //Для избежания многократного выставления
                    return;
                }
            }
            var     pos      = Parent.Trader.Objects.tPositions.SearchFirst(p => p.Sec == panel.TrElement.Security);
            decimal stepStop = panel.TrElement.Security.Params.MinPriceStep * 20;
            int     volume   = pos.NotIsNull() ? pos.Data.CurrentNet : 0;

            if (volume < 0)
            {
                stepStop = stepStop * -1;
                volume   = volume * -1;
            }
            //Просмотр инфо по будущему стопу
            if (showInfo)
            {
                string text = "Инфо создаваемой стоп заявки:\n";
                text += "Позиций: " + pos.Data.CurrentNet + "\n\n";
                text += "Стоп цена: " + panel.PriceStop.Value + "\n";
                text += "Цена исполнения: " + (panel.PriceStop.Value - stepStop) + "\n";
                text += "Объем: " + volume + "\n";
                text += "Дата завершения: " + DateTime.Now.AddDays(1).ToShortDateString() + "\n";
                MessageBox.Show(text);
                return;
            }

            if (panel.PriceStop.Value == 0)
            {
                SetMessage("Некорректная цена стоп-ордера!");
                return;
            }
            if (volume == 0)
            {
                SetMessage("Не текущих позиций!");
                return;
            }
            var stopOrder = new StopOrder()
            {
                Sec            = panel.TrElement.Security,
                Price          = panel.PriceStop.Value - stepStop,
                Volume         = volume,
                Direction      = volume > 0 ? OrderDirection.Sell : OrderDirection.Buy,
                ConditionPrice = panel.PriceStop.Value,
                DateExpiry     = DateMarket.ExtractDateTime(DateTime.Now.AddDays(1)),
                Comment        = Define.STOP_LOSS
            };
            var lastPrice = panel.TrElement.Security.LastPrice;

            if (lastPrice > 0)
            {
                if (pos.IsBuy() && panel.PriceStop.Value > 0)
                {
                    stopOrder.Direction = OrderDirection.Sell;
                    if (panel.PriceStop.Value > lastPrice)
                    {
                        SetMessage("Не корректная цена стоп заявки! Необходимо указать цену ниже текущей.");
                        return;
                    }
                }
                if (pos.IsSell() && panel.PriceStop.Value > 0)
                {
                    stopOrder.Direction = OrderDirection.Buy;
                    if (panel.PriceStop.Value < lastPrice)
                    {
                        SetMessage("Не корректная цена стоп заявки! Необходимо указать цену выше текущей.");
                        return;
                    }
                }
            }

            MThread.InitThread(ThreadPriority.Normal, () =>
            {
                Qlog.CatchException(() =>
                {
                    Thread.Sleep(1000);
                    var countClosed = CancelAllStopOrders(panel);
                    Thread.Sleep(1000);
                    Parent.Trader.CreateStopOrder(stopOrder, StopOrderType.StopLimit);
                    addSignalByStop(stopOrder);
                });
            });
            panel.LastSendStopOrder = DateTime.Now;
        }
Esempio n. 14
0
        /// <summary>
        /// Проверка и выставление стоп-ордера
        /// </summary>
        /// <param name="Price"></param>
        /// <param name="volume"></param>
        public void SetStopOrder(decimal Price, int volume, bool checkSet = true)
        {
            if (Price == 0)
            {
                ShowTransReply("Некорректная цена стоп-ордера!");
                return;
            }
            if (volume == 0)
            {
                ShowTransReply("Не текущих позиций!");
                return;
            }
            decimal stepStop = Securities.Params.MinPriceStep * 20;

            if (volume < 0)
            {
                stepStop = stepStop * -1;
                volume   = volume * -1;
            }
            var stopOrder = new StopOrder()
            {
                Sec            = Securities,
                Price          = Price - stepStop,
                Volume         = volume,
                ConditionPrice = Price,
                DateExpiry     = DateMarket.ExtractDateTime(dateTimePickerStopOrder.Value),
                ClientCode     = ClientCode.Value,
                Comment        = Define.STOP_LOSS
            };

            if (this.Position.IsBuy() && Price > 0)
            {
                stopOrder.Direction = OrderDirection.Sell;
                if (Price > Securities.LastPrice)
                {
                    ShowTransReply("Не корректная цена стоп заявки! Необходимо указать цену ниже текущей.");
                    return;
                }
            }
            if (this.Position.IsSell() && Price > 0)
            {
                stopOrder.Direction = OrderDirection.Buy;
                if (Price < Securities.LastPrice)
                {
                    ShowTransReply("Не корректная цена стоп заявки! Необходимо указать цену выше текущей.");
                    return;
                }
            }
            //Устанавливаем в форму значение стоп цены
            this.GuiAsync(() =>
            {
                numericUpDownStopPrice.Value = Price;
            });
            MThread.InitThread(() =>
            {
                var cancelOrders = this.Trader.Objects.tStopOrders.SearchAll(so => so.Sec == Securities &&
                                                                             so.IsActive() && so.Comment.Contains(Define.STOP_LOSS));
                if (cancelOrders.NotIsNull())
                {
                    this.Trader.CancelListStopOrders(cancelOrders);
                }
                Thread.Sleep(500);
                this.Trader.CreateStopOrder(stopOrder, StopOrderType.StopLimit);
                if (checkSet)
                {
                    Thread.Sleep(10000);
                    var allStopOrders = this.Trader.Objects.tStopOrders.SearchAll(so => so.Sec == Securities && so.IsActive());
                    if (allStopOrders.NotIsNull())
                    {
                        if (allStopOrders.Count() == 0)
                        {
                            this.SetStopOrder(Price, volume, false);
                        }
                    }
                }
            });
        }
Esempio n. 15
0
        public void OnTick(params Tick[] ticks)
        {
            //Update the current market.

            foreach (Tick t in ticks)
            {
                if (!currentOffers.ContainsKey(t.Symbol))
                {
                    currentOffers.Add(t.Symbol, t);
                }
                else
                {
                    currentOffers[t.Symbol] = t;
                }
            }


            //-----------------------------------------------------------
            // On each tick, we must check for stop and limit order hits.
            //-----------------------------------------------------------

            foreach (Tick t in ticks)
            {
                //------------------------------------------------------
                // Stop Order Check
                //------------------------------------------------------

                if (_outStandingStopOrders.ContainsKey(t.Symbol))
                {
                    StopOrder stopOrder = _outStandingStopOrders[t.Symbol];

                    //If trailing, need to relcalculate trigger price.
                    if (stopOrder.Trailing)
                    {
                        stopOrder.RecalculateTrail(t);
                    }

                    //Trigger stop if price drops -below- Buy Stop Trigger
                    if (stopOrder.IsBuyStop())
                    {
                        //net stop to close all
                        if (t.BidLow <= stopOrder.TriggerPrice)
                        {
                            CloseStopOrder(t, stopOrder);
                        }
                    }

                    //Trigger stop if price rises -above- Sell Stop Trigger
                    else if (stopOrder.IsSellStop())
                    {
                        if (t.AskHigh >= stopOrder.TriggerPrice)
                        {
                            CloseStopOrder(t, stopOrder);
                        }
                    }
                }


                //------------------------------------------------------
                // Limit Order Check
                //------------------------------------------------------

                if (_outStandingLimitOrders.ContainsKey(t.Symbol))
                {
                    LimitOrder limitOrder = _outStandingLimitOrders[t.Symbol];

                    //If trailing, need to relcalculate trigger price.
                    if (limitOrder.Trailing)
                    {
                        limitOrder.RecalculateTrail(t);
                    }

                    //Trigger limit if price goes -above- Buy Limit Trigger
                    if (limitOrder.IsBuyLimit())
                    {
                        //net limit to close all
                        if (t.BidClose >= limitOrder.TriggerPrice)
                        {
                            CloseLimitOrder(t, limitOrder);
                        }
                    }

                    //Trigger limit if price drops -below- Limit Stop Trigger
                    else if (limitOrder.IsSellLimit())
                    {
                        if (t.AskClose <= limitOrder.TriggerPrice)
                        {
                            CloseLimitOrder(t, limitOrder);
                        }
                    }
                }
            }


            //-----------------------------------------------------------
            // Adjust portfolio equity/margin
            //-----------------------------------------------------------

            _portfolio.AdjustPortfolioEquityAndMargin(ticks);
        }
Esempio n. 16
0
 private void buttonCreateStopOrder_Click(object sender, EventArgs e)
 {
     try
     {
         decimal Price = numericUpDownStopPrice.Value;
         if (this.Position.Data.CurrentNet == 0)
         {
             UpdateTransReply("Позиций не открыто!");
             return;
         }
         if (this.Position.Data.CurrentNet > 0 && Price > 0)
         {
             var stopOrder = new StopOrder()
             {
                 Direction      = OrderDirection.Sell,
                 Sec            = this.TrElement.Security,
                 Price          = Price - this.TrElement.Security.Params.MinPriceStep * 20,
                 Volume         = this.Position.Data.CurrentNet,
                 ConditionPrice = Price,
                 DateExpiry     = dateTimePickerStopOrder.Value
             };
             if (Price > this.TrElement.Security.LastTrade.Price)
             {
                 UpdateTransReply("Не корректная цена стоп заявки! Необходимо указать цену ниже текущей.");
             }
             else
             {
                 this.Trader.CancelAllStopOrder(this.TrElement.Security);
                 this.Trader.CreateStopOrder(stopOrder, StopOrderType.StopLimit);
                 Common.Ext.NewThread(() =>
                 {
                     Thread.Sleep(300);
                     this.UpdateDepth();
                 });
             }
         }
         if (this.Position.Data.CurrentNet < 0 && Price > 0)
         {
             var stopOrder = new StopOrder()
             {
                 Direction      = OrderDirection.Buy,
                 Sec            = this.TrElement.Security,
                 Price          = Price + this.TrElement.Security.Params.MinPriceStep * 20,
                 Volume         = this.Position.Data.CurrentNet * -1,
                 ConditionPrice = Price,
                 DateExpiry     = dateTimePickerStopOrder.Value
             };
             if (Price < this.TrElement.Security.LastTrade.Price)
             {
                 UpdateTransReply("Не корректная цена стоп заявки! Необходимо указать цену выше текущей.");
             }
             else
             {
                 this.Trader.CancelAllStopOrder(this.TrElement.Security);
                 this.Trader.CreateStopOrder(stopOrder, StopOrderType.StopLimit);
             }
         }
     }
     catch (Exception ee)
     {
         MessageBox.Show(ee.ToString());
     }
 }
Esempio n. 17
0
 public void PlaceStopOrder(StopOrder stop)
 {
     _outStandingStopOrders.Add(stop.Symbol, stop);
 }
Esempio n. 18
0
 public bool StopLimit(StopOrder order, decimal price)
 {
     return(price < order.StopLimitPrice);
 }
Esempio n. 19
0
 internal void RaiseNewStopOrderEvent(StopOrder stopOrder)
 {
     if (NewStopOrder != null)
         NewStopOrder(stopOrder);
 }
Esempio n. 20
0
        private async void CreateStopOrder(Condition condition, Operation operation, decimal condPrice, decimal condPrice2, decimal price, int qty, decimal pricePosition)
        {
            StopOrder orderNew = new StopOrder()
            {
                Account          = _tool.AccountID,
                ClassCode        = _tool.ClassCode,
                ClientCode       = commentStop, // clientCode,
                SecCode          = secCode,
                StopOrderType    = StopOrderType.TakeProfitStopLimit,
                Condition        = condition,
                Operation        = operation,
                ConditionPrice   = (decimal)Math.Round(condPrice, _tool.PriceAccuracy),
                Price            = (decimal)Math.Round(price, _tool.PriceAccuracy),
                ConditionPrice2  = (decimal)Math.Round(condPrice2, _tool.PriceAccuracy),
                Offset           = 0,
                OffsetUnit       = OffsetUnits.PRICE_UNITS,
                Spread           = 0,
                SpreadUnit       = OffsetUnits.PRICE_UNITS,
                MarketStopLimit  = YesOrNo.YES,
                MarketTakeProfit = YesOrNo.YES,
                Quantity         = qty
                                   //Comment = comment
            };

            try
            {
                //var res = _quik.StopOrders.CreateStopOrder(orderNew);
                long transID = await _quik.StopOrders.CreateStopOrder(orderNew).ConfigureAwait(false);

                Log("Выставили тейк-профит стоп-лимит на " + orderNew.Operation + " по цене стоп " + orderNew.ConditionPrice2 + " тейк " + orderNew.ConditionPrice + " TransID " + transID);
                if (transID > 0)
                {
                    Log("Стоп-заявка выставлена. ID транзакции - " + transID);
                    stopTransId = transID;

                    Thread.Sleep(1000);
                    try
                    {
                        var listStopOrders = _quik.StopOrders.GetStopOrders().Result;
                        foreach (StopOrder stopOrder in listStopOrders)
                        {
                            if (stopOrder.TransId == transID && stopOrder.ClassCode == _tool.ClassCode && stopOrder.SecCode == _tool.SecurityCode)
                            {
                                strategy.StopOrderNum = stopOrder.OrderNum;
                                Log("Стоп-заявка номер " + stopOrder.OrderNum + " выставлена");
                            }
                        }
                        strategy.Name          = comment;
                        strategy.IsActive      = true;
                        strategy.PricePosition = pricePosition;
                        strategy.Operation     = orderNew.Operation;
                        strategy.Condition     = condition;
                        strategy.CondPrice     = orderNew.ConditionPrice;
                        strategy.CondPrice2    = orderNew.ConditionPrice2;
                        strategy.Price         = orderNew.Price;
                        strategy.Qty           = qty;

                        UpdateLabelStrategy();
                        Save2File();
                    }
                    catch { Log("Ошибка получения номера стоп-заявки."); }
                }
                else
                {
                    Log("Неудачная попытка выставления стоп-заявки.");
                }
            }
            catch (Exception exception)
            {
                Log("Ошибка выставления заявки CreateStopOrder " + exception);
            }
        }
Esempio n. 21
0
 public async Task<long> KillStopOrder(StopOrder stopOrder)
 {
     Transaction killStopOrderTransaction = new Transaction
     {
         ACTION = TransactionAction.KILL_STOP_ORDER,
         CLASSCODE = stopOrder.ClassCode,
         SECCODE = stopOrder.SecCode,
         STOP_ORDER_KEY = stopOrder.OrderNum.ToString()
     };
     return await Quik.Trading.SendTransaction(killStopOrderTransaction);
 }
Esempio n. 22
0
        public void TestSendNumLotsDissallowNegative()
        {
            var order = new StopOrder(new SOrderParameters());

            Assert.Throws <ArgumentOutOfRangeException>(() => order.Send(20, -100));
        }
Esempio n. 23
0
		public Order SellStopOrder(Instrument instrument, double qty, double stopPrice, string text)
		{
			SingleOrder singleOrder = new StopOrder(instrument.instrument, Side.Sell, qty, stopPrice, text);
			singleOrder.Strategy = this.strategyName;
			Order order = new Order(singleOrder);
			order.Portfolio = this.portfolio;
			Map.OQ_SQ_Order[order] = singleOrder;
			Map.SQ_OQ_Order[singleOrder] = order;
			return order;
		}
Esempio n. 24
0
 /// <summary>
 ///
 /// </summary>
 public void AutoSLLoopControl()
 {
     if (TimeControl.AddSeconds(PERIOD_CONTROL_SEC) > DateTime.Now)
     {
         return;
     }
     TimeControl = DateTime.Now;
     MThread.InitThread(() =>
     {
         foreach (var objControl in ASLObject.ToArray)
         {
             var sec = GetSecCodeAndClass(objControl.SecAndCode);
             if (sec.NotIsNull())
             {
                 var pos = Trader.Objects.tPositions.SearchFirst(p => p.Sec == sec);
                 if (pos.NotIsNull())
                 {
                     var stopLoss = Trader.Objects.tStopOrders.SearchAll(o => o.Sec == sec &&
                                                                         o.IsActive() && o.Comment.Contains(Define.STOP_LOSS)
                                                                         );
                     var volume = pos.CurrentVolume;
                     //Проверяем, не появились ли лишние стоп ордера
                     if (stopLoss.Count() > 1)
                     {
                         Trader.CancelAllStopOrder(sec);
                         continue;
                     }
                     //Проверяем не изменилась ли позиция
                     else if (stopLoss.Count() == 1)
                     {
                         var activeStop = stopLoss.ElementAt(0);
                         //Снимаем стоп если разные обьемы
                         if (activeStop.Volume != volume)
                         {
                             Trader.CancelAllStopOrder(sec);
                             continue;
                         }
                         //Снимаем стоп если он в другую сторону
                         if (activeStop.IsBuy() && pos.IsBuy())
                         {
                             Trader.CancelAllStopOrder(sec);
                             continue;
                         }
                     }
                     else if (stopLoss.Count() == 0 && pos.CurrentVolume > 0)
                     {
                         var allTrades = Trader.Objects.tMyTrades.SearchAll(t => t.Trade.Sec == sec)
                                         .OrderByDescending(o => o.Trade.Number);
                         if (allTrades.NotIsNull())
                         {
                             decimal Price = 0;
                             if (allTrades.Count() > 0)
                             {
                                 var lastTrade = allTrades.FirstOrDefault(o => o.Trade.Direction == pos.CurrentDirection);
                                 if (lastTrade.NotIsNull())
                                 {
                                     Price = lastTrade.Trade.Price;
                                 }
                             }
                             if (Price == 0)
                             {
                                 Price = sec.LastPrice;
                             }
                             var tiks      = objControl.Tiks;
                             var stopOrder = new StopOrder()
                             {
                                 Sec        = sec,
                                 Price      = Price,
                                 ClientCode = objControl.Comment,
                                 Comment    = Define.STOP_LOSS,
                                 Volume     = volume,
                                 DateExpiry = DateMarket.ExtractDateTime(DateTime.Now.AddDays(10))
                             };
                             if (pos.IsBuy())
                             {
                                 stopOrder.Direction      = OrderDirection.Sell;
                                 stopOrder.ConditionPrice = Price - sec.MinPriceStep * tiks;
                                 stopOrder.Price          = stopOrder.ConditionPrice - sec.MinPriceStep * 10;
                             }
                             else if (pos.IsSell())
                             {
                                 stopOrder.Direction      = OrderDirection.Buy;
                                 stopOrder.ConditionPrice = Price + sec.MinPriceStep * tiks;
                                 stopOrder.Price          = stopOrder.ConditionPrice + sec.MinPriceStep * 10;
                             }
                             Trader.CreateStopOrder(stopOrder, StopOrderType.StopLimit);
                             AutoSLLog("Create order: " + sec.ToString() + " " +
                                       (stopOrder.IsBuy() ? "B" : "S") +
                                       " " + stopOrder.ConditionPrice);
                         }
                     }
                 }
             }
         }
     });
 }
Esempio n. 25
0
        private async Task CallCommand()
        {
            string selectedCommand = listBoxCommands.SelectedItem.ToString();

            switch (selectedCommand)
            {
            case "Получить исторические данные":
                try
                {
                    AppendText2TextBox(textBoxLogsWindow, "Подписываемся на получение исторических данных..." + Environment.NewLine);
                    _quik.Candles.Subscribe(tool.ClassCode, tool.SecurityCode, CandleInterval.H1).Wait();
                    AppendText2TextBox(textBoxLogsWindow, "Проверяем состояние подписки..." + Environment.NewLine);
                    isSubscribedToolCandles = _quik.Candles.IsSubscribed(tool.ClassCode, tool.SecurityCode, CandleInterval.H1).Result;
                    if (isSubscribedToolCandles)
                    {
                        AppendText2TextBox(textBoxLogsWindow, "Получаем исторические данные..." + Environment.NewLine);
                        toolCandles = _quik.Candles.GetAllCandles(tool.ClassCode, tool.SecurityCode, CandleInterval.H1).Result;
                        AppendText2TextBox(textBoxLogsWindow, "Выводим исторические данные в таблицу..." + Environment.NewLine);
                        toolCandlesTable = new FormOutputTable(toolCandles);
                        toolCandlesTable.Show();
                    }
                    else
                    {
                        AppendText2TextBox(textBoxLogsWindow, "Неудачная попытка подписки на исторические данные." + Environment.NewLine);
                    }
                }
                catch { AppendText2TextBox(textBoxLogsWindow, "Ошибка получения исторических данных." + Environment.NewLine); }
                break;

            case "Выставить лимитрированную заявку (без сделки)":
                try
                {
                    decimal priceInOrder = Math.Round(tool.LastPrice - tool.LastPrice / 20, tool.PriceAccuracy);
                    AppendText2TextBox(textBoxLogsWindow, "Выставляем заявку на покупку, по цене:" + priceInOrder + " ..." + Environment.NewLine);
                    order = await _quik.Orders.SendLimitOrder(tool.ClassCode, tool.SecurityCode, tool.AccountID, Operation.Buy, priceInOrder, 1).ConfigureAwait(false);

                    if (order.OrderNum > 0)
                    {
                        AppendText2TextBox(textBoxLogsWindow, "Заявка выставлена. ID транзакции - " + order.TransID + Environment.NewLine);
                        AppendText2TextBox(textBoxLogsWindow, "Заявка выставлена. Номер заявки - " + order.OrderNum + Environment.NewLine);
                        Text2TextBox(textBoxOrderNumber, order.OrderNum.ToString());
                    }
                    else
                    {
                        AppendText2TextBox(textBoxLogsWindow, "Неудачная попытка размещения заявки. Error: " + order.RejectReason + Environment.NewLine);
                    }
                }
                catch (Exception er) { textBoxLogsWindow.AppendText("Ошибка процедуры размещения заявки. Error: " + er.Message + Environment.NewLine); }
                break;

            case "Выставить лимитрированную заявку (c выполнением!!!)":
                try
                {
                    decimal priceInOrder = Math.Round(tool.LastPrice + tool.Step * 5, tool.PriceAccuracy);
                    AppendText2TextBox(textBoxLogsWindow, "Выставляем заявку на покупку, по цене:" + priceInOrder + " ..." + Environment.NewLine);
                    long transactionID = (await _quik.Orders.SendLimitOrder(tool.ClassCode, tool.SecurityCode, tool.AccountID, Operation.Buy, priceInOrder, 1).ConfigureAwait(false)).TransID;
                    if (transactionID > 0)
                    {
                        AppendText2TextBox(textBoxLogsWindow, "Заявка выставлена. ID транзакции - " + transactionID + Environment.NewLine);
                        Thread.Sleep(500);
                        try
                        {
                            listOrders = _quik.Orders.GetOrders().Result;
                            foreach (Order _order in listOrders)
                            {
                                if (_order.TransID == transactionID && _order.ClassCode == tool.ClassCode && _order.SecCode == tool.SecurityCode)
                                {
                                    AppendText2TextBox(textBoxLogsWindow, "Заявка выставлена. Номер заявки - " + _order.OrderNum + Environment.NewLine);
                                    Text2TextBox(textBoxOrderNumber, _order.OrderNum.ToString());
                                    order = _order;
                                }
                                else
                                {
                                    Text2TextBox(textBoxOrderNumber, "---");
                                }
                            }
                        }
                        catch { AppendText2TextBox(textBoxLogsWindow, "Ошибка получения номера заявки." + Environment.NewLine); }
                    }
                    else
                    {
                        AppendText2TextBox(textBoxLogsWindow, "Неудачная попытка выставления заявки." + Environment.NewLine);
                    }
                }
                catch { AppendText2TextBox(textBoxLogsWindow, "Ошибка выставления заявки." + Environment.NewLine); }
                break;

            case "Выставить рыночную заявку (c выполнением!!!)":
                try
                {
                    decimal priceInOrder = Math.Round(tool.LastPrice + tool.Step * 5, tool.PriceAccuracy);
                    AppendText2TextBox(textBoxLogsWindow, "Выставляем рыночную заявку на покупку..." + Environment.NewLine);
                    long transactionID = (await _quik.Orders.SendMarketOrder(tool.ClassCode, tool.SecurityCode, tool.AccountID, Operation.Buy, 1).ConfigureAwait(false)).TransID;
                    if (transactionID > 0)
                    {
                        AppendText2TextBox(textBoxLogsWindow, "Заявка выставлена. ID транзакции - " + transactionID + Environment.NewLine);
                        Thread.Sleep(500);
                        try
                        {
                            listOrders = _quik.Orders.GetOrders().Result;
                            foreach (Order _order in listOrders)
                            {
                                if (_order.TransID == transactionID && _order.ClassCode == tool.ClassCode && _order.SecCode == tool.SecurityCode)
                                {
                                    textBoxLogsWindow.AppendText("Заявка выставлена. Номер заявки - " + _order.OrderNum + Environment.NewLine);
                                    Text2TextBox(textBoxOrderNumber, _order.OrderNum.ToString());
                                    order = _order;
                                }
                                else
                                {
                                    Text2TextBox(textBoxOrderNumber, "---");
                                }
                            }
                        }
                        catch { AppendText2TextBox(textBoxLogsWindow, "Ошибка получения номера заявки." + Environment.NewLine); }
                    }
                    else
                    {
                        AppendText2TextBox(textBoxLogsWindow, "Неудачная попытка выставления заявки." + Environment.NewLine);
                    }
                }
                catch { AppendText2TextBox(textBoxLogsWindow, "Ошибка выставления заявки." + Environment.NewLine); }
                break;

            case "Удалить активную заявку":
                try
                {
                    if (order != null && order.OrderNum > 0)
                    {
                        AppendText2TextBox(textBoxLogsWindow, "Удаляем заявку на покупку с номером - " + order.OrderNum + " ..." + Environment.NewLine);
                    }
                    long x = _quik.Orders.KillOrder(order).Result;
                    AppendText2TextBox(textBoxLogsWindow, "Результат - " + x + " ..." + Environment.NewLine);
                    Text2TextBox(textBoxOrderNumber, "");
                }
                catch { AppendText2TextBox(textBoxLogsWindow, "Ошибка удаления заявки." + Environment.NewLine); }
                break;

            case "Получить информацию по бумаге":
                try
                {
                    AppendText2TextBox(textBoxLogsWindow, "Получаем таблицу информации..." + Environment.NewLine);
                    listSecurityInfo = new List <SecurityInfo>();
                    listSecurityInfo.Add(_quik.Class.GetSecurityInfo(tool.ClassCode, tool.SecurityCode).Result);

                    if (listDepoLimits.Count > 0)
                    {
                        AppendText2TextBox(textBoxLogsWindow, "Выводим данные в таблицу..." + Environment.NewLine);
                        toolCandlesTable = new FormOutputTable(listSecurityInfo);
                        toolCandlesTable.Show();
                    }
                    else
                    {
                        AppendText2TextBox(textBoxLogsWindow, "Информация по бумаге '" + tool.Name + "' отсутствует." + Environment.NewLine);
                    }
                }
                catch { AppendText2TextBox(textBoxLogsWindow, "Ошибка получения лимитов." + Environment.NewLine); }
                break;

            case "Получить таблицу лимитов по бумаге":
                try
                {
                    AppendText2TextBox(textBoxLogsWindow, "Получаем таблицу лимитов..." + Environment.NewLine);
                    listDepoLimits = _quik.Trading.GetDepoLimits(tool.SecurityCode).Result;

                    if (listDepoLimits.Count > 0)
                    {
                        AppendText2TextBox(textBoxLogsWindow, "Выводим данные лимитов в таблицу..." + Environment.NewLine);
                        toolCandlesTable = new FormOutputTable(listDepoLimits);
                        toolCandlesTable.Show();
                    }
                    else
                    {
                        AppendText2TextBox(textBoxLogsWindow, "Бумага '" + tool.Name + "' в таблице лимитов отсутствует." + Environment.NewLine);
                    }
                }
                catch { AppendText2TextBox(textBoxLogsWindow, "Ошибка получения лимитов." + Environment.NewLine); }
                break;

            case "Получить таблицу лимитов по всем бумагам":
                try
                {
                    AppendText2TextBox(textBoxLogsWindow, "Получаем таблицу лимитов..." + Environment.NewLine);
                    listDepoLimits = _quik.Trading.GetDepoLimits().Result;

                    if (listDepoLimits.Count > 0)
                    {
                        AppendText2TextBox(textBoxLogsWindow, "Выводим данные лимитов в таблицу..." + Environment.NewLine);
                        toolCandlesTable = new FormOutputTable(listDepoLimits);
                        toolCandlesTable.Show();
                    }
                }
                catch { AppendText2TextBox(textBoxLogsWindow, "Ошибка получения лимитов." + Environment.NewLine); }
                break;

            case "Получить таблицу по фьючерсным лимитам":
                try
                {
                    AppendText2TextBox(textBoxLogsWindow, "Получаем таблицу фьючерсных лимитов..." + Environment.NewLine);
                    futLimit = _quik.Trading.GetFuturesLimit(tool.FirmID, tool.AccountID, 0, "SUR").Result;

                    if (futLimit != null)
                    {
                        listFuturesLimits = new List <FuturesLimits>();
                        listFuturesLimits.Add(futLimit);
                        AppendText2TextBox(textBoxLogsWindow, "Выводим данные лимитов в таблицу..." + Environment.NewLine);
                        toolCandlesTable = new FormOutputTable(listFuturesLimits);
                        toolCandlesTable.Show();
                    }
                    else
                    {
                        Console.WriteLine("futuresLimit = null");
                    }
                }
                catch { AppendText2TextBox(textBoxLogsWindow, "Ошибка получения лимитов." + Environment.NewLine); }
                break;

            case "Получить таблицу заявок":
                try
                {
                    AppendText2TextBox(textBoxLogsWindow, "Получаем таблицу заявок..." + Environment.NewLine);
                    listOrders = _quik.Orders.GetOrders().Result;

                    if (listOrders.Count > 0)
                    {
                        AppendText2TextBox(textBoxLogsWindow, "Выводим данные о заявках в таблицу..." + Environment.NewLine);
                        toolCandlesTable = new FormOutputTable(listOrders);
                        toolCandlesTable.Show();
                    }
                }
                catch { AppendText2TextBox(textBoxLogsWindow, "Ошибка получения заявок." + Environment.NewLine); }
                break;

            case "Получить таблицу сделок":
                try
                {
                    AppendText2TextBox(textBoxLogsWindow, "Получаем таблицу сделок..." + Environment.NewLine);
                    listTrades = _quik.Trading.GetTrades().Result;

                    if (listTrades.Count > 0)
                    {
                        AppendText2TextBox(textBoxLogsWindow, "Выводим данные о сделках в таблицу..." + Environment.NewLine);
                        toolCandlesTable = new FormOutputTable(listTrades);
                        toolCandlesTable.Show();
                    }
                }
                catch { AppendText2TextBox(textBoxLogsWindow, "Ошибка получения сделок." + Environment.NewLine); }
                break;

            case "Получить таблицу `Клиентский портфель`":
                try
                {
                    AppendText2TextBox(textBoxLogsWindow, "Получаем таблицу `Клиентский портфель`..." + Environment.NewLine);
                    listPortfolio = new List <PortfolioInfoEx>();
                    if (classCode == "SPBFUT")
                    {
                        listPortfolio.Add(_quik.Trading.GetPortfolioInfoEx(tool.FirmID, tool.AccountID, 0).Result);
                    }
                    else
                    {
                        listPortfolio.Add(_quik.Trading.GetPortfolioInfoEx(tool.FirmID, clientCode, 2).Result);
                    }

                    if (listPortfolio.Count > 0)
                    {
                        AppendText2TextBox(textBoxLogsWindow, "Выводим данные о портфеле в таблицу..." + Environment.NewLine);
                        toolCandlesTable = new FormOutputTable(listPortfolio);
                        toolCandlesTable.Show();
                    }
                    else
                    {
                        AppendText2TextBox(textBoxLogsWindow, "В таблице `Клиентский портфель` отсутствуют записи." + Environment.NewLine);
                    }
                }
                catch { AppendText2TextBox(textBoxLogsWindow, "Ошибка получения клиентского портфеля." + Environment.NewLine); }
                break;

            case "Получить таблицы денежных лимитов":
                try
                {
                    AppendText2TextBox(textBoxLogsWindow, "Получаем таблицу денежных лимитов..." + Environment.NewLine);
                    listMoneyLimits = new List <MoneyLimit>();
                    listMoneyLimits.Add(_quik.Trading.GetMoney(clientCode, tool.FirmID, "EQTV", "SUR").Result);

                    if (listMoneyLimits.Count > 0)
                    {
                        AppendText2TextBox(textBoxLogsWindow, "Выводим данные о денежных лимитах в таблицу..." + Environment.NewLine);
                        toolCandlesTable = new FormOutputTable(listMoneyLimits);
                        toolCandlesTable.Show();
                    }

                    AppendText2TextBox(textBoxLogsWindow, "Получаем расширение таблицы денежных лимитов..." + Environment.NewLine);
                    listMoneyLimitsEx = new List <MoneyLimitEx>();
                    listMoneyLimitsEx.Add(_quik.Trading.GetMoneyEx(tool.FirmID, clientCode, "EQTV", "SUR", 2).Result);

                    if (listMoneyLimitsEx.Count > 0)
                    {
                        AppendText2TextBox(textBoxLogsWindow, "Выводим данные о денежных лимитах в таблицу..." + Environment.NewLine);
                        toolCandlesTable = new FormOutputTable(listMoneyLimitsEx);
                        toolCandlesTable.Show();
                    }
                }
                catch { AppendText2TextBox(textBoxLogsWindow, "Ошибка получения денежных лимитов." + Environment.NewLine); }
                break;

            case "Связка ParamRequest + OnParam + GetParamEx2":
                try
                {
                    AppendText2TextBox(textBoxLogsWindow, "Подписываемся на получение обновляемого параметра 'BID', через ParamRequest..." + Environment.NewLine);
                    bool pReq = _quik.Trading.ParamRequest(tool.ClassCode, tool.SecurityCode, ParamNames.BID).Result;
                    if (pReq)
                    {
                        AppendText2TextBox(textBoxLogsWindow, "Подписываемся на колбэк 'OnParam'..." + Environment.NewLine);
                        _quik.Events.OnParam += OnParamDo;
                    }
                    else
                    {
                        AppendText2TextBox(textBoxLogsWindow, "Неудачная попытка подписки на обновление параметра..." + Environment.NewLine);
                    }
                }
                catch { AppendText2TextBox(textBoxLogsWindow, "Ошибка работы в связке ParamRequest + OnParam + GetParamEx2." + Environment.NewLine); }
                break;

            case "CancelParamRequest":
                try
                {
                    AppendText2TextBox(textBoxLogsWindow, "Отменяем подписку на получение обновляемого параметра 'BID', через ParamRequest..." + Environment.NewLine);
                    bool pReq = _quik.Trading.CancelParamRequest(tool.ClassCode, tool.SecurityCode, ParamNames.BID).Result;
                    if (pReq)
                    {
                        AppendText2TextBox(textBoxLogsWindow, "Отменяем подписку на колбэк 'OnParam'..." + Environment.NewLine);
                        _quik.Events.OnParam -= OnParamDo;
                    }
                    else
                    {
                        AppendText2TextBox(textBoxLogsWindow, "Неудачная попытка отписки на обновление параметра..." + Environment.NewLine);
                    }
                }
                catch { AppendText2TextBox(textBoxLogsWindow, "Ошибка работы в связке ParamRequest + OnParam + GetParamEx2." + Environment.NewLine); }
                break;

            case "Отменить заказ на получение стакана":
                try
                {
                    AppendText2TextBox(textBoxLogsWindow, "Отменяем заказ на получение с сервера стакана по указанному классу и инструменту..." + Environment.NewLine);
                    bool resultUnsub = await _quik.OrderBook.Unsubscribe(tool.ClassCode, tool.SecurityCode).ConfigureAwait(false);

                    int count = 0;
                    while (!resultUnsub && count < 10)
                    {
                        Thread.Sleep(500);
                        resultUnsub = await _quik.OrderBook.Unsubscribe(tool.ClassCode, tool.SecurityCode).ConfigureAwait(false);

                        count++;
                    }
                    int i = 0;
                    while (isSubscribedToolOrderBook && i < 10)
                    {
                        Thread.Sleep(500);
                        isSubscribedToolOrderBook = _quik.OrderBook.IsSubscribed(tool.ClassCode, tool.SecurityCode).Result;
                        i++;
                    }
                    if (isSubscribedToolOrderBook)
                    {
                        //toolOrderBook                   = new OrderBook();
                        AppendText2TextBox(textBoxLogsWindow, "Отмена подписки на стакан не удалась." + Environment.NewLine);
                    }
                    else
                    {
                        toolOrderBook = null;
                        AppendText2TextBox(textBoxLogsWindow, "Отмена подписки на стакан прошла успешно." + Environment.NewLine);
                        bid   = 0;
                        offer = 0;
                        Text2TextBox(textBoxBestBid, "-");
                        Text2TextBox(textBoxBestOffer, "-");
                    }
                }
                catch { AppendText2TextBox(textBoxLogsWindow, "Ошибка в функции отмены заказа стакана." + Environment.NewLine); }
                break;

            case "Выставить стоп-заявку типа тейк-профит и стоп-лимит":
                try
                {
                    decimal   priceInOrder = Math.Round(tool.LastPrice, tool.PriceAccuracy);
                    StopOrder orderNew     = new StopOrder()
                    {
                        Account         = tool.AccountID,
                        ClassCode       = tool.ClassCode,
                        ClientCode      = clientCode,
                        SecCode         = secCode,
                        Offset          = 50,
                        OffsetUnit      = OffsetUnits.PRICE_UNITS,
                        Spread          = 0.5M,
                        SpreadUnit      = OffsetUnits.PERCENTS,
                        StopOrderType   = StopOrderType.TakeProfitStopLimit,
                        Condition       = Condition.LessOrEqual,
                        ConditionPrice  = Math.Round(priceInOrder - 50 * tool.Step, tool.PriceAccuracy),
                        ConditionPrice2 = Math.Round(priceInOrder + 40 * tool.Step, tool.PriceAccuracy),
                        Price           = Math.Round(priceInOrder + 45 * tool.Step, tool.PriceAccuracy),
                        Operation       = Operation.Buy,
                        Quantity        = 1
                    };
                    AppendText2TextBox(textBoxLogsWindow, "Выставляем стоп-заявку на покупку, по цене:" + priceInOrder + " ..." + Environment.NewLine);
                    long transID = await _quik.StopOrders.CreateStopOrder(orderNew).ConfigureAwait(false);

                    if (transID > 0)
                    {
                        AppendText2TextBox(textBoxLogsWindow, "Заявка выставлена. ID транзакции - " + transID + Environment.NewLine);
                        Thread.Sleep(500);
                        try
                        {
                            var listStopOrders = _quik.StopOrders.GetStopOrders().Result;
                            foreach (StopOrder stopOrder in listStopOrders)
                            {
                                if (stopOrder.TransId == transID && stopOrder.ClassCode == tool.ClassCode && stopOrder.SecCode == tool.SecurityCode)
                                {
                                    AppendText2TextBox(textBoxLogsWindow, "Стоп-заявка выставлена. Номер стоп-заявки - " + stopOrder.OrderNum + Environment.NewLine);
                                }
                            }
                        }
                        catch { AppendText2TextBox(textBoxLogsWindow, "Ошибка получения номера стоп-заявки." + Environment.NewLine); }
                    }
                    else
                    {
                        AppendText2TextBox(textBoxLogsWindow, "Неудачная попытка выставления стоп-заявки." + Environment.NewLine);
                    }
                }
                catch { AppendText2TextBox(textBoxLogsWindow, "Ошибка выставления стоп-заявки." + Environment.NewLine); }
                break;
            }
        }
Esempio n. 26
0
        public void IdentityStops()
        {
            string  sym     = "SPY";
            bool    side    = false;
            int     size    = -256;
            decimal stop    = 134.40m;
            string  comment = "Hello, World!";  // not checked for
            long    id      = 8675309;          // not checked for

            Order orig = new StopOrder(sym, side, size, stop);
            Order comp;

            comp = new StopOrder(sym, size, stop, id);
            Assert.AreEqual(orig.symbol, comp.symbol, "Symbol, SignedStop");
            Assert.AreEqual(orig.side, comp.side, "Side, SignedStop");
            Assert.AreEqual(orig.size, comp.size, "Size, SignedStop");
            Assert.AreEqual(orig.stopp, comp.stopp, "Stop, SignedStop");
            Assert.AreEqual(orig.price, comp.price, "Price, SignedStop");

            comp = new StopOrder(sym, side, size, stop, id);
            Assert.AreEqual(orig.symbol, comp.symbol, "Symbol, StopID");
            Assert.AreEqual(orig.side, comp.side, "Side, StopID");
            Assert.AreEqual(orig.size, comp.size, "Size, StopID");
            Assert.AreEqual(orig.stopp, comp.stopp, "Stop, StopID");
            Assert.AreEqual(orig.price, comp.price, "Price, StopID");

            comp = new StopOrder(sym, side, size, stop, comment);
            Assert.AreEqual(orig.symbol, comp.symbol, "Symbol, StopComment");
            Assert.AreEqual(orig.side, comp.side, "Side, StopComment");
            Assert.AreEqual(orig.size, comp.size, "Size, StopComment");
            Assert.AreEqual(orig.stopp, comp.stopp, "Stop, StopComment");
            Assert.AreEqual(orig.price, comp.price, "Price, StopComment");

            comp = new SellStop(sym, size, stop);
            Assert.AreEqual(orig.symbol, comp.symbol, "Symbol, SellStop");
            Assert.AreEqual(orig.side, comp.side, "Side, SellStop");
            Assert.AreEqual(orig.size, comp.size, "Size, SellStop");
            Assert.AreEqual(orig.stopp, comp.stopp, "Stop, SellStop");
            Assert.AreEqual(orig.price, comp.price, "Price, SellStop");

            comp = new SellStop(sym, size, stop, id);
            Assert.AreEqual(orig.symbol, comp.symbol, "Symbol, SellStopID");
            Assert.AreEqual(orig.side, comp.side, "Side, SellStopID");
            Assert.AreEqual(orig.size, comp.size, "Size, SellStopID");
            Assert.AreEqual(orig.stopp, comp.stopp, "Stop, SellStopID");
            Assert.AreEqual(orig.price, comp.price, "Price, SellStopID");

            comp = new SellStop(sym, size, stop, comment);
            Assert.AreEqual(orig.symbol, comp.symbol, "Symbol, SellStopComment");
            Assert.AreEqual(orig.side, comp.side, "Side, SellStopComment");
            Assert.AreEqual(orig.size, comp.size, "Size, SellStopComment");
            Assert.AreEqual(orig.stopp, comp.stopp, "Stop, SellStopComment");
            Assert.AreEqual(orig.price, comp.price, "Price, SellStopComment");

            side = true;
            orig = new StopOrder(sym, side, size, stop);

            comp = new BuyStop(sym, size, stop);
            Assert.AreEqual(orig.symbol, comp.symbol, "Symbol, BuyStop");
            Assert.AreEqual(orig.side, comp.side, "Side, BuyStop");
            Assert.AreEqual(orig.size, comp.size, "Size, BuyStop");
            Assert.AreEqual(orig.stopp, comp.stopp, "Stop, BuyStop");
            Assert.AreEqual(orig.price, comp.price, "Price, BuyStop");

            comp = new BuyStop(sym, size, stop, id);
            Assert.AreEqual(orig.symbol, comp.symbol, "Symbol, BuyStopID");
            Assert.AreEqual(orig.side, comp.side, "Side, BuyStopID");
            Assert.AreEqual(orig.size, comp.size, "Size, BuyStopID");
            Assert.AreEqual(orig.stopp, comp.stopp, "Stop, BuyStopID");
            Assert.AreEqual(orig.price, comp.price, "Price, BuyStopID");

            comp = new BuyStop(sym, size, stop, comment);
            Assert.AreEqual(orig.symbol, comp.symbol, "Symbol, BuyStopComment");
            Assert.AreEqual(orig.side, comp.side, "Side, BuyStopComment");
            Assert.AreEqual(orig.size, comp.size, "Size, BuyStopComment");
            Assert.AreEqual(orig.stopp, comp.stopp, "Stop, BuyStopComment");
            Assert.AreEqual(orig.price, comp.price, "Price, BuyStopComment");
        }