How to Connect Python to Interactive Brokers (TWS & IB Gateway Setup Guide)
Which Interactive Brokers API port should you use?
Interactive Brokers uses four standard local TCP ports depending on whether you run Trader Workstation (TWS) or headless IB Gateway and whether you are connected to a Paper or Live account.
| Application | Account Mode | Default Port | Recommended Use |
|---|---|---|---|
| IBKR TWS | Paper Trading | 7497 | Visual strategy development, testing & order inspection |
| IBKR TWS | Live Trading | 7496 | Interactive live trading with desktop GUI |
| IB Gateway | Paper Trading | 4002 | Lightweight 24/7 paper execution on desktop or VPS |
| IB Gateway | Live Trading | 4001 | Production unattended live algorithmic trading |
How do you configure TWS or IB Gateway API settings?
Open Global Configuration → API → Settings inside TWS or IB Gateway and verify four core checkboxes before launching Python.
- Check "Enable ActiveX and Socket Clients" so local Python processes can connect.
- Uncheck "Read-Only API" once you are ready to submit paper or live orders.
- Verify "Socket port" matches your IBridgePy settings.py configuration (e.g., 7497 for TWS Paper).
- Add 127.0.0.1 to "Trusted IPs" (or check "Allow connections from localhost only") to avoid manual confirmation popups.
How do you verify your first Python connection to IBKR?
Run a read-only sanity script in IBridgePy that prints your current account balance and fetches recent SPY price bars before enabling automated orders.
def initialize(context):
context.spy = symbol('SPY')
def handle_data(context, data):
print('Portfolio value:', context.portfolio.portfolio_value)
print('SPY last price:', show_real_time_price(context.spy, 'last_price'))
hist = request_historical_data(context.spy, '1 day', '5 D')
print(hist.tail())
end()
Frequently Asked Questions
Why does Interactive Brokers reject my Python connection with Error 502?
Error 502 ("Couldn't connect to TWS") almost always means TWS/IB Gateway is not running, "Enable ActiveX and Socket Clients" is unchecked, or the port number in settings.py does not match the TWS/Gateway API port.
Do I need a market data subscription in IBKR to request prices in Python?
Yes for live real-time US equity or options quotes; IBKR offers low-cost non-professional data bundles and delayed quotes if real-time feeds are not subscribed.
Should I use TWS or IB Gateway for automated trading?
Use TWS while developing and debugging because you can visually inspect orders and fills. Switch to IB Gateway for production because it consumes far less memory and runs cleanly on headless servers or Docker.