Trading Evolution

Markets are never wrong - opinions often are

How to attach stop loss order to any order

Everybody knows that stop loss orders are important. Interactive Brokers API allows you to send an order with attached stop loss so you don't have to write code to monitor when order is filled then you place your stop order. You can send your order and attached stop loss order which will be monitored by Interactive Brokers and as soon as the main order is filled Interactive Brokers will activate your stop. When order is not filled and you cancel it stop loss order will be cancelled as well.

var entryOrder = new IBApi.Order();

entryOrder.OrderId	= _ibWrapper.NextOrderId++;
entryOrder.Action	= "BUY";
entryOrder.OrderType	= "LMT";
entryOrder.LmtPrice	= price;
entryOrder.TotalQuantity = quantity;
entryOrder.Tif		= "GTC";
entryOrder.Transmit	= false;
_ibWrapper.IBClient.placeOrder(entryOrder.OrderId, contract, entryOrder);

var stopOrder = new IBApi.Order();

stopOrder.OrderId	= _ibWrapper.NextOrderId++;
stopOrder.ParentId	= entryOrder.OrderId;
stopOrder.Action	= "SELL";
stopOrder.OrderType	= "STP";
stopOrder.AuxPrice	= stopPrice;
stopOrder.TotalQuantity	= entryOrder.TotalQuantity;
stopOrder.Tif		= "GTC";
stopOrder.Transmit	= false;
_ibWrapper.IBClient.placeOrder(stopOrder.OrderId, contract, stopOrder);

Thread.Sleep(1000); // Let IB process orders first and then transmit parent order

entryOrder.Transmit         = true;
_ibWrapper.IBClient.placeOrder(entryOrder.OrderId, contract, entryOrder);

Few things to note here. First, set stop loss order ParentId to entry order Id. Second, entry order and stop loss order are sent with Transmit field set to "false" and finally transmit entry order.