Esempio n. 1
0
 /// <summary>
 /// Full Constructor
 /// </summary>
 /// <param name="orderId">The order Id assigned by TWS. Used to cancel or update the order.</param>
 /// <param name="contract">Describes the contract for the open order.</param>
 /// <param name="order">Gives the details of the open order.</param>
 /// <param name="orderState">The openOrder() callback with the new OrderState() object will now be invoked each time TWS receives commission information for a trade.</param>
 public OpenOrderEventArgs(int orderId, Contract contract, Order order, OrderState orderState)
 {
     this.orderId = orderId;
     this.order = order;
     this.contract = contract;
     this.orderState = orderState;
 }
Esempio n. 2
0
 ///<summary>
 /// Parameterless OpenOrderEventArgs Constructor
 ///</summary>
 public OpenOrderEventArgs()
 {
     this.orderId = -1;
     this.order = new Order();
     this.contract = new Contract();
     this.orderState = new OrderState();
 }
Esempio n. 3
0
        /// <summary>
        /// Converts a QC order to an IB order
        /// </summary>
        private IB.Order ConvertOrder(Order order)
        {
            var ibOrder = new IB.Order();

            ibOrder.ClientId = _clientID;

            int id = AddInteractiveBrokersOrderID(order);

            // the order ids are generated for us by the SecurityTransactionManaer
            ibOrder.OrderId       = id;
            ibOrder.PermId        = id;
            ibOrder.Action        = ConvertOrderDirection(order.Direction);
            ibOrder.TotalQuantity = Math.Abs(order.Quantity);
            ibOrder.OrderType     = ConvertOrderType(order.Type);

            if (ibOrder.OrderType == IB.OrderType.Limit)
            {
                ibOrder.LimitPrice = (order as LimitOrder).LimitPrice;
            }
            else if (ibOrder.OrderType == IB.OrderType.Stop)
            {
                ibOrder.AuxPrice = (order as StopMarketOrder).StopPrice;
            }

            // not yet supported
            //ibOrder.ParentId =
            //ibOrder.OcaGroup =

            ibOrder.AllOrNone = false;
            ibOrder.Tif       = IB.TimeInForce.GoodTillCancel;
            ibOrder.Transmit  = true;
            ibOrder.Rule80A   = _agentDescription;

            return(ibOrder);
        }
Esempio n. 4
0
        private Order ConvertOrder(IB.Order ibOrder, IB.Contract contract)
        {
            decimal price = 0;

            if (ibOrder.LimitPrice != 0)
            {
                price = ibOrder.LimitPrice;
            }
            else if (ibOrder.AuxPrice != 0)
            {
                price = ibOrder.AuxPrice;
            }

            var order = new Order(contract.Symbol,
                                  ConvertSecurityType(contract.SecurityType),
                                  ibOrder.TotalQuantity,
                                  ConvertOrderType(ibOrder.OrderType),
                                  new DateTime(), // not sure how to get this data
                                  price
                                  );

            order.BrokerId.Add(ibOrder.OrderId);

            return(order);
        }
Esempio n. 5
0
        /// <summary>
        /// Converts a QC order to an IB order
        /// </summary>
        private IB.Order ConvertOrder(Order order, int ibOrderID)
        {
            var ibOrder = new IB.Order
            {
                ClientId      = _clientID,
                OrderId       = ibOrderID,
                Action        = ConvertOrderDirection(order.Direction),
                TotalQuantity = Math.Abs(order.Quantity),
                OrderType     = ConvertOrderType(order.Type),
                AllOrNone     = false,
                Tif           = IB.TimeInForce.GoodTillCancel,
                Transmit      = true,
                Rule80A       = _agentDescription
            };

            var limitOrder      = order as LimitOrder;
            var stopMarketOrder = order as StopMarketOrder;

            if (limitOrder != null)
            {
                ibOrder.LimitPrice = limitOrder.LimitPrice;
            }
            else if (stopMarketOrder != null)
            {
                ibOrder.AuxPrice = stopMarketOrder.StopPrice;
            }

            // not yet supported
            //ibOrder.ParentId =
            //ibOrder.OcaGroup =

            return(ibOrder);
        }
