How to Configure the Interactive Brokers Adapter in NautilusTrader: A Complete Setup Guide
Configure the Interactive Brokers adapter by installing the ib and docker extras, instantiating DockerizedIBGatewayConfig or pointing to an existing TWS/IB Gateway instance, and passing InteractiveBrokersDataClientConfig and InteractiveBrokersExecClientConfig to a TradingNode.
The Interactive Brokers (IB) adapter in nautechsystems/nautilus_trader provides a production-grade bridge to IB’s Trader Workstation (TWS) or IB Gateway via the ibapi library. This guide walks through every configuration class, connection method, and practical code example needed to stream real-time market data and execute orders.
Installation and Prerequisites
Install the adapter with the required extras to pull the repackaged ibapi wheels and the Python Docker SDK:
uv pip install "nautilus_trader[ib,docker]"
The ib extra is mandatory for the protocol implementation. The docker extra is required only if you plan to use the DockerizedIBGateway component for containerized deployments.
Core Architecture and Configuration Classes
The adapter consists of five primary components, each with a dedicated configuration class defined in nautilus_trader/adapters/interactive_brokers/config.py:
| Component | Configuration Class | Purpose |
|---|---|---|
| Gateway | DockerizedIBGatewayConfig |
Manages a containerized IB Gateway instance (optional) |
| Instrument Provider | InteractiveBrokersInstrumentProviderConfig |
Loads contract details, handles symbology, and caches instruments |
| Data Client | InteractiveBrokersDataClientConfig |
Streams real-time quotes, trades, bars, and depth; requests historical data |
| Execution Client | InteractiveBrokersExecClientConfig |
Routes orders, handles modifications, and receives account/position updates |
All configuration classes inherit from NautilusConfig (frozen dataclasses), making them immutable and hashable for safe caching and serialization.
Gateway Configuration: Dockerized vs. Existing Instance
Choose between managing a Docker container automatically or connecting to an already-running TWS or IB Gateway.
Option 1: Dockerized IB Gateway (Recommended for Automation)
Use DockerizedIBGatewayConfig to spin up a headless IB Gateway container automatically. This is ideal for cloud deployments and CI pipelines.
from nautilus_trader.adapters.interactive_brokers.config import DockerizedIBGatewayConfig
gateway_cfg = DockerizedIBGatewayConfig(
username="my_user",
password="my_pass",
trading_mode="paper", # or "live"
read_only_api=False, # set True for data-only mode
timeout=300, # seconds to wait for login
container_image="ghcr.io/gnzsnz/ib-gateway:stable",
vnc_port=None, # set to expose VNC for debugging
)
Security Note: Never commit credentials to version control. The adapter also reads TWS_USERNAME, TWS_PASSWORD, and TWS_ACCOUNT from environment variables if the config fields are None.
Option 2: Existing TWS or IB Gateway
If you already run TWS or IB Gateway locally or on a remote host, omit the dockerized_gateway parameter and specify the host and port directly in the client configs.
# No gateway config needed
# Use ibg_host="127.0.0.1", ibg_port=7497 for local TWS paper trading
Instrument Provider Configuration
The InteractiveBrokersInstrumentProvider handles contract resolution and caching. Configure it via InteractiveBrokersInstrumentProviderConfig in nautilus_trader/adapters/interactive_brokers/providers.py.
from nautilus_trader.adapters.interactive_brokers.config import (
InteractiveBrokersInstrumentProviderConfig,
SymbologyMethod,
)
provider_cfg = InteractiveBrokersInstrumentProviderConfig(
symbology_method=SymbologyMethod.IB_SIMPLIFIED, # or IB_RAW
load_ids=frozenset([
"EUR/USD.IDEALPRO",
"SPY.ARCA",
"ESM4.CME",
]),
load_contracts=None, # Use IBContract objects for complex instruments
build_options_chain=False,
build_futures_chain=False,
convert_exchange_to_mic_venue=True,
cache_validity_days=1,
)
Symbology Methods:
IB_SIMPLIFIED(default): Human-readable IDs likeEUR/USD.IDEALPROorAAPL.SMART.IB_RAW: Exact contract strings required by IB’s API (e.g.,AAPL=STK.SMART).
Data Client Configuration
The InteractiveBrokersDataClient in nautilus_trader/adapters/interactive_brokers/data.py streams market data. Configure it with InteractiveBrokersDataClientConfig.
from nautilus_trader.adapters.interactive_brokers.config import InteractiveBrokersDataClientConfig
from nautilus_trader.adapters.interactive_brokers.common import IBMarketDataTypeEnum
data_cfg = InteractiveBrokersDataClientConfig(
ibg_host="127.0.0.1",
ibg_port=7497, # 7497 for TWS paper, 7496 for TWS live
ibg_client_id=1,
use_regular_trading_hours=True,
market_data_type=IBMarketDataTypeEnum.REALTIME, # or DELAYED_FROZEN for free data
ignore_quote_tick_size_updates=True,
dockerized_gateway=gateway_cfg, # Omit if using existing TWS
instrument_provider=provider_cfg,
)
Key Parameters:
market_data_type: Set toREALTIMEfor live subscriptions orDELAYED_FROZENfor free delayed data if you lack market data subscriptions.ignore_quote_tick_size_updates: Set toTrueto reduce noise from size-only updates on the quote book.
Execution Client Configuration
The InteractiveBrokersExecutionClient in nautilus_trader/adapters/interactive_brokers/execution.py handles order routing. Configure it with InteractiveBrokersExecClientConfig.
from nautilus_trader.adapters.interactive_brokers.config import InteractiveBrokersExecClientConfig
exec_cfg = InteractiveBrokersExecClientConfig(
ibg_host="127.0.0.1",
ibg_port=7497,
ibg_client_id=1,
account_id="DU123456", # Your IB paper account, or None to use TWS_ACCOUNT env var
dockerized_gateway=gateway_cfg,
instrument_provider=provider_cfg,
fetch_all_open_orders=True,
track_option_exercise_from_position_update=False,
routing=RoutingConfig(default=True),
)
Execution-Specific Settings:
account_id: Specify your IB account number (e.g.,DU123456for paper) or leave asNoneto read from theTWS_ACCOUNTenvironment variable.fetch_all_open_orders: Set toTrueto synchronize all pre-existing open orders from IB upon connection.
Complete Trading Node Example
Here is a minimal, runnable configuration that assembles all components into a TradingNode:
from nautilus_trader.adapters.interactive_brokers.config import (
DockerizedIBGatewayConfig,
InteractiveBrokersInstrumentProviderConfig,
InteractiveBrokersDataClientConfig,
InteractiveBrokersExecClientConfig,
SymbologyMethod,
)
from nautilus_trader.adapters.interactive_brokers.common import IBMarketDataTypeEnum
from nautilus_trader.config import RoutingConfig
from nautilus_trader.trading.node import TradingNode
# 1. Gateway configuration (Dockerized)
gateway_cfg = DockerizedIBGatewayConfig(
username="my_user",
password="my_pass",
trading_mode="paper",
read_only_api=False,
timeout=300,
)
# 2. Instrument provider
provider_cfg = InteractiveBrokersInstrumentProviderConfig(
symbology_method=SymbologyMethod.IB_SIMPLIFIED,
load_ids=frozenset([
"EUR/USD.IDEALPRO",
"SPY.ARCA",
"ESM4.CME",
]),
)
# 3. Data client
data_cfg = InteractiveBrokersDataClientConfig(
ibg_host="127.0.0.1",
ibg_port=7497,
ibg_client_id=1,
market_data_type=IBMarketDataTypeEnum.REALTIME,
dockerized_gateway=gateway_cfg,
instrument_provider=provider_cfg,
)
# 4. Execution client
exec_cfg = InteractiveBrokersExecClientConfig(
ibg_host="127.0.0.1",
ibg_port=7497,
ibg_client_id=1,
account_id="DU123456",
dockerized_gateway=gateway_cfg,
instrument_provider=provider_cfg,
routing=RoutingConfig(default=True),
)
# 5. Assemble and start the node
node = TradingNode(
data_clients=[data_cfg],
exec_clients=[exec_cfg],
)
# This launches the Docker container (if configured), connects to IB,
# loads instruments, and begins streaming data.
await node.start()
Common Pitfalls and Troubleshooting
| Symptom | Likely Cause | Solution |
|---|---|---|
ConnectionError: Unable to connect to 127.0.0.1:7497 |
TWS or IB Gateway is not running, or the port is incorrect. | Verify the application is launched. Use port 7497 for TWS paper trading, 7496 for live, 4002 for IB Gateway paper, or 4001 for live. |
Pacing violation warnings |
Exceeded IB’s rate limits for historical data requests or order modifications. | Add await asyncio.sleep(0.2) between batched requests, or increase the request_timeout parameter in your configuration. |
| Missing market data for subscribed instruments | Account lacks the required market data subscription. | Change market_data_type to IBMarketDataTypeEnum.DELAYED_FROZEN for free delayed data, or purchase the appropriate market data subscription from IB. |
Instrument not found errors when using load_ids |
Mismatch between symbology method and ID format. | Ensure symbology_method in InteractiveBrokersInstrumentProviderConfig matches your IDs. Use IB_SIMPLIFIED for human-readable IDs like AAPL.SMART, or IB_RAW for exact contract strings. |
| Docker container fails to start or exits immediately | Incorrect image tag, missing Docker daemon, or invalid credentials. | Ensure Docker is running. Use the default image ghcr.io/gnzsnz/ib-gateway:stable. Check that username and password are valid IB credentials. |
Summary
- Install the adapter using
uv pip install "nautilus_trader[ib,docker]"to include theibapilibrary and Docker SDK. - Choose your connection method: Use
DockerizedIBGatewayConfigfor automated, headless deployments, or connect directly to an existing TWS/IB Gateway instance by specifyingibg_hostandibg_port. - Configure the instrument provider with
InteractiveBrokersInstrumentProviderConfigto handle symbology (IB_SIMPLIFIEDvsIB_RAW) and preload specific instruments viaload_idsorload_contracts. - Set up data and execution clients using
InteractiveBrokersDataClientConfigandInteractiveBrokersExecClientConfig, ensuringaccount_idandmarket_data_typematch your IB account settings. - Assemble the TradingNode by passing the configured clients to
TradingNode(data_clients=[...], exec_clients=[...])and awaitnode.start()to establish the connection.
Frequently Asked Questions
How do I switch between paper trading and live trading with the Interactive Brokers adapter?
Change the trading_mode parameter in DockerizedIBGatewayConfig to "paper" or "live", and adjust the port numbers accordingly. For paper trading, use port 7497 (TWS) or 4002 (IB Gateway); for live trading, use 7496 (TWS) or 4001 (IB Gateway). Ensure your account_id matches the paper or live account number (e.g., DU123456 for paper).
What is the difference between IB_SIMPLIFIED and IB_RAW symbology methods?
IB_SIMPLIFIED (the default) generates human-readable instrument IDs such as EUR/USD.IDEALPRO or AAPL.SMART, making it easier to reference instruments in your strategy code. IB_RAW uses exact contract strings as required by IB’s API (e.g., AAPL=STK.SMART), which is useful when you need precise control over contract specifications or when dealing with complex instruments like options with specific expiries.
How do I handle rate limits and pacing violations when requesting historical data?
Interactive Brokers enforces strict rate limits on historical data requests. To avoid Pacing violation errors, insert a small delay between batched requests using await asyncio.sleep(0.2) or longer. You can also increase the request_timeout parameter in your data client configuration to allow more time for responses. For initial backfills, consider requesting data in smaller chunks (e.g., one day at a time) rather than large date ranges in a single call.
Can I use the Interactive Brokers adapter without Docker?
Yes, you can connect to an existing TWS or IB Gateway instance running on your local machine or a remote server. Simply omit the dockerized_gateway parameter from your data and execution client configurations, and instead set ibg_host and ibg_port to point to your running instance (e.g., ibg_host="127.0.0.1", ibg_port=7497 for local TWS paper trading). This method is common for desktop trading setups where you prefer to manage the IB application manually.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →