简体   繁体   中英

How to replicate bracket orders functionality using Interactive Brokers (IB) API (ib_insync) for Python

I have been struggling with getting the bracket order to behave where I can pass an auto expire parameter (goodTillDate) for only the parent. When passing it in the bracket order code, it adds it to the limit and stop as well which defeats the purpose of a bracket order. I also want to be able to identify two limits for each bracket. Anyone have any code which mirrors the parent/child relationship and OCO functions of a bracket order but with individual orders? One parent, and three children (two limits for our target profit takers, and one stop)?

First you submit the parent with the transmit flag as False, then specify parentId for each of the children and submit the last order with transmit as True.

For two limits, you just split the order and submit the legs. Alternatively you can experiment with conditional orders, specifying time.

How would the children stay alive when the parent has expired? Unless you mean partial fills.

A late answer to this question... I had the same problem and found a solution, with a little help, but I still wanna share, because it took me weeks to fix this.

My old code placing a bracket order looked like this:

order = ib.bracketOrder('BUY', amount, limit, takeprofit, stoploss, outsideRth=True, tif='GTC')    
for ord in order:
    ib.placeOrder(contract, ord)

This will place a bracket order with TIF (time in force) set to GTC (good till cancelled) for all 3 orders, the parent and the 2 children.

When I changed it to TIF=GTD and specified a time, this, of course, applied to the whole bracket order. So if it fills in the desired time, the takeprofit and stoploss will disappear after the GTD time expires. Not good.

Then, someone sent me a little help and now this code works for me:

bracket = ib.bracketOrder('BUY', amount, limit, takeprofit,stoploss, outsideRth=True)

gtddelta = (datetime.now() + timedelta(seconds=45)).strftime("%Y%m%d %H:%M:%S")
bracket.parent.tif = 'GTD'
bracket.parent.goodTillDate = gtddelta
    
for order in bracket:
    ib.placeOrder(contract, order)

This sets a 45 second GTD for the parent order. If it does not get filled, the whole bracket order will be cancelled. If it does get filled, the takeprofit and the stoploss order remain, with TIF=GTC.

Please note the changes to the old code. It is important to call the fist variable 'bracket' to be able to define the 'bracket.parent' later (look into the definiton).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM