ib_insync – get contract from order object

i would like to get the contract ID (conID) from an order object.

I am using this code

from ib_insync import IB, util

# Start the asyncio event loop
util.startLoop()

# Create an IB instance
ib = IB()

# Connect to TWS
ib.connect("127.0.0.1", 7491, clientId=4)

# Fetch orders
orders = ib.orders()
openTrades = ib.openTrades()

# Disconnect from TWS
ib.disconnect()

print(orders)
print(openTrades)

the returned order objects to not contain the contract ID (conID). How to derive them?

from ib_insync import IB, util

# Start the asyncio event loop
util.startLoop()

# Create an IB instance
ib = IB()

# Connect to TWS
ib.connect("127.0.0.1", 7491, clientId=4)

# Fetch orders
orders = ib.orders()
openTrades = ib.openTrades()

# Iterate over open trades to access contract IDs
for trade in openTrades:
    # Each trade has a contract associated with it
    contract = trade.contract
    # Print the contract ID
    print(f"Contract ID (conID) for trade: {contract.conId}")

# Disconnect from TWS
ib.disconnect()

Leave a Comment