How to run the command bracketOrder in ib_insync

1k views Asked by At

In the following code snippet I try to create one action that consists of both Stop loss and Take profit

from ib_insync import *


util.startLoop()
ib = IB()
ib.connect('127.0.0.1', 7497, clientId=1)

contract = Future(symbol='ES', lastTradeDateOrContractMonth='202309', exchange='CME')

order = ib.placeOrder(contract, MarketOrder('BUY', 1))
ib.sleep(1)

ticker = ib.reqMktData(contract, genericTickList='', snapshot=True) # Request real-time market data
ib.sleep(1) # Wait for the ticker to receive data

current_price = ticker.marketPrice()

takeProfitPrice = current_price + 10 # Replace with your desired take profit price
stopLossPrice = current_price - 10 # Replace with your desired stop loss price

takeProfitOrder = LimitOrder('SELL', 1, takeProfitPrice)
stopLossOrder = StopOrder('SELL', 1, stopLossPrice)

ib.sleep(1)

bracket = ib.bracketOrder('SELL', 1, takeProfitPrice+100, stopLossPrice+100, stopLossPrice-200)
bracket[0].parentId = order.order.orderId # Set the parent ID for the main order

bracket[2].parentId = order.order.orderId # Set the parent ID for the stop loss order
bracket[2]. transmit = True # Set transmit to True for the stop loss order

bracket[1].parentId = order.order.orderId # Set the parent ID for the take profit order
bracket[1]. transmit = True # Set transmit to True for the take profit order

ib.placeOrder(contract, bracket) # Place the bracket order

ib.run()
ib.disconnect()

I get the error:

Error 201, reqId 1172: Order rejected - reason: Parent order is being cancelled. Canceled order: Trade(contract=Future(symbol='ES', lastTradeDateOrContractMonth='202309', exchange='CME'),

I would appreciate your help to create the command so that I activate both stop loss and take profit at the same time and the first of them that is executed will cancel the corresponding operation.

Thanks in advance to all the helpers

3

There are 3 answers

1
Hydro Link On

#ib.placeOrder(contract, bracket) # Place the bracket order for order102 in bracket: ib.placeOrder(contract, order102) time.sleep(1) I try this one,It is working, but only see main order be putted and need hand confirm, no other two brackets shows, I am working on it.

2
Django On

I tried to make the trade in several ways and every time I got Cancel I also tried to read and apply the documentation but it was not clear enough

0
Alexis MARTIN On

There a couple of things that do not work in the code:

  1. ib.placeOrder returns a trade, not an order
  2. More significant, it is explained in doc that you must have Transmit flag set to False for the parent and take profit orders and then setting the Transmit flag to True for the Stop order will send the whole bracket order. See https://interactivebrokers.github.io/tws-api/bracket_order.html