
Did you know you can submit complex orders through the Python API?
Let’s review a sample code snippet from our brand-new Traders’ Academy Python course:
Code Snippet: Bracket Order
from ibapi.client import *
from ibapi.wrapper import *
from ibapi.contract import ComboLeg
from ibapi.tag_value import TagValue
class TestApp(EClient, EWrapper):
def __init__(self):
EClient.__init__(self, self)
def nextValidId(self, orderId: int):
# Order info
mycontract = Contract()
mycontract.symbol = "AAPL"
mycontract.secType = "STK"
mycontract.exchange = "SMART"
mycontract.currency = "USD"
parent = Order()
parent.orderId = orderId
parent.orderType = "LMT"
parent.lmtPrice = 140
parent.action = "BUY"
parent.totalQuantity = 10
parent.transmit = False
profit_taker = Order()
profit_taker.orderId = parent.orderId + 1
profit_taker.parentId = parent.orderId
profit_taker.action = "SELL"
profit_taker.orderType = "LMT"
profit_taker.lmtPrice = 137
profit_taker.totalQuantity = 10
profit_taker.transmit = False
stop_loss = Order()
stop_loss.orderId = parent.orderId + 2
stop_loss.parentId = parent.orderId
stop_loss.orderType = "STP"
stop_loss.auxPrice = 155
stop_loss.action = "SELL"
stop_loss.totalQuantity = 10
stop_loss.transmit = True
self.placeOrder(parent.orderId, mycontract, parent)
self.placeOrder(profit_taker.orderId, mycontract, profit_taker)
self.placeOrder(stop_loss.orderId, mycontract, stop_loss)
def openOrder(self, orderId: OrderId, contract: Contract, order: Order, orderState: OrderState):
print(f"openOrder: {orderId}, contract: {contract}, order: {order}, Maintenance Margin: {orderState.maintMarginChange}")
def orderStatus(self, orderId: OrderId, status: str, filled: float, remaining: float, avgFillPrice: float, permId: int, parentId: int, lastFillPrice: float, clientId: int, whyHeld: str, mktCapPrice: float):
print(f"orderStatus. orderId: {orderId}, status: {status}, filled: {filled}, remaining: {remaining}, avgFillPrice: {avgFillPrice}, permId: {permId}, parentId: {parentId}, lastFillPrice: {lastFillPrice}, clientId: {clientId}, whyHeld: {whyHeld}, mktCapPrice: {mktCapPrice}")
def execDetails(self, reqId: int, contract: Contract, execution: Execution):
print(f"execDetails. reqId: {reqId}, contract: {contract}, execution: {execution}")
app = TestApp()
app.connect("127.0.0.1", 7497, 1000)
app.run()
Code Snippet: Bracket Order from IBKR Traders' Academy
Visit the IBKR Traders’ Academy to see a tutorial on complex orders: https://tradersacademy.online/trading-courses/ibkr-api/python-tws-api
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 LLC, its affiliates, or its employees.
Any trading symbols displayed are for illustrative purposes only and are not intended to portray recommendations.
In accordance with EU regulation: The statements in this document shall not be considered as an objective or independent explanation of the matters. Please note that this document (a) has not been prepared in accordance with legal requirements designed to promote the independence of investment research, and (b) is not subject to any prohibition on dealing ahead of the dissemination or publication of investment research.
Disclosure: API Examples Discussed
Throughout the lesson, please keep in mind that the examples discussed are purely for technical demonstration purposes, and do not constitute trading advice. Also, it is important to remember that placing trades in a paper account is recommended before any live trading.
Disclosure: Displaying Symbols on Video
Any stock, options or futures symbols displayed are for illustrative purposes only and are not intended to portray recommendations.
Disclosure: Order Types / TWS
The order types available through Interactive Brokers LLC’s Trader Workstation are designed to help you limit your loss and/or lock in a profit. Market conditions and other factors may affect execution. In general, orders guarantee a fill or guarantee a price, but not both. In extreme market conditions, an order may either be executed at a different price than anticipated or may not be filled in the marketplace.