Overview
Interactive Brokers is one of the most widely used brokerage platforms among professional traders, systematic trading firms, hedge funds, and individual algorithmic traders who require institutional-grade execution, broad instrument coverage, and programmatic trading access. IB offers trading across equities, options, futures, forex, bonds, and cryptocurrencies through a unified account, with access to over 150 markets in 33 countries. For trading systems that need a credible, well-capitalised broker with a mature API and broad instrument coverage, Interactive Brokers is frequently the execution venue of choice.
The Interactive Brokers API ecosystem offers two primary programmatic interfaces: the TWS API (Trader Workstation API), which connects through a locally running TWS or IB Gateway application, and the Client Portal API (now called the IBKR REST API or Web API), which provides REST-based access without requiring a locally running TWS instance. A third option — the FIX CTCI protocol — is available for institutional clients requiring FIX connectivity. Each interface has different characteristics, different capabilities, and different appropriate use cases.
The TWS API is the most mature and most capable interface — providing the full depth of IB's functionality including real-time streaming market data, order management with all IB order types, account data, position tracking, historical data, scanner results, and options chains. The TWS API uses a persistent socket connection to the locally running TWS or IB Gateway, with a proprietary binary protocol and an event-driven callback architecture. Correct TWS API integration requires understanding the connection lifecycle, the request-response correlation mechanism, the order state machine, and the specific error handling patterns that IB's execution model requires.
We build Interactive Brokers integrations for systematic trading firms, algorithmic traders, portfolio management systems, and risk monitoring applications that need to connect to IB's execution and data infrastructure — covering TWS API integration for full-featured programmatic trading, IB Gateway deployment for server-side automated trading, and the order management, market data, and account monitoring implementations that production IB trading systems require.
What Interactive Brokers Integration Covers
TWS API connection management. The TWS API connects through a persistent TCP socket to a locally running TWS or IB Gateway instance. The connection management that the trading system must implement correctly for reliable operation.
Connection establishment: the EClient.connect() call that establishes the TCP connection to TWS/IB Gateway on the configured host and port (default 7497 for TWS paper trading, 7496 for live TWS, 4001 for live IB Gateway, 4002 for paper IB Gateway). The clientId parameter that identifies the connecting application — each connected client must have a unique client ID. The EReader thread that runs the message processing loop, reading incoming messages from the socket and dispatching them to the appropriate callback methods. The connection established confirmation through the connectAck() and nextValidId() callbacks.
Disconnection handling: the error() callback with error code 1100 (connectivity to IB server lost) and 1102 (connectivity to IB server restored) that indicate connection disruptions. The reconnection logic that re-establishes the connection after a disconnection, re-subscribes to market data, and reconciles position and order state after reconnection.
IB Gateway for server-side deployment: IB Gateway is a headless version of TWS designed for automated systems that do not need the full TWS charting and interface. IB Gateway runs as a Java process, configured to auto-restart on login, and does not require a GUI environment — making it suitable for server and VPS deployment. The IB Gateway configuration for auto-reconnect, session management to handle IB's daily server restart at specific times, and the keep-alive settings that maintain the connection during low-activity periods.
Daily server restart: IB performs a daily server restart (typically around 23:45 EST) that disconnects all TWS/Gateway connections. The reconnection logic that handles the daily restart, waits for the server to come back up, reconnects, and resumes operation — critical for automated systems that must operate continuously.
Order placement and management. The TWS API order management covering the full range of IB order types and execution algorithms.
Order submission: the EClient.placeOrder(orderId, contract, order) method for placing orders. The orderId — an integer that must be unique and greater than the nextValidOrderId returned by IB at connection time. The Contract object specifying the instrument — the symbol, the security type (STK, OPT, FUT, FOREX, CFD, FUND, BOND, CRYPTO), the exchange, the currency, and the additional fields for options (strike, expiry, right) and futures (expiry). The Order object specifying the order parameters — action (BUY, SELL), total quantity, order type, price parameters.
Order types: MKT for market orders, LMT for limit orders, STP for stop orders, STP LMT for stop-limit orders, MOC for market-on-close, LOC for limit-on-close, MIT for market-if-touched, LIT for limit-if-touched, TRAIL for trailing stop, TRAIL LIMIT for trailing stop limit. IB-specific algorithmic order types: MIDPRICE for midpoint execution, VWAP for VWAP execution, TWAP for TWAP execution, IBKRATS for IB's adaptive order routing.
Order state callbacks: the orderStatus() callback that fires when order state changes — the status string (PreSubmitted, Submitted, Filled, Inactive, Cancelled), the filled quantity, the remaining quantity, the average fill price, and the permId (IB's permanent order identifier that persists across connections). The openOrder() callback that provides the full order and execution details. The execDetails() callback that fires when an execution occurs — the Execution object with the execution ID, the order ID, the side, the shares, the price, the exchange, and the execution time.
Order cancellation: the EClient.cancelOrder(orderId) method for cancelling a specific open order by order ID. The EClient.reqGlobalCancel() method for cancelling all open orders simultaneously.
Market data — real-time streaming. TWS API real-time market data subscriptions for live price data.
Ticker subscriptions: the EClient.reqMktData(reqId, contract, genericTickList, snapshot, regulatorySnapshot, mktDataOptions) method for subscribing to real-time tick data. The tickPrice(), tickSize(), tickString(), tickGeneric(), and tickEFP() callbacks that deliver the subscribed data — bid price, ask price, last price, bid size, ask size, last size, volume, and the additional tick types available for the subscribed instrument.
Tick types: the price tick types — BID (1), ASK (2), LAST (4), HIGH (6), LOW (7), CLOSE (9), OPEN (14) — and the size tick types — BID_SIZE (0), ASK_SIZE (3), LAST_SIZE (5), VOLUME (8). The tick type integers that identify which data point each callback delivers.
Market data lines: IB limits the number of simultaneous market data subscriptions based on the account's market data subscription level. The market data line count management that tracks active subscriptions and stays within the permitted limit. The snapshot request (snapshot=true) that requests a one-time price snapshot rather than a continuous stream for instruments where continuous streaming is not required.
Real-time bars: the EClient.reqRealTimeBars() method for subscribing to 5-second OHLCV bars — the real-time bar stream that updates every 5 seconds with the OHLCV data for the current bar period.
Market data — historical. Historical price data for strategy backtesting, indicator initialisation, and analytics.
Historical data request: the EClient.reqHistoricalData(reqId, contract, endDateTime, durationStr, barSizeSetting, whatToShow, useRTH, formatDate, keepUpToDate, chartOptions) method. The durationStr that specifies the historical data period ("1 D", "1 W", "1 M", "1 Y") and the barSizeSetting that specifies the bar size ("1 secs", "5 secs", "10 secs", "15 secs", "30 secs", "1 min", "2 mins", "3 mins", "5 mins", "10 mins", "15 mins", "20 mins", "30 mins", "1 hour", "2 hours", "3 hours", "4 hours", "8 hours", "1 day", "1 week", "1 month"). The historicalData() callback that delivers each bar with the date, open, high, low, close, volume, and WAP (weighted average price).
Historical data pacing: IB enforces pacing restrictions on historical data requests — a maximum of 60 requests per 10 minutes per account for historical data, and a maximum of 6 identical requests per 10 minutes. The pacing management that queues historical data requests and spaces them to avoid pacing violations.
Account and portfolio data. Account balance, position, and P&L data from the TWS API.
Account summary: the EClient.reqAccountSummary(reqId, group, tags) method for requesting account summary data across one or all accounts. The accountSummary() callback that delivers account values — NetLiquidation, TotalCashValue, GrossPositionValue, MaintMarginReq, AvailableFunds, BuyingPower, UnrealizedPnL, RealizedPnL. The ALL group for all accounts in the IB account structure.
Account updates: the EClient.reqAccountUpdates(subscribe, acctCode) method for subscribing to real-time account update events. The updateAccountValue() and updatePortfolioValue() callbacks that deliver live position and account data as they change.
Positions: the EClient.reqPositions() method for requesting all current positions across all accounts. The position() callback that delivers each position — the account, the contract, the position size, and the average cost.
Portfolio data: the updatePortfolioValue() callback in account updates that delivers the full position detail including the market price, the market value, the unrealised and realised P&L, and the average cost.
P&L subscription: the EClient.reqPnL(reqId, account, modelCode) and EClient.reqPnLSingle(reqId, account, modelCode, conid) methods for subscribing to real-time P&L data for the account or for a specific position. The pnl() and pnlSingle() callbacks that deliver daily P&L and unrealised P&L updates.
Contract details and instrument search. Resolving instrument identifiers and retrieving instrument specifications.
Contract details: the EClient.reqContractDetails(reqId, contract) method for retrieving the full specification of an instrument — the conid (IB's contract identifier), the trading hours, the minimum tick size, the multiplier for futures and options, the exchange listing, and the expiry dates for derivatives. The contractDetails() callback that returns the ContractDetails object with the complete instrument specification.
Symbol search: the EClient.reqMatchingSymbols(reqId, pattern) method for searching for instruments by name or symbol pattern. The symbolSamples() callback that returns matching contracts.
Options chains: the EClient.reqSecDefOptParams(reqId, underlyingSymbol, futFopExchange, underlyingSecType, underlyingConId) method for retrieving the available options strikes and expiries for an underlying. The securityDefinitionOptionParameter() callback that returns the available expiries and strikes for the options chain.
ibapi Python client and ib_insync. The Python integration libraries for TWS API access.
ibapi: the official IB Python client that provides the base EClient and EWrapper classes for TWS API connectivity. The EClient for sending requests and the EWrapper for receiving callbacks — the architecture that requires subclassing EWrapper to implement the callback methods the application uses.
ib_insync: the third-party asyncio-based Python wrapper around ibapi that significantly improves the development experience — the IB class with synchronous-style methods (ib.placeOrder(), ib.reqHistoricalData(), ib.positions()) that hide the callback complexity of the native ibapi. The ib.sleep() and event loop integration that makes asyncio-based IB API programs readable and maintainable. ib_insync is the recommended approach for Python TWS API development.
.NET API (IBApi). The official IB .NET client for C# TWS API integration — the EClient and EWrapper classes in the IBApi namespace, with the same architecture as the Python ibapi but for C# applications.
Client Portal API (IBKR Web API). The REST-based API alternative to the TWS API for applications that cannot run TWS or IB Gateway locally.
Authentication: the Client Portal API requires authentication through IB's OAuth-based authentication flow or through the IBKR API gateway. The session management that maintains the authenticated session and handles re-authentication.
Order and portfolio endpoints: the REST endpoints for placing orders (POST /v1/api/iserver/account/{accountId}/orders), retrieving positions (GET /v1/api/portfolio/{accountId}/positions), retrieving account summary data, and the other operations that the TWS API supports through the REST interface.
Limitations versus TWS API: the Client Portal API has limitations compared to the full TWS API — fewer order types, less real-time data granularity, and different rate limits. For production automated trading systems, the TWS API via IB Gateway is generally preferred.
Financial Advisor Account Structure
For trading firms and portfolio managers using IB's Financial Advisor (FA) account structure — a master account that manages multiple sub-accounts.
FA account management: the EClient.requestFA(faDataType) method for retrieving the FA account groups, allocation profiles, and account aliases configuration. The receiveFA() callback that returns the FA configuration XML.
Multi-account order placement: placing orders in FA accounts with allocation methods — by percentage, by equity, by quantity, or by custom profile. The Order.faGroup, Order.faMethod, Order.faPercentage, and Order.faProfile fields that configure the FA allocation for each order.
Sub-account position aggregation: aggregating positions across all sub-accounts for the aggregate portfolio view — the combined position management that gives a unified view of exposure across all managed accounts.
Technologies Used
- Python / ib_insync — primary IB TWS API integration for strategy development, signal generation, and portfolio management in Python
- C# / IBApi — IB TWS API integration for .NET-based trading systems and portfolio management applications
- Rust — high-performance order management and market data processing with custom TWS API client implementation for latency-critical applications
- Java — IB Gateway process management and Java-based TWS API integration
- IB Gateway — headless TWS deployment for server-side automated trading
- REST / HTTP — IBKR Client Portal API for non-Gateway deployments
- SQL (PostgreSQL / MySQL) — trade history, position records, account data, order records
- Redis — real-time position state, order tracking, market data caching
- Docker — containerised trading system deployment alongside IB Gateway
- GitHub Actions — CI/CD pipeline for trading system deployment
IB Gateway Deployment Architecture
For production automated trading systems using the TWS API, IB Gateway is the appropriate deployment model — the headless Java process that provides TWS API connectivity without requiring a GUI environment.
IB Gateway configuration: the jts.ini configuration file that sets the login credentials, the auto-reconnect settings, the session management for the daily restart, and the paper/live account selection. The startup script that launches IB Gateway with the correct Java arguments and configuration.
Docker deployment: the IB Gateway Docker image (the community-maintained ghcr.io/extrange/ibkr-docker or similar) that packages IB Gateway for container deployment. The Docker container configuration with the port mapping for the TWS API connection and the volume mount for the IB Gateway configuration and data.
Session management: IB Gateway performs a daily server-initiated disconnection at approximately 23:45 EST. The session management that detects the disconnection, waits for the server restart (typically 5–15 minutes), reconnects, and resumes operation. The order and position state reconciliation after reconnection that ensures the trading system's view of the account matches IB's actual account state.
IB as Part of a Multi-Broker Architecture
For trading systems that route orders to multiple brokers — IB alongside cTrader, Binance, or other venue — the IB connector is one component of the multi-broker execution architecture. The normalisation layer that translates the internal order model to IB's Contract and Order objects, maps IB's callback events to the internal trade event model, and handles IB-specific error codes in a way that the strategy layer does not need to be aware of.
Production IB Integration
Interactive Brokers TWS API integrations built to production standards — correct connection lifecycle management with daily restart handling, accurate order state tracking through the full order state machine, real-time position and P&L monitoring, historical data pacing compliance, and the operational monitoring that surfaces connectivity and execution issues before they affect trading operations.