Esempio n. 6
0
        private Order ConvertOrder(IB.Order ibOrder, IB.Contract contract)
        {
            // this function is called by GetOpenOrders which is mainly used by the setup handler to
            // initialize algorithm state.  So the only time we'll be executing this code is when the account
            // has orders sitting and waiting from before algo initialization...
            // because of this we can't get the time accurately

            Order order;
            var   mappedSymbol = MapSymbol(contract);
            var   orderType    = ConvertOrderType(ibOrder.OrderType);

            switch (orderType)
            {
            case OrderType.Market:
                order = new MarketOrder(mappedSymbol,
                                        ibOrder.TotalQuantity,
                                        new DateTime() // not sure how to get this data
                                        );
                break;

            case OrderType.Limit:
                order = new LimitOrder(mappedSymbol,
                                       ibOrder.TotalQuantity,
                                       ibOrder.LimitPrice,
                                       new DateTime()
                                       );
                break;

            case OrderType.StopMarket:
                order = new StopMarketOrder(mappedSymbol,
                                            ibOrder.TotalQuantity,
                                            ibOrder.AuxPrice,
                                            new DateTime()
                                            );
                break;

            case OrderType.StopLimit:
                order = new StopLimitOrder(mappedSymbol,
                                           ibOrder.TotalQuantity,
                                           ibOrder.AuxPrice,
                                           ibOrder.LimitPrice,
                                           new DateTime()
                                           );
                break;

            default:
                throw new InvalidEnumArgumentException("orderType", (int)orderType, typeof(OrderType));
            }

            order.SecurityType = ConvertSecurityType(contract.SecurityType);
            order.BrokerId.Add(ibOrder.OrderId);

            return(order);
        }
Esempio n. 7
0
        private Order ConvertOrder(IB.Order ibOrder, IB.Contract contract)
        {
            decimal price = 0;

            if (ibOrder.LimitPrice != 0)
            {
                price = ibOrder.LimitPrice;
            }
            else if (ibOrder.AuxPrice != 0)
            {
                price = ibOrder.AuxPrice;
            }

            Order order;
            var   orderType    = ConvertOrderType(ibOrder.OrderType);
            var   securityType = ConvertSecurityType(contract.SecurityType);

            switch (orderType)
            {
            default:
            case OrderType.Market:
                order = new MarketOrder(contract.Symbol, ibOrder.TotalQuantity, new DateTime(), "", securityType);
                break;

            case OrderType.Limit:
                order = new LimitOrder(contract.Symbol, ibOrder.TotalQuantity, price, new DateTime(), "", securityType);
                break;

            case OrderType.StopMarket:
                order = new StopMarketOrder(contract.Symbol, ibOrder.TotalQuantity, price, new DateTime(), "", securityType);
                break;
            }

            order.BrokerId.Add(ibOrder.OrderId);

            return(order);
        }
        /// <summary>
        /// Converts a QC order to an IB order
        /// </summary>
        private IB.Order ConvertOrder(Order order, IB.Contract contract, int ibOrderID)
        {
            var ibOrder = new IB.Order
            {
                ClientId = _clientID,
                OrderId = ibOrderID,
                Account = _account,
                Action = ConvertOrderDirection(order.Direction),
                TotalQuantity = Math.Abs(order.Quantity),
                OrderType = ConvertOrderType(order.Type),
                AllOrNone = false,
                Tif = IB.TimeInForce.GoodTillCancel,
                Transmit = true,
                Rule80A = _agentDescription
            };

            if (order.Type == OrderType.MarketOnOpen)
            {
                ibOrder.Tif = IB.TimeInForce.MarketOnOpen;
            }

            var limitOrder = order as LimitOrder;
            var stopMarketOrder = order as StopMarketOrder;
            var stopLimitOrder = order as StopLimitOrder;
            if (limitOrder != null)
            {
                ibOrder.LimitPrice = RoundPrice(limitOrder.LimitPrice, GetMinTick(contract));
            }
            else if (stopMarketOrder != null)
            {
                ibOrder.AuxPrice = RoundPrice(stopMarketOrder.StopPrice, GetMinTick(contract));
            }
            else if (stopLimitOrder != null)
            {
                var minTick = GetMinTick(contract);
                ibOrder.LimitPrice = RoundPrice(stopLimitOrder.LimitPrice, minTick);
                ibOrder.AuxPrice = RoundPrice(stopLimitOrder.StopPrice, minTick);
            }

            // not yet supported
            //ibOrder.ParentId = 
            //ibOrder.OcaGroup =

            return ibOrder;
        }
Esempio n. 9
0
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        //[STAThread]
        static void Main(string[] args)
        {
            client = new IBClient();
            client.ThrowExceptions = true;

            client.TickPrice += client_TickPrice;
            client.TickSize += client_TickSize;
            client.Error += client_Error;
            client.NextValidId += client_NextValidId;
            client.UpdateMarketDepth += client_UpdateMktDepth;
            client.RealTimeBar += client_RealTimeBar;
            client.OrderStatus += client_OrderStatus;
            client.ExecDetails += client_ExecDetails;

            Console.WriteLine("Connecting to IB.");
            client.Connect("127.0.0.1", 7496, 0);
            TF = new Contract("TF", "NYBOT", SecurityType.Future, "USD", "200909");
            YmEcbot = new Contract("YM", "ECBOT", SecurityType.Future, "USD", "200909");
            ES = new Contract("ES", "GLOBEX", SecurityType.Future, "USD", "200909");
            SPY = new Contract("SPY", "GLOBEX", SecurityType.Future, "USD", "200909");
            ZN = new Contract("ZN", "ECBOT", SecurityType.Future, "USD", "200909");
            ZB = new Contract("ZB", "ECBOT", SecurityType.Future, "USD", "200909");
            ZT = new Contract("ZT", "ECBOT", SecurityType.Future, "USD", "200909");
            AAPL = new Contract("ZF", "ECBOT", SecurityType.Future, "USD", "200909");

            //TickNasdaq = new Contract("TICK-NASD", "NASDAQ", SecurityType.Index, "USD");
            //VolNasdaq = new Contract("VOL-NASD", "NASDAQ", SecurityType.Index, "USD");
            //AdNasdaq = new Contract("AD-NASD", "NASDAQ", SecurityType.Index, "USD");


            //TickNyse = new Contract("TICK-NYSE", "NYSE", SecurityType.Index, "USD");
            //VolNyse = new Contract("VOL-NYSE", "NYSE", SecurityType.Index, "USD");
            //AdNyse = new Contract("AD-NYSE", "NYSE", SecurityType.Index, "USD");

            //New Contract Creation Features
            Equity Google = new Equity("GOOG");

            client.RequestMarketData(14, Google, null, false, false);
            client.RequestMarketDepth(15, Google, 5);
            client.RequestRealTimeBars(16, Google, 5, RealTimeBarType.Trades, false);

            Order BuyContract = new Order();
            BuyContract.Action = ActionSide.Sell;
            BuyContract.OutsideRth = false;
            BuyContract.LimitPrice = 560;
            BuyContract.OrderType = OrderType.Market;
            BuyContract.TotalQuantity = 1;
            BuyContract.AuxPrice = 560;       
            
            
            client.PlaceOrder(NextOrderId, Google, BuyContract);
            client.RequestIds(1);

            client.RequestExecutions(34, new ExecutionFilter());

            client.RequestAllOpenOrders();

            //Application.EnableVisualStyles();
            //Application.SetCompatibleTextRenderingDefault(false);
            //Application.Run(new Form1());

            while (true)
            {
                Thread.Sleep(100);
            }
        }
Esempio n. 10
0
        //Take in an order in the canonical format, translate it, and add to the internal queue
        public int submitOrder(FlexTrade.Order o) 
        {
            int currentID = orderIdCounter;
            //Must pass all orders through the risk filter to ensure that it is compliant
            try
            {
                log.Debug("Running order #" + o.internalId + " through risk filter.");
                riskFilter.isAcceptable(o);
            }
            catch(UnacceptableRiskException e)
            {
                log.Error("Order " + o.internalId + " rejected by risk filter");
                
                //Alert any interested in hearing about orders caught by the risk filter 
                if(RiskFilterFailure != null)
                    RiskFilterFailure(e.riskFilterMessages);
                
                //Rethrow the messages so that the sender of the order knows it failed
                throw;
            }

            //If the order ID is still set to -1, then we haven't received the intial ID value from IB
            //We must wait until this is received.
            if (!isReadyToTakeOrders())
            {
                log.Error("Manager not fully initialized.");
                return -1;
            }
            else
            {
                Contract contract = null;

                //Translate to the internal representation of an order
                Krs.Ats.IBNet.Order internalOrder = new Krs.Ats.IBNet.Order();
                internalOrder.Action = (o.side.Equals(FlexTrade.Order.Side.BUY) ? ActionSide.Buy : ActionSide.Sell);
                internalOrder.OutsideRth = false;
                internalOrder.TotalQuantity = o.orderQuantity;
                internalOrder.OrderId = currentID;
                o.internalId = currentID;

                contract = createContractFromProduct(o.product);

                if (o is FlexTrade.LimitOrder)
                {
                    internalOrder.OrderType = OrderType.Limit;
                    internalOrder.LimitPrice = (decimal)((FlexTrade.LimitOrder)o).limitPrice;
                    internalOrder.AuxPrice = 0;
                }
                else if (o is FlexTrade.MarketOrder)
                {
                    internalOrder.OrderType = OrderType.Market;
                    internalOrder.AuxPrice = 0;
                }
                else
                {
                    //throw exception!! We don't support other order types
                }

                //Keeping track of all the objects involved
                orderInputQueue.Add(internalOrder);
                openOrderContracts.Add(currentID, contract);
                ordersOrgFormat.Add(currentID, o);

                //TODO For now this will be done on the same thread. It was created as a separate method to remind me that it would be
                //better to execute this asynchronously for improved performance in the future.
                log.Info("Sending order #" + internalOrder.OrderId + " for " + internalOrder.TotalQuantity + " of " + contract.Symbol);
                placeOrder(internalOrder, contract);
                requestMarketDataForProduct(o.product);
                o.status = Order.OrderStatus.SENT;

                //increment the order and ticker IDs for the next order and contract
                orderIdCounter++;

                return currentID;
            }
        }
Esempio n. 11
0
        //Place the orders
        public static void PlaceOrders()
        {
            int id = nextOrderId;

            fPlaceOrders = true;

            Logger.WriteToLog(DateTime.Now, string.Format("ClientManager.PlaceOrders: start placing orders for {0}", Mode) , Program.UserId);

            foreach (OrderInfo order in orders)
            {
                Equity stock = new Equity(order.Symbol);

                if (order.Amount == 0)
                    continue;

                Order contract = new Order{ Action = order.Direction == "Buy" ? ActionSide.Buy : ActionSide.Sell,TotalQuantity = order.Amount };

                contract.Tif = TimeInForce.Day;

                order.OrderId = id;

                try
                {
                    client.PlaceOrder(id++, stock, contract);
                    Logger.WriteToLog(DateTime.Now,String.Format("ClientManager.PlaceOrders: orderid: {0,-4} symbol:{1,-4} diraction:{2,-4} amount:{3,-4} stutus:{4,-4}",order.OrderId, stock.Symbol, contract.Action, contract.TotalQuantity, order.Status), Program.UserId);
                }
                catch (Exception e)
                {
                    Logger.WriteToLog(DateTime.Now, String.Format("ClientManager.PlaceOrders: {0}", e.Message),Program.UserId);
                }
            }

                fdone = true;
                Logger.WriteToLog(DateTime.Now, String.Format("ClientManager.PlaceOrders: done placing orders"), Program.UserId);
                Logger.WriteToProgramLog(DateTime.Now, string.Format("{0}: done placing {1} orders", Program.UserId,execCounter));
        }
Esempio n. 12
0
        public bool SubmitOrder(RightEdge.Common.BrokerOrder order, out string orderId)
        {
            Krs.Ats.IBNet.Order apiOrder = new Krs.Ats.IBNet.Order();
            Contract contract;
            int intOrderId;

            lock (_lockObject)
            {
                // Before we submit the order, we need to make sure the price is trimmed
                // to something that IB will accept.  In other words, if a price is submitted
                // for 40.1032988923, this will be get rejected.

                order.LimitPrice = RoundPrice(order.OrderSymbol, order.LimitPrice);
                order.StopPrice = RoundPrice(order.OrderSymbol, order.StopPrice);

                contract = TWSAssetArgs.Create(order.OrderSymbol).ToContract();

                if (order.TransactionType == TransactionType.Buy ||
                    order.TransactionType == TransactionType.Cover)
                {
                    apiOrder.Action = ActionSide.Buy;
                }
                else if (order.TransactionType == TransactionType.Sell)
                {
                    apiOrder.Action = ActionSide.Sell;
                }
                else if (order.TransactionType == TransactionType.Short)
                {
                    //	SShort is apparently only used as part of a combo leg, and you get an "Invalid side" error if you try to use it otherwise
                    //apiOrder.Action = ActionSide.SShort;
                    apiOrder.Action = ActionSide.Sell;
                }
                else
                {
                    throw new RightEdgeError("Cannot submit order with transaction type " + order.TransactionType.ToString());
                }

                double limitPrice = 0.0;
                double auxPrice = 0.0;

                switch (order.OrderType)
                {
                    case RightEdge.Common.OrderType.Limit:
                        apiOrder.OrderType = Krs.Ats.IBNet.OrderType.Limit;
                        limitPrice = order.LimitPrice;
                        break;

                    case RightEdge.Common.OrderType.LimitOnClose:
                        apiOrder.OrderType = Krs.Ats.IBNet.OrderType.LimitOnClose;
                        limitPrice = order.LimitPrice;
                        break;

                    case RightEdge.Common.OrderType.Market:
                    case RightEdge.Common.OrderType.MarketOnOpen:
                        apiOrder.OrderType = Krs.Ats.IBNet.OrderType.Market;
                        break;

                    case RightEdge.Common.OrderType.MarketOnClose:
                        apiOrder.OrderType = Krs.Ats.IBNet.OrderType.MarketOnClose;
                        break;

                    case RightEdge.Common.OrderType.PeggedToMarket:
                        apiOrder.OrderType = Krs.Ats.IBNet.OrderType.PeggedToMarket;
                        break;

                    case RightEdge.Common.OrderType.Stop:
                        apiOrder.OrderType = Krs.Ats.IBNet.OrderType.Stop;
                        auxPrice = order.StopPrice;
                        break;

                    case RightEdge.Common.OrderType.StopLimit:
                        apiOrder.OrderType = Krs.Ats.IBNet.OrderType.StopLimit;
                        auxPrice = order.StopPrice;
                        limitPrice = order.LimitPrice;
                        break;

                    //	TODO: investigate and add support for trailing stop
                    case RightEdge.Common.OrderType.TrailingStop:
                        if (order.TrailingStopType != TargetPriceType.RelativePrice)
                        {
                            lastError = order.TrailingStopType.ToString() + " trailing stops not supported by IB.";
                            orderId = null;
                            return false;
                        }
                        apiOrder.OrderType = Krs.Ats.IBNet.OrderType.TrailingStop;
                        auxPrice = order.TrailingStop;
                        break;
                    default:
                        lastError = "Order type not supported by IB service: " + order.OrderType.ToString();
                        orderId = null;
                        return false;
                }

                if (double.IsNaN(limitPrice))
                {
                    throw new RightEdgeError("Limit price for order cannot be NaN");
                }
                if (double.IsNaN(auxPrice))
                {
                    throw new RightEdgeError("Stop price for order cannot be NaN");
                }

                apiOrder.LimitPrice = (Decimal)limitPrice;
                apiOrder.AuxPrice = (Decimal)auxPrice;

                if (order.GoodTillCanceled)
                {
                    //DateTime gtcDate = GetAccountTime("SubmitOrder").AddMonths(12);
                    //apiOrder.GoodTillDate = gtcDate.ToString("yyyyMMdd");
                    //apiOrder.GoodTillDate = "";
                    apiOrder.GoodTillDate = "GTC";
                    apiOrder.Tif = TimeInForce.GoodTillCancel;
                }

                apiOrder.TotalQuantity = (int)order.Shares;
                apiOrder.FAGroup = accountCode;
                apiOrder.FAMethod = _FAMethod;
                apiOrder.FAPercentage = _FAPercentage;
                apiOrder.FAProfile = _FAProfile;
                //	TODOSOON: Verify that RTH still works after upgrading Krs library
                //if (_useRTH)
                //{
                //    apiOrder.IgnoreRth = true;
                //    apiOrder.RthOnly = true;
                //}
                apiOrder.OutsideRth = !_useRTH;

                orderId = nextOrderId.ToString();
                order.OrderId = orderId;
                openOrders.Add(orderId, order);

                unSubmittedOrders[order.OrderId] = true;

                intOrderId = nextOrderId;

                nextOrderId++;
            }

            client.PlaceOrder(intOrderId, contract, apiOrder);

            Trace.WriteLine("IB Sent: " + order.ToString());

            return true;
        }
        /// <summary>
        /// Converts a QC order to an IB order
        /// </summary>
        private IB.Order ConvertOrder(Order order)
        {
            var ibOrder = new IB.Order();
            ibOrder.ClientId = _clientID;

            int id = AddInteractiveBrokersOrderID(order);

            // the order ids are generated for us by the SecurityTransactionManaer
            ibOrder.OrderId = id;
            ibOrder.PermId = id;
            ibOrder.Action = ConvertOrderDirection(order.Direction);
            ibOrder.TotalQuantity = Math.Abs(order.Quantity);
            ibOrder.OrderType = ConvertOrderType(order.Type);

            if (ibOrder.OrderType == IB.OrderType.Limit)
            {
                ibOrder.LimitPrice = order.Price;
            }
            else if (ibOrder.OrderType == IB.OrderType.Stop)
            {
                ibOrder.AuxPrice = order.Price;
            }
            else if (ibOrder.OrderType == IB.OrderType.TrailingStop)
            {
                ibOrder.TrailStopPrice = order.Price;
            }

            // not yet supported
            //ibOrder.ParentId =
            //ibOrder.OcaGroup =

            ibOrder.AllOrNone = false;
            ibOrder.Tif = IB.TimeInForce.GoodTillCancel;
            ibOrder.Transmit = true;
            ibOrder.Rule80A = _agentDescription;

            return ibOrder;
        }