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()