public Task <OrderModel> ActiveOrderOrDefault(string stock)
        {
            ibClient.ClientSocket.reqOpenOrders();
            Order openOrder = null;

            ibClient.IbOpenOrder += order =>
            {
                if (order.Contract.Symbol.EqualsIgnoreCase(stock))
                {
                    openOrder = order.Order;
                }
            };
            var success = false;

            ibClient.IbOpenOrderEnd += () => { success = true; };

            var waitTime = DateTime.Now.AddMinutes(1);

            while (!success && DateTime.Now < waitTime)
            {
            }

            return(Task.FromResult(new OrderModel
            {
                BuyingPrice = Convert.ToDecimal(openOrder.LmtPrice),
                ExternalId = openOrder.OrderId.ToString(),
                Quantity = Convert.ToInt16(openOrder.TotalQuantity - openOrder.FilledQuantity),
                UserOrderActionType = openOrder.Action == "BUY"
                    ? UserOrderActionType.Buy
                    : UserOrderActionType.Sell
            }));
        }
Ejemplo n.º 2
0
        /// <summary>
        ///     Выставить заявку
        /// </summary>
        /// <param name="transaction">
        ///     Транзакция
        /// </param>
        /// <param name="order">
        ///     IB-заявка
        /// </param>
        public async Task PlaceOrderAsync(NewOrderTransaction transaction, IBOrder order)
        {
            var instrument = transaction.Instrument;

            var contract = await connector.ContractContainer.GetContractAsync(instrument, null);

            if (contract == null)
            {
                throw new TransactionRejectedException($"Details of contract {instrument.Code} are not available");
            }

            using (orderInfoContainerLock.Lock())
            {
                var tickerId = NextTickerId();
                order.OrderId = tickerId;

                // Сохраняем заявку по ее тикеру
                var orderInfo = new OrderInfo(order, transaction.Instrument)
                {
                    State = OrderState.New,
                    NewOrderTransactionId = transaction.TransactionId
                };
                orderInfoContainer.StoreByTickerId(tickerId, orderInfo, true);

                Socket.placeOrder(tickerId, contract, order);
            }
        }
Ejemplo n.º 3
0
 public OpenOrderMessage(int orderId, IBApi.Contract contract, IBApi.Order order, OrderState orderState)
 {
     OrderId    = orderId;
     Contract   = contract;
     Order      = order;
     OrderState = orderState;
 }
Ejemplo n.º 4
0
 /// <summary>
 /// Initializes a new instance of the <see cref="OpenOrderEventArgs"/> class
 /// </summary>
 public OpenOrderEventArgs(int orderId, Contract contract, Order order, OrderState orderState)
 {
     OrderId = orderId;
     Contract = contract;
     Order = order;
     OrderState = orderState;
 }
Ejemplo n.º 5
0
 public static Order MarketOrder()
 {
     Order order = new Order();
     order.Action = "BUY";
     order.OrderType = "MKT";
     order.TotalQuantity = 1;
     return order;
 }
Ejemplo n.º 6
0
 public OpenOrderMessage(int orderId, Contract contract, Order order, OrderState orderState)
 {
     Type = MessageType.OpenOrder;
     OrderId = orderId;
     Contract = contract;
     Order = order;
     OrderState = orderState;
 }
Ejemplo n.º 7
0
 public static Order LimitOrder()
 {
     Order order = new Order();
     order.Action = "BUY";
     order.OrderType = "LMT";
     order.TotalQuantity = 100;
     order.Account = "DU74649";
     order.LmtPrice = 0.8;
     return order;
 }
Ejemplo n.º 8
0
        public IBApi.Order MarketOrder(int orderId, int quantity, string action)
        {
            IBApi.Order mktOrder = new IBApi.Order();
            mktOrder.OrderId = orderId;
            mktOrder.TotalQuantity = quantity;
            mktOrder.OrderType = "MKT";
            mktOrder.Action = action;

            return mktOrder;
        }
Ejemplo n.º 9
0
 public void PlaceOrder(Contract contract, Order order)
 {
     if (order.OrderId != 0)
     {
         ibClient.ClientSocket.placeOrder(order.OrderId, contract, order);
     }
     else
     {
         ibClient.ClientSocket.placeOrder(ibClient.NextOrderId, contract, order);
         ibClient.NextOrderId++;
     }
 }
Ejemplo n.º 10
0
        public IBApi.Order LimitOrder(int orderId, int quantity, string action, double price)
        {
            IBApi.Order limitOrder = new IBApi.Order();
            limitOrder.OrderId = orderId;
            limitOrder.TotalQuantity = quantity;
            limitOrder.OrderType = "LMT";
            limitOrder.Action = action;
            limitOrder.LmtPrice = price;

            return limitOrder;

        }
Ejemplo n.º 11
0
        public IBApi.Order StopOrder(int orderId, int quantity, string action, double price)
        {
            IBApi.Order stopOrder = new IBApi.Order();
            stopOrder.OrderId = orderId;
            stopOrder.TotalQuantity = quantity;
            stopOrder.OrderType = "STP";
            stopOrder.Action = action;
            stopOrder.AuxPrice = price;
            //SHould this be a stop price?

            return stopOrder;

        }
        private static Order GetOrder(int quantity, decimal price, int id, bool buy)
        {
            var orderInfo = new Order
            {
                OrderId       = id,
                OrderType     = "LMT",
                Action        = buy ? "BUY" : "SELL",
                TotalQuantity = quantity,
                LmtPrice      = Convert.ToDouble(price),
                Tif           = "DAY"
            };

            return(orderInfo);
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Place order.
        /// Order must have contract field.
        /// </summary>
        public void PlaceOrder(Order o)
        {
            if ((!o.IsValid) || (string.IsNullOrEmpty(o.FullSymbol)))
            {
                OnDebug("Order is not valid.");
                return;
            }

            IBApi.Order order = new IBApi.Order();

            order.AuxPrice = o.IsTrail ? (double)o.TrailPrice : (double)o.StopPrice;
            order.LmtPrice = (double)o.LimitPrice;

            // Only MKT, LMT, STP, and STP LMT, TRAIL, TRAIL LIMIT are supported
            order.OrderType = o.OrderType;

            order.TotalQuantity = o.UnsignedSize;
            order.Action        = o.OrderSide ? "BUY" : "SELL";  // SSHORT not supported here

            // order.Account = Account;
            order.Tif        = o.TIF.ToString();
            order.OutsideRth = true;
            //order.OrderId = (int)o.id;
            order.Transmit = true;
            if (string.IsNullOrEmpty(o.Account))
            {
                order.Account = Account;
            }
            else
            {
                order.Account = o.Account;
            }

            // Set up IB order Id
            if (o.Id == 0)
            {
                throw new ArgumentOutOfRangeException("Order id is missing.");
            }
            else // TODO: elimitate situation where strategy Order Id already exists
            {
                //order.OrderId = System.Threading.Interlocked.Increment(ref _nextValidIBID); // it returns the incremented id
                order.OrderId = (int)o.Id;
                _iborderIdToOrderInfo.Add(order.OrderId, new OrderInfo(o.Id, order.Account, false));
            }


            IBApi.Contract contract = SecurityFullNameToContract(o.FullSymbol);

            _ibSocket.placeOrder(order.OrderId, contract, order);
        }
Ejemplo n.º 14
0
        public static Order LimitOrderForComboWithLegPrice()
        {
            Order order = new Order();
            order.Action = "BUY";
            order.OrderType = "LMT";
            order.TotalQuantity = 1;

            OrderComboLeg ocl1 = new OrderComboLeg();
            ocl1.Price = 5.0;

            OrderComboLeg ocl2 = new OrderComboLeg();
            ocl2.Price = 5.90;
            order.OrderComboLegs = new List<OrderComboLeg>();
            order.OrderComboLegs.Add(ocl1);
            order.OrderComboLegs.Add(ocl2);

            order.SmartComboRoutingParams = new List<TagValue>();
            order.SmartComboRoutingParams.Add(new TagValue("NonGuaranteed", "1"));

            return order;
        }
Ejemplo n.º 15
0
        public void openOrder(int orderId, Contract contract, IBApi.Order order, OrderState orderState)
        {
            _____________________________________________________________________________Logger.WriteMethod(nameof(openOrder), nameof(orderId), orderId, nameof(contract), contract, nameof(order), order, nameof(orderState), orderState);

            if (PlacedOrders.ContainsKey(orderId))
            {
                Models.Order modelOrder = PlacedOrders[orderId];

                OrderStatus orderStatus = Utils.GetEnumArray <OrderStatus>().Single(x => x.Text() == orderState.Status);
                if (orderStatus.IsLastStatus() && orderState.Commission != decimal.MaxValue)
                {
                    modelOrder.Commission = orderState.Commission;
                    modelOrder.CommissionLock.Set();
                }

                modelOrder.Status = orderStatus;
                if (modelOrder.Status.IsLastStatus())
                {
                    modelOrder.FinishLock.Set();
                }
            }

            Locks[nameof(openOrder) + orderId].Set();
        }
Ejemplo n.º 16
0
 public void SetOrder(Order order)
 {
     orderId = order.OrderId;
     action.Text = order.Action;
     orderType.Text = order.OrderType;
     lmtPrice.Text = order.LmtPrice.ToString();
     quantity.Text = order.TotalQuantity.ToString();
     account.Text = order.Account;
     timeInForce.Text = order.Tif;
     auxPrice.Text = order.AuxPrice.ToString();
     displaySize.Text = order.DisplaySize.ToString();
     //order = GetExtendedOrderAttributes(order);
     //order = GetAdvisorAttributes(order);
     //order = GetVolatilityAttributes(order);
     //order = GetScaleAttributes(order);
     //order = GetAlgoAttributes(order);
 }
Ejemplo n.º 17
0
        private Order GetAlgoAttributes(Order order)
        {
            if (algoStrategy.Text.Equals("") || algoStrategy.Text.Equals("None"))
                return order;
            List<TagValue> algoParams = new List<TagValue>();
            algoParams.Add(new TagValue("startTime", startTime.Text));
            algoParams.Add(new TagValue("endTime", endTime.Text));

            order.AlgoStrategy = algoStrategy.Text;

            /*Vwap Twap ArrivalPx DarkIce PctVol*/
            if (order.AlgoStrategy.Equals("VWap"))
            {
                algoParams.Add(new TagValue("maxPctVol", maxPctVol.Text));
                algoParams.Add(new TagValue("noTakeLiq", noTakeLiq.Text));
                algoParams.Add(new TagValue("getDone", getDone.Text));
                algoParams.Add(new TagValue("noTradeAhead", noTradeAhead.Text));
                algoParams.Add(new TagValue("useOddLots", useOddLots.Text));
                algoParams.Add(new TagValue("allowPastEndTime", allowPastEndTime.Text));
            }

            if (order.AlgoStrategy.Equals("Twap"))
            {
                algoParams.Add(new TagValue("strategyType", strategyType.Text));
                algoParams.Add(new TagValue("allowPastEndTime", allowPastEndTime.Text));
            }

            if (order.AlgoStrategy.Equals("ArrivalPx"))
            {
                algoParams.Add(new TagValue("allowPastEndTime", allowPastEndTime.Text));
                algoParams.Add(new TagValue("maxPctVol", maxPctVol.Text));
                algoParams.Add(new TagValue("riskAversion", riskAversion.Text));
                algoParams.Add(new TagValue("forceCompletion", forceCompletion.Text));
            }

            if (order.AlgoStrategy.Equals("DarkIce"))
            {
                algoParams.Add(new TagValue("allowPastEndTime", allowPastEndTime.Text));
                algoParams.Add(new TagValue("displaySize", displaySizeAlgo.Text));
            }

            if (order.AlgoStrategy.Equals("PctVol"))
            {
                algoParams.Add(new TagValue("pctVol", pctVol.Text));
                algoParams.Add(new TagValue("noTakeLiq", noTakeLiq.Text));
            }
            order.AlgoParams = algoParams;
            return order;
        }
Ejemplo n.º 18
0
        private Order GetScaleAttributes(Order order)
        {
            if(!initialLevelSize.Text.Equals(""))
                order.ScaleInitLevelSize = Int32.Parse(initialLevelSize.Text);
            if (!subsequentLevelSize.Text.Equals(""))
                order.ScaleSubsLevelSize = Int32.Parse(subsequentLevelSize.Text);
            if(!priceIncrement.Text.Equals(""))
                order.ScalePriceIncrement = Double.Parse(priceIncrement.Text);
            if (!priceAdjustValue.Text.Equals(""))
                order.ScalePriceAdjustValue = Double.Parse(priceAdjustValue.Text);
            if (!priceAdjustInterval.Text.Equals(""))
                order.ScalePriceAdjustInterval = Int32.Parse(priceAdjustInterval.Text);
            if (!profitOffset.Text.Equals(""))
                order.ScaleProfitOffset = Double.Parse(profitOffset.Text);
            if (!initialPosition.Text.Equals(""))
                order.ScaleInitPosition = Int32.Parse(initialPosition.Text);
            if (!initialFillQuantity.Text.Equals(""))
                order.ScaleInitFillQty = Int32.Parse(initialFillQuantity.Text);

            order.ScaleAutoReset = autoReset.Checked;
            order.ScaleRandomPercent = randomiseSize.Checked;
            
            return order;
        }
Ejemplo n.º 19
0
 private Order GetAdvisorAttributes(Order order)
 {
     order.FaGroup = faGroup.Text;
     order.FaPercentage = faPercentage.Text;
     order.FaMethod = (string)((IBType)faMethod.SelectedItem).Value;
     order.FaProfile = faProfile.Text;
     return order;
 }
Ejemplo n.º 20
0
 public static void FillAdaptiveParams(IBApi.Order baseOrder, string priority) {
   baseOrder.AlgoStrategy = "Adaptive";
   baseOrder.AlgoParams = new List<TagValue>();
   baseOrder.AlgoParams.Add(new TagValue("adaptivePriority", priority));
 }
Ejemplo n.º 21
0
        private void MakeOrder(OrderType orderType, OrderAction orderAction)
        {
            Contract contract = new Contract();

            IBApi.Order order = new IBApi.Order();

            switch (orderType)
            {
            case OrderType.MTL:

                // AUC
                contract.Symbol   = "IBKR";
                contract.SecType  = "STK";
                contract.Currency = "USD";
                contract.Exchange = "SMART";

                OrderAuction orderAuction = new OrderAuction();
                orderAuction.Action     = orderAction;
                orderAuction.LimitPrice = 10;
                orderAuction.Quantity   = 1;

                order = orderAuction.GetOrder;

                break;

            case OrderType.MKT:


                contract.Symbol   = "IBKR";
                contract.SecType  = "STK";
                contract.Currency = "USD";
                contract.Exchange = "SMART";

                OrderMarket orderMarket = new OrderMarket();
                orderMarket.Action      = orderAction;
                orderMarket.Quantity    = 1;
                orderMarket.TimeInForce = OrderTimeInForce.GTC;

                order = orderMarket.GetOrder;

                break;

            case OrderType.LMT:

                contract.Symbol   = "IBKR";
                contract.SecType  = "STK";
                contract.Currency = "USD";
                contract.Exchange = "SMART";

                OrderLimit orderLimit = new OrderLimit();

                orderLimit.Action      = orderAction;
                orderLimit.LimitPrice  = 10;
                orderLimit.Quantity    = 1;
                orderLimit.TimeInForce = OrderTimeInForce.GTC;

                order = orderLimit.GetOrder;

                break;
            }

            manager.SubmitOrder(contract, order);
        }
Ejemplo n.º 22
0
 public virtual void openOrder(int orderId, Contract contract, Order order, OrderState orderState)
 {
     parentUI.HandleMessage(new OpenOrderMessage(orderId, contract, order, orderState));
 }
Ejemplo n.º 23
0
        protected bool VerifyOrder(Order order, int id, bool isBagOrder)
        {
            if (serverVersion < MinServerVer.SCALE_ORDERS)
            {
                if (order.ScaleInitLevelSize != Int32.MaxValue ||
                    order.ScalePriceIncrement != Double.MaxValue)
                {
                    ReportError(id, EClientErrors.UPDATE_TWS,
                        "  It does not support Scale orders.");
                    return false;
                }
            }
            if (serverVersion < MinServerVer.WHAT_IF_ORDERS)
            {
                if (order.WhatIf)
                {
                    ReportError(id, EClientErrors.UPDATE_TWS,
                        "  It does not support what-if orders.");
                    return false;
                }
            }
            
            if (serverVersion < MinServerVer.SCALE_ORDERS2)
            {
                if (order.ScaleSubsLevelSize != Int32.MaxValue)
                {
                    ReportError(id, EClientErrors.UPDATE_TWS,
                        "  It does not support Subsequent Level Size for Scale orders.");
                    return false;
                }
            }

            if (serverVersion < MinServerVer.ALGO_ORDERS)
            {
                if (!IsEmpty(order.AlgoStrategy))
                {
                    ReportError(id, EClientErrors.UPDATE_TWS,
                        "  It does not support algo orders.");
                    return false;
                }
            }

            if (serverVersion < MinServerVer.NOT_HELD)
            {
                if (order.NotHeld)
                {
                    ReportError(id, EClientErrors.UPDATE_TWS,
                        "  It does not support notHeld parameter.");
                    return false;
                }
            }
            
            if (serverVersion < MinServerVer.SSHORTX)
            {
                if (order.ExemptCode != -1)
                {
                    ReportError(id, EClientErrors.UPDATE_TWS,
                        "  It does not support exemptCode parameter.");
                    return false;
                }
            }

            

            if (serverVersion < MinServerVer.HEDGE_ORDERS)
            {
                if (!IsEmpty(order.HedgeType))
                {
                    ReportError(id, EClientErrors.UPDATE_TWS,
                        "  It does not support hedge orders.");
                    return false;
                }
            }

            if (serverVersion < MinServerVer.OPT_OUT_SMART_ROUTING)
            {
                if (order.OptOutSmartRouting)
                {
                    ReportError(id, EClientErrors.UPDATE_TWS,
                        "  It does not support optOutSmartRouting parameter.");
                    return false;
                }
            }

            if (serverVersion < MinServerVer.DELTA_NEUTRAL_CONID)
            {
                if (order.DeltaNeutralConId > 0
                        || !IsEmpty(order.DeltaNeutralSettlingFirm)
                        || !IsEmpty(order.DeltaNeutralClearingAccount)
                        || !IsEmpty(order.DeltaNeutralClearingIntent))
                {
                    ReportError(id, EClientErrors.UPDATE_TWS,
                        "  It does not support deltaNeutral parameters: ConId, SettlingFirm, ClearingAccount, ClearingIntent");
                    return false;
                }
            }

            if (serverVersion < MinServerVer.DELTA_NEUTRAL_OPEN_CLOSE)
            {
                if (!IsEmpty(order.DeltaNeutralOpenClose)
                        || order.DeltaNeutralShortSale
                        || order.DeltaNeutralShortSaleSlot > 0
                        || !IsEmpty(order.DeltaNeutralDesignatedLocation)
                        )
                {
                    ReportError(id, EClientErrors.UPDATE_TWS,
                        "  It does not support deltaNeutral parameters: OpenClose, ShortSale, ShortSaleSlot, DesignatedLocation");
                    return false;
                }
            }

            if (serverVersion < MinServerVer.SCALE_ORDERS3)
            {
                if (order.ScalePriceIncrement > 0 && order.ScalePriceIncrement != Double.MaxValue)
                {
                    if (order.ScalePriceAdjustValue != Double.MaxValue ||
                        order.ScalePriceAdjustInterval != Int32.MaxValue ||
                        order.ScaleProfitOffset != Double.MaxValue ||
                        order.ScaleAutoReset ||
                        order.ScaleInitPosition != Int32.MaxValue ||
                        order.ScaleInitFillQty != Int32.MaxValue ||
                        order.ScaleRandomPercent)
                    {
                        ReportError(id, EClientErrors.UPDATE_TWS,
                            "  It does not support Scale order parameters: PriceAdjustValue, PriceAdjustInterval, " +
                            "ProfitOffset, AutoReset, InitPosition, InitFillQty and RandomPercent");
                        return false;
                    }
                }
            }

            if (serverVersion < MinServerVer.ORDER_COMBO_LEGS_PRICE && isBagOrder)
            {
                if (order.OrderComboLegs.Count > 0)
                {
                    OrderComboLeg orderComboLeg;
                    for (int i = 0; i < order.OrderComboLegs.Count; ++i)
                    {
                        orderComboLeg = (OrderComboLeg)order.OrderComboLegs[i];
                        if (orderComboLeg.price != Double.MaxValue)
                        {
                            ReportError(id, EClientErrors.UPDATE_TWS,
                                "  It does not support per-leg prices for order combo legs.");
                            return false;
                        }
                    }
                }
            }

            if (serverVersion < MinServerVer.TRAILING_PERCENT)
            {
                if (order.TrailingPercent != Double.MaxValue)
                {
                    ReportError(id, EClientErrors.UPDATE_TWS,
                        "  It does not support trailing percent parameter.");
                    return false;
                }
            }

            if (serverVersion < MinServerVer.SCALE_TABLE)
            {
                if (!IsEmpty(order.ScaleTable) || !IsEmpty(order.ActiveStartTime) || !IsEmpty(order.ActiveStopTime))
                {
                    ReportError(id, EClientErrors.UPDATE_TWS,
                        "  It does not support scaleTable, activeStartTime nor activeStopTime parameters.");
                    return false;
                }
            }

            return true;
        }
Ejemplo n.º 24
0
 public CompletedOrderMessage(IBApi.Contract contract, IBApi.Order order, OrderState orderState)
 {
     Contract   = contract;
     Order      = order;
     OrderState = orderState;
 }
Ejemplo n.º 25
0
 public virtual void openOrder(int orderId, Contract contract, Order order, OrderState orderState)
 {
     Console.WriteLine("OpenOrder. ID: " + orderId + ", " + contract.Symbol + ", " + contract.SecType + " @ " + contract.Exchange + ": " + order.Action + ", " + order.OrderType + " " + order.TotalQuantity + ", " + orderState.Status + "\n");
     //clientSocket.reqMktData(2, contract, "", false);
     contract.ConId = 0;
     _client.placeOrder(_nextOrderId, contract, order);
 }
        // This function is called to feed in open orders.
        // // It is also fired after reconnecting to TWS if the client has any open orders.
        public virtual void openOrder(int orderId, Contract contract, Order order, OrderState orderState)
        {
            String str;
            str = "Open order @ " + DateTime.Now.ToShortTimeString()
                + ": OrderId = " + orderId.ToString()
                + ", contract symbol = " + contract.Symbol
                + "order = " + order.OrderId.ToString()
                + "client = " + order.ClientId.ToString()
                + " order state = " + orderState.Status.ToString();

            AddTextToResponseListWindow(str);
        }
Ejemplo n.º 27
0
 public void completedOrder(Contract contract, IBApi.Order order, OrderState orderState)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 28
0
        public void processSignal(PairSignal oneSignal)
        {
            if (oneSignal.TrSignal == PairType.nullType)
                // do nothing
                return;

            // retrieve Pair information from pair dict, based on this signal
            PairPos tmpPair = this.PairPosDict[oneSignal.StkTID];
            tmpPair.ThisPairStatus = oneSignal.TrSignal;


            // TODO: remove this line later, this is just for test
            tmpPair.PairBeta = 1;

            if (tmpPair.PairBeta == 0)
            {
                // the beta of this pair is zero, this pair hasn't be completely set up. exit application
                Console.WriteLine("Please build the model first!, {0}, {1}", tmpPair.pairEtfLeg.Symbol, tmpPair.pairStkLeg.Symbol);
                Console.WriteLine("Press any key to start over...");
                Console.ReadKey();
                Environment.Exit(-2);
            }

            // create contract objects for both stk and etf
            Contract etfContract = new Contract();
            etfContract.Symbol = tmpPair.pairEtfLeg.Symbol;
            etfContract.SecType = "STK";        // Both etf and stk are using the same security type, required by IB
            etfContract.Currency = "USD";
            etfContract.Exchange = "SMART";
            Contract stkContract = new Contract();
            stkContract.Symbol = tmpPair.pairStkLeg.Symbol;
            stkContract.SecType = "STK";
            stkContract.Currency = "USD";
            stkContract.Exchange = "SMART";

            // create order objects for both stk and etf
            Order etfOrder = new Order();
            etfOrder.OrderId = this.NextOrderId;
            etfOrder.OrderType = "MKT";
            Order stkOrder = new Order();
            stkOrder.OrderId = this.NextOrderId + 1;
            stkOrder.OrderType = "MKT";

            // pass order ID to Pair Dictionary
            switch (oneSignal.TrSignal)
            {
                case PairType.openLong:
                    tmpPair.ThisPairStatus = PairType.openLong;
                    tmpPair.pairEtfLeg.OpenOrderID= this.nextOrderId;
                    tmpPair.pairStkLeg.OpenOrderID = this.nextOrderId + 1;
                    break;
                case PairType.openShort:
                    tmpPair.ThisPairStatus = PairType.openShort;
                    tmpPair.pairEtfLeg.OpenOrderID= this.nextOrderId;
                    tmpPair.pairStkLeg.OpenOrderID = this.nextOrderId + 1;
                    break;
                case PairType.closeLong:
                    tmpPair.ThisPairStatus = PairType.closeLong;
                    tmpPair.pairEtfLeg.CloseOrderID = this.nextOrderId;
                    tmpPair.pairStkLeg.CloseOrderID = this.nextOrderId + 1;
                    break;
                case PairType.closeShort:
                    tmpPair.ThisPairStatus = PairType.closeShort;
                    tmpPair.pairEtfLeg.CloseOrderID = this.nextOrderId;
                    tmpPair.pairStkLeg.CloseOrderID = this.nextOrderId + 1;
                    break;
                default:
                    Console.WriteLine("Wrong signal type. Press any key to start over...");
                    Console.ReadKey();
                    Environment.Exit(-2);
                    break;
            }

            this.PairPosDict[oneSignal.StkTID] = tmpPair;

            switch (oneSignal.TrSignal)
            {
                case PairType.openLong:
                    // long etf short stk
                    stkOrder.Action = "SELL";
                    stkOrder.TotalQuantity = this.STK_SHARE;
                    stkOrder.OrderType = "MKT";
                    etfOrder.Action = "BUY";
                    etfOrder.TotalQuantity = Convert.ToInt32(this.STK_SHARE * tmpPair.PairBeta);
                    etfOrder.OrderType = "MKT";
                    break;
                case PairType.openShort:
                    // short etf long stk
                    stkOrder.Action = "BUY";
                    stkOrder.TotalQuantity = this.STK_SHARE;
                    stkOrder.OrderType = "MKT";
                    etfOrder.Action = "SSHORT";
                    etfOrder.TotalQuantity = Convert.ToInt32(this.STK_SHARE * tmpPair.PairBeta);
                    etfOrder.OrderType = "MKT";
                    break;
                case PairType.closeLong:
                    // close, sell etf buy cover stk
                    stkOrder.Action = "BUY";
                    stkOrder.TotalQuantity = this.STK_SHARE;
                    stkOrder.OrderType = "MKT";
                    etfOrder.Action = "SELL";
                    etfOrder.TotalQuantity = Convert.ToInt32(this.STK_SHARE * tmpPair.PairBeta);
                    etfOrder.OrderType = "MKT";
                    break;
                case PairType.closeShort:
                    // close, buy cover etf sell stk
                    stkOrder.Action = "SELL";
                    stkOrder.TotalQuantity = this.STK_SHARE;
                    stkOrder.OrderType = "MKT";
                    etfOrder.Action = "BUY";
                    etfOrder.TotalQuantity = Convert.ToInt32(this.STK_SHARE * tmpPair.PairBeta);
                    etfOrder.OrderType = "MKT";
                    break;
                default:
                    // not gonna happen
                    Console.WriteLine("Wrong signal! Press any key to stop...");
                    Console.ReadKey();
                    Environment.Exit(-1);
                    break;
            }

            // TODO: add log file here
            this.ClientSocket.placeOrder(etfOrder.OrderId, etfContract, etfOrder);
            this.ClientSocket.placeOrder(stkOrder.OrderId, stkContract, stkOrder);
            this.ClientSocket.reqIds(1);
        }
Ejemplo n.º 29
0
 public void openOrder(int orderId, Contract contract, IBApi.Order order, OrderState orderState)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 30
0
 // "Feeds in currently open orders." We can subscribe to all the current OrdersInfo. For MOC orders for example, before PlaceOrder() we should check that if there is already an MOC order then we Modify that (or Cancel&Recreate)
 public virtual void openOrder(int orderId, Contract contract, Order order, OrderState orderState)
 {
     Utils.Logger.Info("OpenOrder. ID: " + orderId + ", " + contract.Symbol + ", " + contract.SecType + " @ " + contract.Exchange + ": " + order.Action + ", " + order.OrderType + " " + order.TotalQuantity + ", " + orderState.Status);
 }
Ejemplo n.º 31
0
        private void OpenOrderEvent()
        {
            int msgVersion = ReadInt();
            // read order id
            Order order = new Order();
            order.OrderId = ReadInt();

            // read contract fields
            Contract contract = new Contract();
            if (msgVersion >= 17)
            {
                contract.ConId = ReadInt();
            }
            contract.Symbol = ReadString();
            contract.SecType = ReadString();
            contract.Expiry = ReadString();
            contract.Strike = ReadDouble();
            contract.Right = ReadString();
            if (msgVersion >= 32)
            {
                contract.Multiplier = ReadString();
            }
            contract.Exchange = ReadString();
            contract.Currency = ReadString();
            if (msgVersion >= 2)
            {
                contract.LocalSymbol = ReadString();
            }
            if (msgVersion >= 32)
            {
                contract.TradingClass = ReadString();
            }

            // read order fields
            order.Action = ReadString();
            order.TotalQuantity = ReadInt();
            order.OrderType = ReadString();
            if (msgVersion < 29)
            {
                order.LmtPrice = ReadDouble();
            }
            else
            {
                order.LmtPrice = ReadDoubleMax();
            }
            if (msgVersion < 30)
            {
                order.AuxPrice = ReadDouble();
            }
            else
            {
                order.AuxPrice = ReadDoubleMax();
            }
            order.Tif = ReadString();
            order.OcaGroup = ReadString();
            order.Account = ReadString();
            order.OpenClose = ReadString();
            order.Origin = ReadInt();
            order.OrderRef = ReadString();

            if (msgVersion >= 3)
            {
                order.ClientId = ReadInt();
            }

            if (msgVersion >= 4)
            {
                order.PermId = ReadInt();
                if (msgVersion < 18)
                {
                    // will never happen
                    /* order.ignoreRth = */
                    ReadBoolFromInt();
                }
                else
                {
                    order.OutsideRth = ReadBoolFromInt();
                }
                order.Hidden = ReadInt() == 1;
                order.DiscretionaryAmt = ReadDouble();
            }

            if (msgVersion >= 5)
            {
                order.GoodAfterTime = ReadString();
            }

            if (msgVersion >= 6)
            {
                // skip deprecated sharesAllocation field
                ReadString();
            }

            if (msgVersion >= 7)
            {
                order.FaGroup = ReadString();
                order.FaMethod = ReadString();
                order.FaPercentage = ReadString();
                order.FaProfile = ReadString();
            }

            if (msgVersion >= 8)
            {
                order.GoodTillDate = ReadString();
            }

            if (msgVersion >= 9)
            {
                order.Rule80A = ReadString();
                order.PercentOffset = ReadDoubleMax();
                order.SettlingFirm = ReadString();
                order.ShortSaleSlot = ReadInt();
                order.DesignatedLocation = ReadString();
                if (parent.ServerVersion == 51)
                {
                    ReadInt(); // exemptCode
                }
                else if (msgVersion >= 23)
                {
                    order.ExemptCode = ReadInt();
                }
                order.AuctionStrategy = ReadInt();
                order.StartingPrice = ReadDoubleMax();
                order.StockRefPrice = ReadDoubleMax();
                order.Delta = ReadDoubleMax();
                order.StockRangeLower = ReadDoubleMax();
                order.StockRangeUpper = ReadDoubleMax();
                order.DisplaySize = ReadInt();
                if (msgVersion < 18)
                {
                    // will never happen
                    /* order.rthOnly = */
                    ReadBoolFromInt();
                }
                order.BlockOrder = ReadBoolFromInt();
                order.SweepToFill = ReadBoolFromInt();
                order.AllOrNone = ReadBoolFromInt();
                order.MinQty = ReadIntMax();
                order.OcaType = ReadInt();
                order.ETradeOnly = ReadBoolFromInt();
                order.FirmQuoteOnly = ReadBoolFromInt();
                order.NbboPriceCap = ReadDoubleMax();
            }

            if (msgVersion >= 10)
            {
                order.ParentId = ReadInt();
                order.TriggerMethod = ReadInt();
            }

            if (msgVersion >= 11)
            {
                order.Volatility = ReadDoubleMax();
                order.VolatilityType = ReadInt();
                if (msgVersion == 11)
                {
                    int receivedInt = ReadInt();
                    order.DeltaNeutralOrderType = ((receivedInt == 0) ? "NONE" : "MKT");
                }
                else
                { // msgVersion 12 and up
                    order.DeltaNeutralOrderType = ReadString();
                    order.DeltaNeutralAuxPrice = ReadDoubleMax();

                    if (msgVersion >= 27 && !Util.StringIsEmpty(order.DeltaNeutralOrderType))
                    {
                        order.DeltaNeutralConId = ReadInt();
                        order.DeltaNeutralSettlingFirm = ReadString();
                        order.DeltaNeutralClearingAccount = ReadString();
                        order.DeltaNeutralClearingIntent = ReadString();
                    }

                    if (msgVersion >= 31 && !Util.StringIsEmpty(order.DeltaNeutralOrderType))
                    {
                        order.DeltaNeutralOpenClose = ReadString();
                        order.DeltaNeutralShortSale = ReadBoolFromInt();
                        order.DeltaNeutralShortSaleSlot = ReadInt();
                        order.DeltaNeutralDesignatedLocation = ReadString();
                    }
                }
                order.ContinuousUpdate = ReadInt();
                if (parent.ServerVersion == 26)
                {
                    order.StockRangeLower = ReadDouble();
                    order.StockRangeUpper = ReadDouble();
                }
                order.ReferencePriceType = ReadInt();
            }

            if (msgVersion >= 13)
            {
                order.TrailStopPrice = ReadDoubleMax();
            }

            if (msgVersion >= 30)
            {
                order.TrailingPercent = ReadDoubleMax();
            }

            if (msgVersion >= 14)
            {
                order.BasisPoints = ReadDoubleMax();
                order.BasisPointsType = ReadIntMax();
                contract.ComboLegsDescription = ReadString();
            }

            if (msgVersion >= 29)
            {
                int comboLegsCount = ReadInt();
                if (comboLegsCount > 0)
                {
                    contract.ComboLegs = new List<ComboLeg>(comboLegsCount);
                    for (int i = 0; i < comboLegsCount; ++i)
                    {
                        int conId = ReadInt();
                        int ratio = ReadInt();
                        String action = ReadString();
                        String exchange = ReadString();
                        int openClose = ReadInt();
                        int shortSaleSlot = ReadInt();
                        String designatedLocation = ReadString();
                        int exemptCode = ReadInt();

                        ComboLeg comboLeg = new ComboLeg(conId, ratio, action, exchange, openClose,
                                shortSaleSlot, designatedLocation, exemptCode);
                        contract.ComboLegs.Add(comboLeg);
                    }
                }

                int orderComboLegsCount = ReadInt();
                if (orderComboLegsCount > 0)
                {
                    order.OrderComboLegs = new List<OrderComboLeg>(orderComboLegsCount);
                    for (int i = 0; i < orderComboLegsCount; ++i)
                    {
                        double price = ReadDoubleMax();

                        OrderComboLeg orderComboLeg = new OrderComboLeg(price);
                        order.OrderComboLegs.Add(orderComboLeg);
                    }
                }
            }

            if (msgVersion >= 26)
            {
                int smartComboRoutingParamsCount = ReadInt();
                if (smartComboRoutingParamsCount > 0)
                {
                    order.SmartComboRoutingParams = new List<TagValue>(smartComboRoutingParamsCount);
                    for (int i = 0; i < smartComboRoutingParamsCount; ++i)
                    {
                        TagValue tagValue = new TagValue();
                        tagValue.tag = ReadString();
                        tagValue.value = ReadString();
                        order.SmartComboRoutingParams.Add(tagValue);
                    }
                }
            }

            if (msgVersion >= 15)
            {
                if (msgVersion >= 20)
                {
                    order.ScaleInitLevelSize = ReadIntMax();
                    order.ScaleSubsLevelSize = ReadIntMax();
                }
                else
                {
                    /* int notSuppScaleNumComponents = */
                    ReadIntMax();
                    order.ScaleInitLevelSize = ReadIntMax();
                }
                order.ScalePriceIncrement = ReadDoubleMax();
            }

            if (msgVersion >= 28 && order.ScalePriceIncrement > 0.0 && order.ScalePriceIncrement != Double.MaxValue)
            {
                order.ScalePriceAdjustValue = ReadDoubleMax();
                order.ScalePriceAdjustInterval = ReadIntMax();
                order.ScaleProfitOffset = ReadDoubleMax();
                order.ScaleAutoReset = ReadBoolFromInt();
                order.ScaleInitPosition = ReadIntMax();
                order.ScaleInitFillQty = ReadIntMax();
                order.ScaleRandomPercent = ReadBoolFromInt();
            }

            if (msgVersion >= 24)
            {
                order.HedgeType = ReadString();
                if (!Util.StringIsEmpty(order.HedgeType))
                {
                    order.HedgeParam = ReadString();
                }
            }

            if (msgVersion >= 25)
            {
                order.OptOutSmartRouting = ReadBoolFromInt();
            }

            if (msgVersion >= 19)
            {
                order.ClearingAccount = ReadString();
                order.ClearingIntent = ReadString();
            }

            if (msgVersion >= 22)
            {
                order.NotHeld = ReadBoolFromInt();
            }

            if (msgVersion >= 20)
            {
                if (ReadBoolFromInt())
                {
                    UnderComp underComp = new UnderComp();
                    underComp.ConId = ReadInt();
                    underComp.Delta = ReadDouble();
                    underComp.Price = ReadDouble();
                    contract.UnderComp = underComp;
                }
            }

            if (msgVersion >= 21)
            {
                order.AlgoStrategy = ReadString();
                if (!Util.StringIsEmpty(order.AlgoStrategy))
                {
                    int algoParamsCount = ReadInt();
                    if (algoParamsCount > 0)
                    {
                        order.AlgoParams = new List<TagValue>(algoParamsCount);
                        for (int i = 0; i < algoParamsCount; ++i)
                        {
                            TagValue tagValue = new TagValue();
                            tagValue.tag = ReadString();
                            tagValue.value = ReadString();
                            order.AlgoParams.Add(tagValue);
                        }
                    }
                }
            }

            OrderState orderState = new OrderState();
            if (msgVersion >= 16)
            {
                order.WhatIf = ReadBoolFromInt();
                orderState.Status = ReadString();
                orderState.InitMargin = ReadString();
                orderState.MaintMargin = ReadString();
                orderState.EquityWithLoan = ReadString();
                orderState.Commission = ReadDoubleMax();
                orderState.MinCommission = ReadDoubleMax();
                orderState.MaxCommission = ReadDoubleMax();
                orderState.CommissionCurrency = ReadString();
                orderState.WarningText = ReadString();
            }

            parent.Wrapper.openOrder(order.OrderId, contract, order, orderState);
        }
Ejemplo n.º 32
0
        // orderStatus, openOrderEnd, EClientSocket::placeOrder, EClientSocket::reqAllOpenOrders, EClientSocket::reqAutoOpenOrders
        public virtual void openOrder(int orderId, Contract contract, IBApi.Order order, OrderState orderState)
        {
            // log warning
            if (!String.IsNullOrEmpty(orderState.WarningText))
            {
                OnDebug(orderState.WarningText);
            }
            if (orderState.Status != "Submitted" && orderState.Status != "Filled" && orderState.Status != "PreSubmitted")
            {
                // igore other states
                return;
            }

            Order o = new Order();

            o.OrderStatus = (OrderStatus)EnumDescConverter.GetEnumValue(typeof(OrderStatus), orderState.Status);
            if (_iborderIdToOrderInfo.ContainsKey(orderId))
            {
                if (_iborderIdToOrderInfo[orderId].IsAcknowledged)
                {
                    return;         // already acknowledged
                }
                _iborderIdToOrderInfo[orderId].IsAcknowledged = true;
                // update account as it might not have been set explicitly
                // account is used for cancelling order
                _iborderIdToOrderInfo[orderId].Account = order.Account;
            }
            else    // the order was placed directly in Tws
            {
                long soId = (long)orderId;
                _iborderIdToOrderInfo.Add(orderId, new OrderInfo(soId, order.Account, true));
                OnDebug("Got order not from strategy. Id = " + orderId + ", " + "symbol = " + contract.Symbol);
            }

            o.Id      = _iborderIdToOrderInfo[orderId].StrategyOrderId;            // strategy Order Id
            o.Account = order.Account;

            o.OrderSize = Math.Abs(order.TotalQuantity) * ((order.Action == "BUY") ? 1 : -1);

            // Order full symbol includes localsymbol, exchange, multiplier, sectype
            // o.LocalSymbol = contract.LocalSymbol;
            // o.Exchange = contract.Exchange;
            // o.Security = (SecurityType)EnumDescConverter.GetEnumValue(typeof(SecurityType), contract.SecType);
            o.FullSymbol = ContractToSecurityFullName(contract);

            o.TrailPrice = ((order.OrderType == "TRAIL") || (order.OrderType == "TRAIL LIMIT")) ? (decimal)order.AuxPrice : 0m;
            o.StopPrice  = ((order.OrderType == "STP") || (order.OrderType == "STP LMT")) ? (decimal)order.AuxPrice : 0m;
            o.LimitPrice = ((order.OrderType == "LMT") || (order.OrderType == "TRAIL LIMIT") || (order.OrderType == "STP LMT")) ? (decimal)order.LmtPrice : 0m;

            o.Currency = contract.Currency;
            // o.Currency = (CurrencyType)EnumDescConverter.GetEnumValue(typeof(CurrencyType), contract.Currency);

            // o.TIF = order.Tif;           // Todo: add Tif

            o.OrderDate = Util.ToIntDate(DateTime.Now);
            o.OrderTime = Util.ToIntTime(DateTime.Now);

            if (contract.SecType != "BAG")
            {
                OnGotOrder(o);

                // send deferred fills if any
                // iterate backwards for possible removal
                for (int i = _duplicateIBIdToDeferredTrade.Count - 1; i > -1; i--)
                {
                    if (_duplicateIBIdToDeferredTrade[i].Key == orderId)
                    {
                        Trade trade = _duplicateIBIdToDeferredTrade[i].Value;
                        trade.Id = o.Id;                // strategy id
                        _duplicateIBIdToDeferredTrade.RemoveAt(i);
                        OnGotFill(trade);
                    }
                }
            }
        }
Ejemplo n.º 33
0
        /// <summary>
        /// Place order. 
        /// Order must have contract field.
        /// </summary>
        public void PlaceOrder(Order o)
        {
            if ((!o.IsValid) || (string.IsNullOrEmpty(o.FullSymbol)))
            {
                OnDebug("Order is not valid.");
                return;
            }

            IBApi.Order order = new IBApi.Order();

            order.AuxPrice = o.IsTrail ? (double)o.TrailPrice : (double)o.StopPrice;
            order.LmtPrice = (double)o.LimitPrice;

            // Only MKT, LMT, STP, and STP LMT, TRAIL, TRAIL LIMIT are supported
            order.OrderType = o.OrderType;

            order.TotalQuantity = o.UnsignedSize;
            order.Action = o.OrderSide ? "BUY" : "SELL";         // SSHORT not supported here

            // order.Account = Account;
            order.Tif = o.TIF.ToString();
            order.OutsideRth = true;
            //order.OrderId = (int)o.id;
            order.Transmit = true;
            if (string.IsNullOrEmpty(o.Account))
                order.Account = Account;
            else
                order.Account = o.Account;

            // Set up IB order Id
            if (o.Id == 0)
            {
                throw new ArgumentOutOfRangeException("Order id is missing.");
            }
            else // TODO: elimitate situation where strategy Order Id already exists
            {
                //order.OrderId = System.Threading.Interlocked.Increment(ref _nextValidIBID); // it returns the incremented id
                order.OrderId = (int)o.Id;
                _iborderIdToOrderInfo.Add(order.OrderId, new OrderInfo(o.Id, order.Account, false));
            }


            IBApi.Contract contract = SecurityFullNameToContract(o.FullSymbol);

            _ibSocket.placeOrder(order.OrderId, contract, order);
        }
Ejemplo n.º 34
0
        private void btnSubmit_Click(object sender, RoutedEventArgs e)
        {
            ///1. Submit order
            ///a. Get Order Fields 
            ///b. Check if all fields are filled 
            ///c. Check if fields are correct
            ///d. Check limits
            ///


            var selectedSymbol = cbInstruments.Text;
            Instrument instrument = InstrumentManager.ActiveContracts.Find(x => x.BBCode == selectedSymbol);
            


            int OrderId = ibClient.NextOrderId;

            IBApi.Order order = new IBApi.Order();

            int orderSize = Convert.ToInt32(tbQty.Text);

            string mktAction;
            mktAction = (bool)rbBuy.IsChecked ? "BUY" : "SELL";




            int quantity = Convert.ToInt32(tbQty.Text);
            double lmtPrice = Convert.ToDouble(tbPrice.Text);
           // double auxPrice =  Convert.ToDouble(tbAltPrice.Text);

            //tryconvert

            string otype = cbOrderType.Text;

            if (otype != null)
                switch (otype)
                {
                    case "Market":
                        order = OrderManager.MarketOrder(OrderId, orderSize, mktAction);
                        break;

                    case "Limit":
                        order = OrderManager.LimitOrder(OrderId, orderSize, mktAction, lmtPrice);
                        break;

                    case "Stop":
                        order = OrderManager.StopOrder(OrderId, orderSize, mktAction, lmtPrice);
                        break;
                    case "TrailStop":
                        order = OrderManager.TrailingStopOrder(OrderId, orderSize, mktAction, lmtPrice);
                        break;
                }

            if (OrderManager.ValidateOrder(order))
            {
                MessageHandler.messageBox.Enqueue(new Message()
                {
                    DateTime = DateTime.Now,
                    Text = "Order #" + order.OrderId + " Validated"
                });
                ibClient.ClientSocket.placeOrder(OrderId, instrument.GetIBContract(), order);
                MessageHandler.messageBox.Enqueue(new Message()
                {
                    DateTime = DateTime.Now,
                    Text = "Order #" + order.OrderId + " Submitted"
                });
                ibClient.ClientSocket.reqIds(1);
                OrderManager.AddOrder(order);
                UpdateTables();

            }
            else
            {
                MessageHandler.messageBox.Enqueue(new Message()
                {
                    DateTime = DateTime.Now,
                    Text = "Order #" + order.OrderId + " Failed Validation"
                });
            }


        }
Ejemplo n.º 35
0
        public override void openOrder(int orderId, Contract contract, IBApi.Order order, IBApi.OrderState orderState)
        {
            using (orderInfoContainerLock.Lock())
            {
                OrderInfo orderInfo;
                if (orderInfoContainer.TryGetByTickerId(orderId, out orderInfo) ||
                    orderInfoContainer.TryGetByPermId(order.PermId, out orderInfo))
                {
                    // Заявка уже есть в раутере

                    // Запомним ее PermId
                    orderInfo.PermId = order.PermId;
                    if (order.PermId != 0)
                    {
                        orderInfoContainer.StoreByPermId(order.PermId, orderInfo);
                    }

                    // Если по ней есть транзакция, и она еще не подтверждена, то нужно отправить TransactionReply
                    if (!orderInfo.IsExternal &&
                        !orderInfo.NewOrderTransactionReplySent)
                    {
                        connector.IBOrderRouter.Transmit(new TransactionReply
                        {
                            Success       = true,
                            TransactionId = orderInfo.NewOrderTransactionId
                        });
                        orderInfo.NewOrderTransactionReplySent = true;
                    }
                    return;
                }

                // Новая заявка, ее еще нет в раутере. Нужно решить, что с нею делать
                switch (connector.IBOrderRouter.ModeInternal)
                {
                case OrderRouterMode.ThisSessionOnly:
                    // Невозобновляемая сессия, раутер не должен подцеплять старые заявки, в игнор ее
                    return;

                case OrderRouterMode.ThisSessionRenewable:
                    // Возобновляемая сессия, раутер должен подцеплять старые заявки с фильтрацией по комментарию
                    if (!connector.IBOrderRouter.FilterByComment(order.OrderRef))
                    {
                        // Чужая заявка, в игнор ее
                        return;
                    }
                    break;

                case OrderRouterMode.ExternalSessionsRenewable:
                    // Возобновляемая сессия, раутер должен подцеплять старые заявки без фильтрации по комментарию
                    break;

                default:
                    throw new ArgumentOutOfRangeException("OrderRouterMode");
                }

                // Запоминаем эту заявку
                // Инструмент у нее будет проставлен ниже
                orderInfo = new OrderInfo(order, orderState: orderState.Status)
                {
                    IsExternal = true,
                    ShouldEmitExternalOrderMessage = true
                };

                if (orderId != 0)
                {
                    orderInfoContainer.StoreByTickerId(orderId, orderInfo);
                }

                if (order.PermId != 0)
                {
                    orderInfoContainer.StoreByPermId(order.PermId, orderInfo);
                }

                // Резолвим ее инструмент
                connector.ContractContainer.GetInstrumentAsync(
                    contract,
                    $"A order \"{orderInfo.OrderId}\", account \"{orderInfo.Account}\"",
                    instrument =>
                {
                    using (orderInfoContainerLock.Lock())
                    {
                        // После резолва выплевываем заявку
                        orderInfo.Instrument = instrument;

                        if (orderInfo.ShouldEmitExternalOrderMessage)
                        {
                            // Выплевываем внешнюю заявку
                            connector.IBOrderRouter.Transmit(new ExternalOrderMessage {
                                Order = orderInfo.CreateOrder()
                            });
                            orderInfo.ShouldEmitExternalOrderMessage = false;
                        }
                    }
                });
            }
        }
Ejemplo n.º 36
0
 public void openOrder(int orderId, Contract contract, Order order, OrderState orderState)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 37
0
        public Order getOrder()
        {
            Order order = new Order();

            order.Action = tbOrderAction.Text;
            order.TotalQuantity = Int32.Parse(tbTotalOrderSize.Text, CultureInfo.InvariantCulture);
            order.OrderType = tbOrderType.Text;
            double limit = Double.Parse(tbOrderPrice.Text, CultureInfo.InvariantCulture);
            if (limit != 0.0)
            {
                order.LmtPrice = limit;
            }
            double stop = Double.Parse(tbAuxPrice.Text, CultureInfo.InvariantCulture);
            if (stop != 0.0)
            {
                order.AuxPrice = stop;
            }

            return order;
        }
Ejemplo n.º 38
0
 public virtual void openOrder(int orderId, Contract contract, IBApi.Order order, IBApi.OrderState orderState)
 {
 }
Ejemplo n.º 39
0
 public void placeOrder(int id, Contract contract, IBApi.Order order)
 {
     _Log.Debug().PrintFormat("> placeOrder id={0}, contract={1}, order={2}", id, contract, order);
     ThrowIfNotConnected();
     socket.placeOrder(id, contract, order);
 }
Ejemplo n.º 40
0
        //! [orderstatus]

        //! [openorder]
        public virtual void openOrder(int orderId, Contract contract, IBApi.Order order, OrderState orderState)
        {
            Output.WriteLine("OpenOrder. ID: " + orderId + ", " + contract.Symbol + ", " + contract.SecType + " @ " + contract.Exchange + ": " + order.Action + ", " + order.OrderType + " " + order.TotalQuantity + ", " + orderState.Status);
        }
Ejemplo n.º 41
0
        /**
         * @brief Places an order
         * @param id the order's unique identifier. Use a sequential id starting with the id received at the nextValidId method.
         * @param contract the order's contract
         * @param order the order
         * @sa nextValidId, reqAllOpenOrders, reqAutoOpenOrders, reqOpenOrders, cancelOrder, reqGlobalCancel, EWrapper::openOrder, EWrapper::orderStatus, Order, Contract
         */
        public void placeOrder(int id, Contract contract, Order order)
        {
            if (!CheckConnection())
                return;

            if (!VerifyOrder(order, id, StringsAreEqual(Constants.BagSecType, contract.SecType)))
                return;
            if (!VerifyOrderContract(contract, id))
                return;

            int MsgVersion = (serverVersion < MinServerVer.NOT_HELD ) ? 27 : 41;
            List<byte> paramsList = new List<byte>();

            paramsList.AddParameter(OutgoingMessages.PlaceOrder);
            paramsList.AddParameter(MsgVersion);
            paramsList.AddParameter(id);
            
            if (serverVersion >= MinServerVer.PLACE_ORDER_CONID)
            {
                paramsList.AddParameter(contract.ConId);
            }
            paramsList.AddParameter(contract.Symbol);
            paramsList.AddParameter(contract.SecType);
            paramsList.AddParameter(contract.Expiry);
            paramsList.AddParameter(contract.Strike);
            paramsList.AddParameter(contract.Right);
            if (serverVersion >= 15)
            {
                paramsList.AddParameter(contract.Multiplier);
            }
            paramsList.AddParameter(contract.Exchange);
            if (serverVersion >= 14)
            {
                paramsList.AddParameter(contract.PrimaryExch);
            }
            paramsList.AddParameter(contract.Currency);
            if (serverVersion >= 2)
            {
                paramsList.AddParameter(contract.LocalSymbol);
            }
            if (serverVersion >= MinServerVer.TRADING_CLASS)
            {
                paramsList.AddParameter(contract.TradingClass);
            }
            if (serverVersion >= MinServerVer.SEC_ID_TYPE)
            {
                paramsList.AddParameter(contract.SecIdType);
                paramsList.AddParameter(contract.SecId);
            }

            // paramsList.AddParameter main order fields
            paramsList.AddParameter(order.Action);
            paramsList.AddParameter(order.TotalQuantity);
            paramsList.AddParameter(order.OrderType);
            if (serverVersion < MinServerVer.ORDER_COMBO_LEGS_PRICE)
            {
                paramsList.AddParameter(order.LmtPrice == Double.MaxValue ? 0 : order.LmtPrice);
            }
            else
            {
                paramsList.AddParameterMax(order.LmtPrice);
            }
            if (serverVersion < MinServerVer.TRAILING_PERCENT)
            {
                paramsList.AddParameter(order.AuxPrice == Double.MaxValue ? 0 : order.AuxPrice);
            }
            else
            {
                paramsList.AddParameterMax(order.AuxPrice);
            }

            // paramsList.AddParameter extended order fields
            paramsList.AddParameter(order.Tif);
            paramsList.AddParameter(order.OcaGroup);
            paramsList.AddParameter(order.Account);
            paramsList.AddParameter(order.OpenClose);
            paramsList.AddParameter(order.Origin);
            paramsList.AddParameter(order.OrderRef);
            paramsList.AddParameter(order.Transmit);
            if (serverVersion >= 4)
            {
                paramsList.AddParameter(order.ParentId);
            }

            if (serverVersion >= 5)
            {
                paramsList.AddParameter(order.BlockOrder);
                paramsList.AddParameter(order.SweepToFill);
                paramsList.AddParameter(order.DisplaySize);
                paramsList.AddParameter(order.TriggerMethod);
                if (serverVersion < 38)
                {
                    // will never happen
                    paramsList.AddParameter(/* order.ignoreRth */ false);
                }
                else
                {
                    paramsList.AddParameter(order.OutsideRth);
                }
            }

            if (serverVersion >= 7)
            {
                paramsList.AddParameter(order.Hidden);
            }

            // paramsList.AddParameter combo legs for BAG requests
            bool isBag = StringsAreEqual(Constants.BagSecType, contract.SecType);
            if (serverVersion >= 8 && isBag)
            {
                if (contract.ComboLegs == null)
                {
                    paramsList.AddParameter(0);
                }
                else
                {
                    paramsList.AddParameter(contract.ComboLegs.Count);

                    ComboLeg comboLeg;
                    for (int i = 0; i < contract.ComboLegs.Count; i++)
                    {
                        comboLeg = (ComboLeg)contract.ComboLegs[i];
                        paramsList.AddParameter(comboLeg.ConId);
                        paramsList.AddParameter(comboLeg.Ratio);
                        paramsList.AddParameter(comboLeg.Action);
                        paramsList.AddParameter(comboLeg.Exchange);
                        paramsList.AddParameter(comboLeg.OpenClose);

                        if (serverVersion >= MinServerVer.SSHORT_COMBO_LEGS)
                        {
                            paramsList.AddParameter(comboLeg.ShortSaleSlot);
                            paramsList.AddParameter(comboLeg.DesignatedLocation);
                        }
                        if (serverVersion >= MinServerVer.SSHORTX_OLD)
                        {
                            paramsList.AddParameter(comboLeg.ExemptCode);
                        }
                    }
                }
            }

            // add order combo legs for BAG requests
            if (serverVersion >= MinServerVer.ORDER_COMBO_LEGS_PRICE && isBag)
            {
                if (order.OrderComboLegs == null)
                {
                    paramsList.AddParameter(0);
                }
                else
                {
                    paramsList.AddParameter(order.OrderComboLegs.Count);

                    for (int i = 0; i < order.OrderComboLegs.Count; i++)
                    {
                        OrderComboLeg orderComboLeg = order.OrderComboLegs[i];
                        paramsList.AddParameterMax(orderComboLeg.price);
                    }
                }
            }

            if (serverVersion >= MinServerVer.SMART_COMBO_ROUTING_PARAMS && isBag)
            {
                List<TagValue> smartComboRoutingParams = order.SmartComboRoutingParams;
                int smartComboRoutingParamsCount = smartComboRoutingParams == null ? 0 : smartComboRoutingParams.Count;
                paramsList.AddParameter(smartComboRoutingParamsCount);
                if (smartComboRoutingParamsCount > 0)
                {
                    for (int i = 0; i < smartComboRoutingParamsCount; ++i)
                    {
                        TagValue tagValue = smartComboRoutingParams[i];
                        paramsList.AddParameter(tagValue.Tag);
                        paramsList.AddParameter(tagValue.Value);
                    }
                }
            }

            if (serverVersion >= 9)
            {
                // paramsList.AddParameter deprecated sharesAllocation field
                paramsList.AddParameter("");
            }

            if (serverVersion >= 10)
            {
                paramsList.AddParameter(order.DiscretionaryAmt);
            }

            if (serverVersion >= 11)
            {
                paramsList.AddParameter(order.GoodAfterTime);
            }

            if (serverVersion >= 12)
            {
                paramsList.AddParameter(order.GoodTillDate);
            }

            if (serverVersion >= 13)
            {
                paramsList.AddParameter(order.FaGroup);
                paramsList.AddParameter(order.FaMethod);
                paramsList.AddParameter(order.FaPercentage);
                paramsList.AddParameter(order.FaProfile);
            }
            if (serverVersion >= 18)
            { // institutional short sale slot fields.
                paramsList.AddParameter(order.ShortSaleSlot);      // 0 only for retail, 1 or 2 only for institution.
                paramsList.AddParameter(order.DesignatedLocation); // only populate when order.shortSaleSlot = 2.
            }
            if (serverVersion >= MinServerVer.SSHORTX_OLD)
            {
                paramsList.AddParameter(order.ExemptCode);
            }
            if (serverVersion >= 19)
            {
                paramsList.AddParameter(order.OcaType);
                if (serverVersion < 38)
                {
                    // will never happen
                    paramsList.AddParameter( /* order.rthOnly */ false);
                }
                paramsList.AddParameter(order.Rule80A);
                paramsList.AddParameter(order.SettlingFirm);
                paramsList.AddParameter(order.AllOrNone);
                paramsList.AddParameterMax(order.MinQty);
                paramsList.AddParameterMax(order.PercentOffset);
                paramsList.AddParameter(order.ETradeOnly);
                paramsList.AddParameter(order.FirmQuoteOnly);
                paramsList.AddParameterMax(order.NbboPriceCap);
                paramsList.AddParameterMax(order.AuctionStrategy);
                paramsList.AddParameterMax(order.StartingPrice);
                paramsList.AddParameterMax(order.StockRefPrice);
                paramsList.AddParameterMax(order.Delta);
                // Volatility orders had specific watermark price attribs in server version 26
                double lower = (serverVersion == 26 && order.OrderType.Equals("VOL"))
                     ? Double.MaxValue
                     : order.StockRangeLower;
                double upper = (serverVersion == 26 && order.OrderType.Equals("VOL"))
                     ? Double.MaxValue
                     : order.StockRangeUpper;
                paramsList.AddParameterMax(lower);
                paramsList.AddParameterMax(upper);
            }

            if (serverVersion >= 22)
            {
                paramsList.AddParameter(order.OverridePercentageConstraints);
            }

            if (serverVersion >= 26)
            { // Volatility orders
                paramsList.AddParameterMax(order.Volatility);
                paramsList.AddParameterMax(order.VolatilityType);
                if (serverVersion < 28)
                {
                    bool isDeltaNeutralTypeMKT = (String.Compare("MKT", order.DeltaNeutralOrderType, true) == 0);
                    paramsList.AddParameter(isDeltaNeutralTypeMKT);
                }
                else
                {
                    paramsList.AddParameter(order.DeltaNeutralOrderType);
                    paramsList.AddParameterMax(order.DeltaNeutralAuxPrice);

                    if (serverVersion >= MinServerVer.DELTA_NEUTRAL_CONID && !IsEmpty(order.DeltaNeutralOrderType))
                    {
                        paramsList.AddParameter(order.DeltaNeutralConId);
                        paramsList.AddParameter(order.DeltaNeutralSettlingFirm);
                        paramsList.AddParameter(order.DeltaNeutralClearingAccount);
                        paramsList.AddParameter(order.DeltaNeutralClearingIntent);
                    }

                    if (serverVersion >= MinServerVer.DELTA_NEUTRAL_OPEN_CLOSE && !IsEmpty(order.DeltaNeutralOrderType))
                    {
                        paramsList.AddParameter(order.DeltaNeutralOpenClose);
                        paramsList.AddParameter(order.DeltaNeutralShortSale);
                        paramsList.AddParameter(order.DeltaNeutralShortSaleSlot);
                        paramsList.AddParameter(order.DeltaNeutralDesignatedLocation);
                    }
                }
                paramsList.AddParameter(order.ContinuousUpdate);
                if (serverVersion == 26)
                {
                    // Volatility orders had specific watermark price attribs in server version 26
                    double lower = order.OrderType.Equals("VOL") ? order.StockRangeLower : Double.MaxValue;
                    double upper = order.OrderType.Equals("VOL") ? order.StockRangeUpper : Double.MaxValue;
                    paramsList.AddParameterMax(lower);
                    paramsList.AddParameterMax(upper);
                }
                paramsList.AddParameterMax(order.ReferencePriceType);
            }

            if (serverVersion >= 30)
            { // TRAIL_STOP_LIMIT stop price
                paramsList.AddParameterMax(order.TrailStopPrice);
            }

            if (serverVersion >= MinServerVer.TRAILING_PERCENT)
            {
                paramsList.AddParameterMax(order.TrailingPercent);
            }

            if (serverVersion >= MinServerVer.SCALE_ORDERS)
            {
                if (serverVersion >= MinServerVer.SCALE_ORDERS2)
                {
                    paramsList.AddParameterMax(order.ScaleInitLevelSize);
                    paramsList.AddParameterMax(order.ScaleSubsLevelSize);
                }
                else
                {
                    paramsList.AddParameter("");
                    paramsList.AddParameterMax(order.ScaleInitLevelSize);

                }
                paramsList.AddParameterMax(order.ScalePriceIncrement);
            }

            if (serverVersion >= MinServerVer.SCALE_ORDERS3 && order.ScalePriceIncrement > 0.0 && order.ScalePriceIncrement != Double.MaxValue)
            {
                paramsList.AddParameterMax(order.ScalePriceAdjustValue);
                paramsList.AddParameterMax(order.ScalePriceAdjustInterval);
                paramsList.AddParameterMax(order.ScaleProfitOffset);
                paramsList.AddParameter(order.ScaleAutoReset);
                paramsList.AddParameterMax(order.ScaleInitPosition);
                paramsList.AddParameterMax(order.ScaleInitFillQty);
                paramsList.AddParameter(order.ScaleRandomPercent);
            }

            if (serverVersion >= MinServerVer.SCALE_TABLE)
            {
                paramsList.AddParameter(order.ScaleTable);
                paramsList.AddParameter(order.ActiveStartTime);
                paramsList.AddParameter(order.ActiveStopTime);
            }

            if (serverVersion >= MinServerVer.HEDGE_ORDERS)
            {
                paramsList.AddParameter(order.HedgeType);
                if (!IsEmpty(order.HedgeType))
                {
                    paramsList.AddParameter(order.HedgeParam);
                }
            }

            if (serverVersion >= MinServerVer.OPT_OUT_SMART_ROUTING)
            {
                paramsList.AddParameter(order.OptOutSmartRouting);
            }

            if (serverVersion >= MinServerVer.PTA_ORDERS)
            {
                paramsList.AddParameter(order.ClearingAccount);
                paramsList.AddParameter(order.ClearingIntent);
            }

            if (serverVersion >= MinServerVer.NOT_HELD)
            {
                paramsList.AddParameter(order.NotHeld);
            }

            if (serverVersion >= MinServerVer.UNDER_COMP)
            {
                if (contract.UnderComp != null)
                {
                    UnderComp underComp = contract.UnderComp;
                    paramsList.AddParameter(true);
                    paramsList.AddParameter(underComp.ConId);
                    paramsList.AddParameter(underComp.Delta);
                    paramsList.AddParameter(underComp.Price);
                }
                else
                {
                    paramsList.AddParameter(false);
                }
            }

            if (serverVersion >= MinServerVer.ALGO_ORDERS)
            {
                paramsList.AddParameter(order.AlgoStrategy);
                if (!IsEmpty(order.AlgoStrategy))
                {
                    List<TagValue> algoParams = order.AlgoParams;
                    int algoParamsCount = algoParams == null ? 0 : algoParams.Count;
                    paramsList.AddParameter(algoParamsCount);
                    if (algoParamsCount > 0)
                    {
                        for (int i = 0; i < algoParamsCount; ++i)
                        {
                            TagValue tagValue = (TagValue)algoParams[i];
                            paramsList.AddParameter(tagValue.Tag);
                            paramsList.AddParameter(tagValue.Value);
                        }
                    }
                }
            }

            if (serverVersion >= MinServerVer.WHAT_IF_ORDERS)
            {
                paramsList.AddParameter(order.WhatIf);
            }

            Send(id, paramsList, EClientErrors.FAIL_SEND_ORDER);
        }
Ejemplo n.º 42
0
 private Order GetOrder()
 {
     Order order = new Order();
     if (orderId != 0)
         order.OrderId = orderId;
     order.Action = action.Text;
     order.OrderType = orderType.Text;
     if(!lmtPrice.Text.Equals(""))
         order.LmtPrice = Double.Parse(lmtPrice.Text);
     if(!quantity.Text.Equals(""))
         order.TotalQuantity = Int32.Parse(quantity.Text);
     order.Account = account.Text;
     order.Tif = timeInForce.Text;
     if (!auxPrice.Text.Equals(""))
         order.AuxPrice = Double.Parse(auxPrice.Text);
     if (!displaySize.Text.Equals(""))
         order.DisplaySize = Int32.Parse(displaySize.Text);
     order = GetExtendedOrderAttributes(order);
     order = GetAdvisorAttributes(order);
     order = GetVolatilityAttributes(order);
     order = GetScaleAttributes(order);
     order = GetAlgoAttributes(order);
     return order;
 }
Ejemplo n.º 43
0
 public virtual void openOrder(int orderId, Contract contract, Order order, OrderState orderState)
 {
     MyLogger.Instance.CreateEntry("OpenOrder. ID: " + orderId + ", " + contract.Symbol + ", " + contract.SecType + " @ " + contract.Exchange + ": " + order.Action + ", " + order.OrderType + " " + order.TotalQuantity + ", " + orderState.Status + "\n");
     Console.WriteLine("OpenOrder. ID: " + orderId + ", " + contract.Symbol + ", " + contract.SecType + " @ " + contract.Exchange + ": " + order.Action + ", " + order.OrderType + " " + order.TotalQuantity + ", " + orderState.Status + "\n");
 }
Ejemplo n.º 44
0
        private Order GetExtendedOrderAttributes(Order order)
        {
            order.OrderRef = orderReference.Text;
            if (!minQty.Text.Equals(""))
                order.MinQty = Int32.Parse(minQty.Text);
            order.GoodAfterTime = goodAfter.Text;
            order.GoodTillDate = goodUntil.Text;
            order.Rule80A = (string)((IBType)rule80A.SelectedItem).Value;
            order.TriggerMethod = (int)((IBType)triggerMethod.SelectedItem).Value;

            if(!percentOffset.Text.Equals(""))
                order.PercentOffset = Double.Parse(percentOffset.Text);
            if (!trailStopPrice.Text.Equals(""))
                order.TrailStopPrice = Double.Parse(trailStopPrice.Text);
            if (!trailingPercent.Text.Equals(""))
                order.TrailingPercent = Double.Parse(trailingPercent.Text);
            if (!discretionaryAmount.Text.Equals(""))
                order.DiscretionaryAmt = Int32.Parse(discretionaryAmount.Text);
            if (!nbboPriceCap.Text.Equals(""))
                order.NbboPriceCap = Double.Parse(nbboPriceCap.Text);

            order.OcaGroup = ocaGroup.Text;
            order.OcaType = (int)((IBType)ocaType.SelectedItem).Value;
            order.HedgeType = (string)((IBType)hedgeType.SelectedItem).Value;
            order.HedgeParam = hedgeParam.Text;
                        
            order.NotHeld = notHeld.Checked;
            order.BlockOrder = block.Checked;
            order.SweepToFill = sweepToFill.Checked;
            order.Hidden = hidden.Checked;
            order.OutsideRth = outsideRTH.Checked;
            order.AllOrNone = allOrNone.Checked;
            order.OverridePercentageConstraints = overrideConstraints.Checked;
            order.ETradeOnly = eTrade.Checked;
            order.FirmQuoteOnly = firmQuote.Checked;
            order.OptOutSmartRouting = optOutSmart.Checked;
            order.Transmit = transmit.Checked;

            return order;
        }
Ejemplo n.º 45
0
        public int PlaceOrder(Contract p_contract, TransactionType p_transactionType, double p_volume, OrderExecution p_orderExecution, OrderTimeInForce p_orderTif, double? p_limitPrice, double? p_stopPrice, double p_estimatedPrice, bool p_isSimulatedTrades)
        {

            Order order = new Order();
            switch (p_transactionType)
            {
                case TransactionType.BuyAsset:
                    order.Action = "BUY";
                    break;
                case TransactionType.SellAsset:
                    order.Action = "SELL";
                    break;
                default:
                    throw new Exception($"Unexpected transactionType: {p_transactionType}");
            }

            order.TotalQuantity = p_volume;
            if (p_limitPrice != null)
                order.LmtPrice = (double)p_limitPrice;

            switch (p_orderExecution)
            {
                case OrderExecution.Market:
                    order.OrderType = "MKT";
                    break;
                case OrderExecution.MarketOnClose:
                    order.OrderType = "MOC";
                    break;
                default:
                    throw new Exception($"Unexpected OrderExecution: {p_orderExecution}");
            }

            switch (p_orderTif)
            {
                case OrderTimeInForce.Day:  // Day is the default, so don't do anything
                    order.Tif = "DAY";
                    break;
                default:
                    throw new Exception($"Unexpected OrderTimeInForce: {p_orderTif}");
            }

            int p_realOrderId = NextOrderId++;
            OrderSubscriptions.TryAdd(p_realOrderId, new OrderSubscription() { Contract = p_contract, Order = order });
            if (!p_isSimulatedTrades)
                ClientSocket.placeOrder(p_realOrderId, p_contract, order);
            return p_realOrderId;
        }
Ejemplo n.º 46
0
        private Order GetVolatilityAttributes(Order order)
        {
            if(!volatility.Text.Equals(""))
                order.Volatility = Double.Parse(volatility.Text);
            order.VolatilityType = (int)((IBType)volatilityType.SelectedItem).Value;
            if(continuousUpdate.Checked)
                order.ContinuousUpdate = 1;
            else
                order.ContinuousUpdate = 0;
            order.ReferencePriceType = (int)((IBType)optionReferencePrice.SelectedItem).Value;
            
            if(!deltaNeutralOrderType.Text.Equals("None"))
                order.DeltaNeutralOrderType = deltaNeutralOrderType.Text;

            if (!deltaNeutralAuxPrice.Text.Equals(""))
                order.DeltaNeutralAuxPrice = Double.Parse(deltaNeutralAuxPrice.Text);
            if (!deltaNeutralConId.Text.Equals(""))
                order.DeltaNeutralConId = Int32.Parse(deltaNeutralConId.Text);
            if (!stockRangeLower.Text.Equals(""))
                order.StockRangeLower = Double.Parse(stockRangeLower.Text);
            if (!stockRangeUpper.Text.Equals(""))
                order.StockRangeUpper = Double.Parse(stockRangeUpper.Text);
            return order;
        }