Trader Workstation (TWS) is Interactive Brokers’ local desktop application for accessing market data and trading functions through a Python API. The local dependency adds setup complexity, especially for cloud-based systems, but enables programmatic portfolio access and order execution. section 6.3.2 section 11.4.3
A practical integration typically involves:
- Configure and start TWS, then connect with ib_insync. section 6.3.2
- Retrieve positions or market data and normalize them into DataFrame-compatible records. section 6.3.2
- Choose market or limit orders while accounting for bid-ask spread and potentially delayed data without premium subscriptions. section 11.4.3
Listing 6.2 Extracting data from Interactive Brokers
from ib_insync import * #1
util.startLoop() #1
ib = IB() #1
ib.connect() #1
ibr = util.df(ib.positions()) #2
ibr[COL_TICKER] = (ibr.contract.apply
(lambda x: x.symbol)) #2
ibr["exchange"] = (ibr.contract.apply
(lambda x: x.exchange)) #2
ibr["broker"] = "INTERACTIVE_BROKER" #2
IB_balances = (ibr[[COL_TICKER, 'position', 'avgCost',
COL_EXCHANGE, COL_BROKER]].
rename(columns={'position': COL_AMOUNT,
'avgCost': COL_PRICE_INIT}))
The listing demonstrates connecting through ib_insync, extracting positions, and reshaping contract fields into a consistent portfolio table. section 6.3.2
