ib_insync for Interactive Brokers
A modern, Pythonic wrapper for the Interactive Brokers API. Features async/await support, event-driven programming, and a clean API for live trading and market data.
Prerequisites
- •Interactive Brokers account (live or paper trading)
- •TWS (Trader Workstation) or IB Gateway installed and running
- •API connections enabled in TWS settings (Edit → Global Configuration → API)
Installation
Connection Settings
TWS (Trader Workstation)
- Paper Trading: port 7497
- Live Trading: port 7496
IB Gateway
- Paper Trading: port 4002
- Live Trading: port 4001
Key Features
Async/Await Support
Native async programming support for efficient handling of multiple data streams and orders.
Real-Time Data
Streaming market data, real-time bars, and tick-by-tick data with event callbacks.
Full Trading API
Complete order management: market, limit, stop, bracket orders, and complex order types.
Paper Trading
Test strategies with paper trading account using the same API as live trading.
Code Examples
Connect to Interactive Brokers
Establish connection to TWS or IB Gateway
Get Real-Time Market Data
Stream live prices and historical data
Download Historical Data
Get historical bars for backtesting
Place Market and Limit Orders
Execute trades with different order types
Bracket Orders with SL/TP
Enter position with stop loss and take profit
Monitor and Manage Positions
Track open positions and close trades
Async/Await Pattern
Use async programming for better performance
Event-Driven Trading Bot
React to market events in real-time
Common Use Cases
Best Practices & Common Pitfalls
Always Qualify Contracts
Call ib.qualifyContracts() before using any contract to ensure proper resolution.
Use Paper Trading First
Test all strategies on paper account (port 7497) before switching to live (7496).
Handle Disconnections
Implement reconnection logic and state recovery for production trading systems.
Market Data Limitations
IB has limits on concurrent market data subscriptions. Cancel unused subscriptions.
Order ID Management
Use unique client IDs for each connection to avoid order ID conflicts.
Gateway vs TWS
IB Gateway is more stable for automated trading. TWS requires user interaction.
Additional Resources
Learning Resources
- Notebook examples in GitHub repo
- IB API webinars and tutorials
- Quantopian community discussions
Next Steps
Explore other live trading options or build strategy components: