How to Code a Bracket Order in Python

Articles From: Interactive Brokers
Website: Interactive Brokers

IBKR API GitHub Guide offers practical examples in Python on how to code order types and algos.

Today we review the Python syntax for a Bracket Order. This order type is intended to help limit your loss and attempts to “lock in” a profit by “bracketing” an order with two opposite-side orders. For the mechanics behind this order, see our Order Type page and short video here: https://www.interactivebrokers.com/en/index.php?f=583

Let’s try to code this in Python – take a look at the script below as referenced from our GitHub Guide. It is important to note that the Bracket order is composed of three orders, so traders need to pay attention if one or two of the orders get filled before the entire bracket is sent. To avoid this, consider using the IBApi.Order.Transmit flag. Read how here: http://interactivebrokers.github.io/tws-api/classIBApi_1_1Order.html#aaa1c4f31b9580ee0715edcd78a51cbec

@staticmethod
def BracketOrder(parentOrderId:int, action:str, quantity:float,
limitPrice:float, takeProfitLimitPrice:float,
stopLossPrice:float):

#This will be our main or “parent” order
parent = Order()
parent.orderId = parentOrderId
parent.action = action
parent.orderType = “LMT”
parent.totalQuantity = quantity
parent.lmtPrice = limitPrice
#The parent and children orders will need this attribute set to False to prevent accidental executions.
#The LAST CHILD will have it set to True,
parent.transmit = False

takeProfit = Order()
takeProfit.orderId = parent.orderId + 1
takeProfit.action = “SELL” if action == “BUY” else “BUY”
takeProfit.orderType = “LMT”
takeProfit.totalQuantity = quantity
takeProfit.lmtPrice = takeProfitLimitPrice
takeProfit.parentId = parentOrderId
takeProfit.transmit = False

stopLoss = Order()
stopLoss.orderId = parent.orderId + 2
stopLoss.action = “SELL” if action == “BUY” else “BUY”
stopLoss.orderType = “STP”
#Stop trigger price
stopLoss.auxPrice = stopLossPrice
stopLoss.totalQuantity = quantity
stopLoss.parentId = parentOrderId
#In this case, the low side order will be the last child being sent. Therefore, it needs to set this attribute to True
#to activate all its predecessors
stopLoss.transmit = True

bracketOrder = [parent, takeProfit, stopLoss]
return bracketOrder

bracket = OrderSamples.BracketOrder(self.nextOrderId(), “BUY”, 100, 30, 40, 20)
for o in bracket:
self.placeOrder(o.orderId, ContractSamples.EuropeanStock(), o)
self.nextOrderId() # need to advance this we’ll skip one extra oid, it’s fine

Stay tuned for more articles featuring IBKR order types. See the previous installment in this series: How to Code a Forex Order in Python

Disclosure: Interactive Brokers

The analysis in this material is provided for information only and is not and should not be construed as an offer to sell or the solicitation of an offer to buy any security. To the extent that this material discusses general market activity, industry or sector trends or other broad-based economic or political conditions, it should not be construed as research or investment advice. To the extent that it includes references to specific securities, commodities, currencies, or other instruments, those references do not constitute a recommendation by IBKR to buy, sell or hold such investments. This material does not and is not intended to take into account the particular financial conditions, investment objectives or requirements of individual customers. Before acting on this material, you should consider whether it is suitable for your particular circumstances and, as necessary, seek professional advice.

The views and opinions expressed herein are those of the author and do not necessarily reflect the views of Interactive Brokers, its affiliates, or its employees.