Guide
BrokerMarket dataStocksETFsOptionsFuturesForexBondsCrypto API key

Interactive Brokers API guide

Interactive Brokers (IBKR) offers the widest market access of any retail broker API, which is why serious algorithmic traders end up there. The trade-off is architecture: the classic TWS API is a socket protocol to a desktop application you keep running, so an IBKR bot is an infrastructure project, not just an HTTP client.

Last verified · Also known as IBKR, IB, TWS API, IB Gateway

Quick answer

The Interactive Brokers API (TWS API) lets a program trade stocks, options, futures, FX and bonds on 150+ markets, but it talks to a running copy of Trader Workstation or IB Gateway over a local socket, not to a cloud REST endpoint. Paper trading uses port 7497 (TWS) or 4002 (Gateway). Historical data is paced: at most 50 simultaneous requests, with extra limits on small bars.

Interactive Brokers API at a glance

Pricing
API free with account; market data subscriptions extra
Availability
Most countries, through regional IBKR entities
Paper trading
Paper trading account (TWS port 7497, Gateway 4002)
Integration type
Local gateway
In AlgoGP
Design and backtest in AlgoGP, connect the exported code
Main API
TWS API (socket) via Trader Workstation or IB Gateway
Other APIs
Client Portal / IBKR Web API (REST), FIX for institutions
Ports
TWS 7496 live / 7497 paper; Gateway 4001 live / 4002 paper
Languages
Official Python, Java, C++, C#; community ib_async
Historical pacing
Max 50 simultaneous historical requests
Data
Requires market data subscriptions per exchange

What Interactive Brokers offers developers

IBKR is a global broker regulated through local entities (SEC/FINRA and CFTC in the US, FCA in the UK and others). One account can trade stocks, ETFs, options, futures, FX, bonds and more on well over a hundred venues. Developers choose it for breadth, low costs and mature order types, not for ease of setup.

  • Good fit: multi-asset or international strategies, options and futures, anyone who needs one account for everything.
  • Harder fit: a small script that should run unattended with no desktop software, or a serverless function.

TWS API vs Client Portal (Web) API vs FIX

APIHow it connectsWhen to use it
TWS APISocket to TWS or IB Gateway on your machineMost bots; full order types, streaming, history
Client Portal / IBKR Web APIREST + WebSocket through an authenticated gateway sessionWeb apps; lighter automation; sessions expire and need re-auth
FIXFIX session, usually via a CTCI connectionInstitutions and high-volume clients

IB Gateway is a lighter, GUI-less sibling of TWS meant for API use. Either must be logged in for the TWS API to work, and both restart daily, so a production bot needs reconnect logic and a process supervisor.

Market data and historical pacing

Real-time and historical data require market data subscriptions on the account, billed per exchange. Without them you get delayed data or errors. Historical requests are paced: no more than 50 simultaneous requests, and repeated identical or very small-bar requests within short windows trigger pacing violations (error 162).

Python libraries

IBKR ships an official Python client (ibapi) with the TWS API download. Most Python developers use the community ib_async package (the maintained successor of ib_insync), which wraps the callback API in a simpler synchronous/asyncio interface.

from ib_async import IB, Stock, util

ib = IB()
ib.connect("127.0.0.1", 7497, clientId=1)   # paper TWS
contract = Stock("AAPL", "SMART", "USD")
bars = ib.reqHistoricalData(contract, endDateTime="", durationStr="1 Y",
                            barSizeSetting="1 day", whatToShow="TRADES", useRTH=True)
print(util.df(bars).tail())
ib.disconnect()
Daily bars from a paper TWS session with ib_async (pip install ib_async).

Common errors and fixes

502 Couldn’t connect to TWS
TWS/Gateway not running, API not enabled, or the wrong port (7497 paper vs 7496 live).
326 client id already in use
Two programs used the same clientId; give each a unique integer.
162 Historical Market Data Service error
Pacing violation or missing data permission; slow down and check subscriptions.
354 Requested market data is not subscribed
Subscribe to the exchange’s data in Client Portal, or request delayed data.
Daily disconnect
TWS and Gateway restart once a day; schedule the restart and reconnect automatically.

Build an Interactive Brokers strategy with AlgoGP

AlgoGP does not connect to Interactive Brokers natively yet. Interactive Brokers connects through a local gateway, socket, FIX or Protobuf stack rather than plain HTTPS, so it runs as a separate process next to your strategy.

  1. 1

    Design and backtest in AlgoGP

    Describe the strategy to the copilot and backtest it on years of normalized history. The result does not depend on any vendor.

  2. 2

    Export the Python project

    Every project exports strategy.py, market_data.py, brokers.py and live.py. The strategy only sees bars, cash, positions and orders, never a vendor’s wire format.

  3. 3

    Plug in Interactive Brokers

    Implement the four adapter methods (account, positions, submit_market_order and a candle fetcher) with Interactive Brokers’s SDK, or keep a built-in platform for paper trading and add Interactive Brokers when you go live.

Built-in brokers for the same markets: Alpaca, Binance, Kraken, Bybit.

Interactive Brokers API: frequently asked questions

Does Interactive Brokers have a REST API?

Yes: the Client Portal (IBKR Web) API is REST plus WebSocket, but it still runs through an authenticated session that must be refreshed. Most bots use the socket-based TWS API through IB Gateway.

Is the IBKR API free?

API access is free with an account. Market data subscriptions are charged per exchange, and normal commissions apply.

Which port does the IBKR paper account use?

7497 for TWS and 4002 for IB Gateway. Live accounts use 7496 and 4001.

Can I run the IBKR API without TWS?

Not the TWS API: either TWS or IB Gateway must be running and logged in. IB Gateway is the headless-friendly option.

What is the best Python library for Interactive Brokers?

ib_async, the maintained successor of ib_insync, is the most popular. The official ibapi package is lower level and callback based.

How do I avoid IBKR pacing violations?

Keep under 50 simultaneous historical requests, avoid repeating identical requests within 15 seconds, and request larger bars or longer durations per call.

Design and backtest your Interactive Brokers strategy first

AlgoGP turns an idea into Python and tests it on years of history before you connect it to Interactive Brokers. The exported code keeps the broker behind four small adapter methods.

  • AI copilot writes and revises the rules
  • Backtests with realistic costs
  • Exported Python ready to wire to Interactive Brokers

Free plan, no card required.

Interactive Brokers alternatives

Independent guide. AlgoGP is not affiliated with Interactive Brokers. Limits, prices and availability change; confirm them in the official documentation. Nothing here is investment advice.