开云体育

ctrl + shift + ? for shortcuts
© 2025 开云体育

How to attach a stop loss order (Child) to a buy order(Parent)?


 

Hi folk,
?
I am new to the IB_async API... I want to sent a buy order as a parent order and attach a trailing stop order as a child order. The child will only be fired as long the parent order is fired.?
Can anyone tells me if the following code is right?
Thanks a lot.?
?
from ib_async import *
import random

# Connect to Interactive Brokers
ib = IB()
ib.connect('127.0.0.1', 4004, clientId=1)

# Define the Tesla stock contract
tesla_contract = Stock('TSLA', 'SMART', 'USD')

# Generate a unique order ID
parent_order_id = ib.client.getReqId()

# Create the parent buy limit order
parent_order = LimitOrder(
? ? action='BUY',
? ? totalQuantity=100,
? ? lmtPrice=100.00,
? ? tif='GTC', ? ? ? ? ? ? # Good-Til-Canceled
? ? outsideRth=True, ? ? ? # Allow order outside regular trading hours
? ? orderId=parent_order_id,
? ? transmit=False ? ? ? ? # Transmit with child order
)

# Create the child trailing stop sell order
child_order = Order(
? ? action='SELL',
? ? orderType='TRAIL',
? ? totalQuantity=100,
? ? trailingPercent=None, ?# Use None to specify trailing amount in absolute dollars
? ? auxPrice=5.00, ? ? ? ? # Trailing amount in dollars
? ? tif='GTC', ? ? ? ? ? ? # Good-Til-Canceled
? ? outsideRth=True, ? ? ? # Allow order outside regular trading hours
? ? parentId=parent_order_id,
? ? transmit=True ? ? ? ? ?# Transmit the entire order (parent and child)
)

# Place both orders
ib.placeOrder(tesla_contract, parent_order)
ib.placeOrder(tesla_contract, child_order)

# Disconnect from IB
ib.disconnect()

?
?


 

That code should work okay I would just remove the following two lines. Are you having any problems running it?
?
parent_order_id = ib.client.getReqId() # --- ib_async handles this for you
?
ib.placeOrder(tesla_contract, parent_order) ?# --- i used to use these types of orders and you can just submit the lowest child order and all of the parents will be sent in the same batch