Interactive Brokers (IB) Integration
Relevant source files
The following files were used as context for generating this wiki page:
The Interactive Brokers (IB) integration in Backtrader provides a comprehensive interface for live trading and real-time data acquisition. It bridges the Backtrader ecosystem with the IB API, enabling users to execute strategies on live markets using IB's infrastructure. The integration is primarily architected around a "Store" pattern, which centralizes connection management and serves as a factory for broker and data feed components.
Sources: backtrader/stores/ibstore.py:100-110, backtrader/stores/ibstores/ib.py:120-135
The system supports two primary paradigms: a legacy implementation utilizing a singleton IBStore and a modern asynchronous implementation based on the ib_insync library. These components handle the complexities of IB's asynchronous message-based protocol, transforming it into the synchronous-looking event-driven flow expected by Backtrader strategies.
Sources: backtrader/stores/ibstore.py:125-140, backtrader/stores/ibstores/ib.py:35-50
Core Architecture: The Store Pattern
The integration centers on the IBStore class (and its asynchronous counterpart), which manages the connection to Trader Workstation (TWS) or IB Gateway (IBG). It acts as a singleton to ensure a single socket connection is shared across multiple data feeds and the broker.
Component Relationship
The diagram below illustrates how the Store coordinates between the IB API and Backtrader's functional components.
The Store handles connection lifecycle, including automatic reconnection logic and time synchronization with the IB server.
Sources: backtrader/stores/ibstore.py:125-145, backtrader/stores/ibstores/ib.py:135-150, backtrader/stores/ibstores/decoder.py:30-50
Configuration Options
The IB integration can be customized via several parameters passed during initialization:
| Parameter | Type | Default | Description |
|---|---|---|---|
host | String | '127.0.0.1' | IP address where TWS/IBG is running. |
port | Integer | 7496 | Socket port (7496 for live, 7497 for paper trading). |
clientId | Integer | Random | Unique ID for the connection session. |
reconnect | Integer | 3 | Number of retries (-1 for forever). |
timeout | Float | 3.0 | Seconds between connection attempts. |
timeoffset | Boolean | True | Adjust local timestamps to match IB server time. |
Sources: backtrader/stores/ibstore.py:145-160, backtrader/stores/ibstores/ib.py:205-225
Data Feeds and Market Data
The IBData class implements the data feed interface, supporting a wide range of asset classes and data types. It parses string-based contract specifications into IB Contract objects.
Data Flow for Real-Time Bars
The sequence below shows how a data request is initiated and processed.
Supported Contract Patterns
IBData utilizes a hyphen-separated string pattern in the dataname parameter to define contracts:
- Stocks:
STK-AAPL-USD-SMART-ARCA(Type-Symbol-Currency-Exchange-PrimaryExchange) - Futures:
FUT-ES-USD-CME-202309-50(Type-Symbol-Currency-Exchange-Expiry-Multiplier) - Forex:
CASH-EUR-GBP-IDEALPRO - Options:
OPT-GOOG-USD-SMART-20241220-100-180-C(Type-Symbol-Currency-Exchange-Expiry-Multiplier-Strike-Right)
Sources: backtrader/feeds/ibdata.py:55-100, backtrader/feeds/ibdata.py:270-320
Brokerage and Commission Logic
Live execution is managed by the IBBroker (via the Store), while financial calculations are handled by IBCommInfo.
Commission Schemes
The IBCommInfo class provides models for IB's complex tiered or fixed commission structures. It supports specific logic for different asset classes.
| Asset Type | Commission Logic | Derivation |
|---|---|---|
STK | Fixed/Tiered with Fees | Per share (min $1.0), includes FINRA/Transaction fees. |
FUT | Per contract | Typically a fixed rate per side (e.g., $1.37). |
OPT | Premium Dependent | Varies based on option price (e.g., $0.25 to $0.65). |
CASH | Percentage | Based on trade value (min $2.0). |
Sources: backtrader/commissions/ibcommission.py:40-60, backtrader/commissions/ibcommission.py:115-180
Order Execution Flow
When a strategy issues a buy() or sell() command, the Store handles the mapping of Backtrader order types to IB API calls:
- Qualification: The Store ensures the contract is fully qualified (e.g., has a
conId). - Submission:
placeOrderis called with a uniqueorderId. - Tracking: The
DecoderinterceptsorderStatus,openOrder, andexecDetailsmessages to update the order state. - Commission Reporting:
commissionReportmessages are used to finalize the P&L of the trade.
Sources: backtrader/stores/ibstore.py:850-880, backtrader/stores/ibstores/decoder.py:970-1010
Message Decoding and Asynchronous Handling
The Decoder class is responsible for deserializing byte streams from the IB socket into structured Python objects.
Message Handling Logic
The decoder maps numerical Message IDs to specific handler functions.
The decoder supports advanced IB features like tickByTick data and historicalSchedule requests, ensuring that even high-frequency data is correctly typed and dispatched to the relevant feed or broker component.
Sources: backtrader/stores/ibstores/decoder.py:890-930, backtrader/stores/ibstores/decoder.py:1270-1285
Summary
The Interactive Brokers integration provides a robust bridge for transitioning Backtrader strategies from backtesting to live execution. By utilizing a central Store for connection management, standardized contract parsing for data feeds, and specialized commission objects, the system maintains high fidelity between simulated and real-world trading environments. The architecture supports both legacy synchronous operations and modern asynchronous patterns through refined message decoding and dispatching.