I am working with the ibrokers package in R and am trying to set multiple closing prices for a trade. For example, buy 100 shares of AAPL at $106, sell 50 at $107 and 50 at $108, with a stop price of $105.
When I send the multiple profit taking orders, it seems like the quantity of 50 is ignored, instead I get two sell orders for 100 shares each.
This is the code I am running
tws <- twsConnect()
stock <- twsEquity("AAPL")
parentLongId <- reqIds(tws)
parentLongOrder <- twsOrder(parentLongId, action="BUY", totalQuantity = 100,
orderType = "LMT", lmtPrice = 106,
transmit=TRUE)
placeOrder(tws, stock, parentLongOrder)
childLongProfitId <- reqIds(tws)
childLongProfitOrder <- twsOrder(childLongProfitId, action="SELL", totalQuantity = 50,
orderType = "LMT", lmtPrice = 107,
transmit=TRUE, parentId = parentLongId)
placeOrder(tws, stock, childLongProfitOrder)
childLongProfitId2 <- reqIds(tws)
childLongProfitOrder2 <- twsOrder(childLongProfitId2, action="SELL", totalQuantity = 50,
orderType = "LMT", lmtPrice = 108,
transmit=TRUE, parentId = parentLongId)
placeOrder(tws, stock, childLongProfitOrder2)
childLongStopId <- reqIds(tws)
childLongStopOrder <- twsOrder(childLongStopId, action="SELL", totalQuantity = 100,
orderType = "STP", auxPrice = 105,
transmit=TRUE, parentId = parentLongId, account=accountNum)
placeOrder(tws, stock, childLongStopOrder)
twsDisconnect(tws)
You can see that the quantity is 100 for all 3 orders instead of 100 for the buy and 50 for each of the sell orders.
Does anyone know how this can be corrected?
As a sanity check, I entered in orders without the parentId and it worked. Here is the code for that:
tws <- twsConnect() #open connection, R automatically pauses until manually accepted on IB.
stock <- twsEquity("AAPL")
parentLongId <- reqIds(tws)
parentLongOrder <- twsOrder(parentLongId, action="BUY", totalQuantity = 100,
orderType = "LMT", lmtPrice = 106,
transmit=TRUE)
placeOrder(tws, stock, parentLongOrder)
childLongProfitId <- reqIds(tws)
childLongProfitOrder <- twsOrder(childLongProfitId, action="SELL", totalQuantity = 50,
orderType = "LMT", lmtPrice = 107,
transmit=TRUE)
placeOrder(tws, stock, childLongProfitOrder)
childLongProfitId2 <- reqIds(tws)
childLongProfitOrder2 <- twsOrder(childLongProfitId2, action="SELL", totalQuantity = 50,
orderType = "LMT", lmtPrice = 108,
transmit=TRUE)
placeOrder(tws, stock, childLongProfitOrder2)
childLongStopId <- reqIds(tws)
childLongStopOrder <- twsOrder(childLongStopId, action="SELL", totalQuantity = 100,
orderType = "STP", auxPrice = 105,
transmit=TRUE, parentId = parentLongId, account=accountNum)
placeOrder(tws, stock, childLongStopOrder)
twsDisconnect(tws)
Though this won't work in practice since it I want the profit and stop orders to cancel the others once hit.
Thank you.