ib_async
Versions and branches
In December 2026, IBKR will require TWS / IB Gateway 10.51 or later for
API connections. ib_async 3.0, on the main branch, is the version built
for that, and the only supported version. ib_async 2.2.0, on the
legacy-2.x branch, is the last 2.x release; that branch gets no further
changes. All performance, feature and usability work goes into 3.0.
2.2.0 (legacy-2.x, tag v2.2.0) |
3.0 (main) |
|
|---|---|---|
| Released | 2026-12-02 | 2026-12-02 |
| Wire protocol | IBKR's text protocol | IBKR's protobuf protocol |
| API server version | Up to 178 | 226 to 228 (TWS / IB Gateway 10.51 or later; 228 is 10.53) |
| Python | 3.11+ | 3.11 to 3.15, PyPy 3.11 and 3.12 |
| After December 2026 | Legacy, unsupported | Supported |
Three version numbers are involved, and they are often confused:
- Your TWS / IB Gateway version, such as 10.51. IBKR sets the minimum.
- The API server version, such as 178, 226 or 228. The client and the gateway agree on it when they connect: the highest version both support. ib_async logs it on connect.
- The ib_async version, such as 2.2.0 or 3.0.0. It decides the highest API server version the client can use.
Upgrading from 2.x to 3.0 changes some APIs. See the changelog and the upgrade guide.
Use ib_async from a checkout
For a live trading system, we recommend depending on a local checkout of ib_async instead of the PyPI package. When you hit a problem, you can fix it right next to your own code and keep going, instead of waiting days to months for a release. Please send the fix back as a pull request too.
git clone https://github.com/ib-api-reloaded/ib_async.git
cd ib_async
make protos # generates the protobuf bindings; needs uv
cd ../your-project
uv add --editable ../ib_async # or: pip install -e ../ib_async
The protobuf bindings are generated, not committed. Run make protos
again after pulling a change that updates the TWS API version pinned in
pyproject.toml.
Introduction
ib_async is a Python library that provides a clean, modern interface to Interactive Brokers' Trader Workstation (TWS) and IB Gateway. It handles the complexities of the IBKR API so you can focus on building trading applications, research tools, and market data analysis.
What You Can Build
- Market Data Applications: Stream live quotes, historical data, and market depth
- Trading Systems: Place, modify, and monitor orders programmatically
- Portfolio Tools: Track positions, account balances, and P&L in real-time
- Research Platforms: Analyze contract details, option chains, and historical data
- Risk Management: Monitor exposures and implement automated controls
Key Features
- Simple and Intuitive: Write straightforward Python code without dealing with callback complexity
- Automatic Synchronization: The IB component stays in sync with TWS/Gateway automatically
- Async-Ready: Built on asyncio and eventkit for high-performance applications
- Notebook-Friendly: Explore live data interactively in marimo or Jupyter notebooks
- Production-Ready: Robust error handling, reconnection logic, and comprehensive logging
Be sure to take a look at the examples and notebooks, the recipes and the API docs.
Installation
ib_async now targets Python 3.11+ and publishes standard PEP 621 metadata, so the project installs cleanly with pip and uv.
Install with pip
pip install ib_async
util.df() and FlexReport.df() return polars DataFrames; install the extra to use them:
pip install "ib_async[polars]"
Install with uv
uv add ib_async
Requirements:
- Python 3.11 or higher
- We plan to support Python releases 2 years back which allows us to continue adding newer features and performance improvements over time.
- A running IB Gateway application (or TWS with API mode enabled)
- stable gateway — updated every few months
- latest gateway — updated weekly
- Make sure the API port is enabled and 'Download open orders on connection' is checked.
- You may also want to increase the Java memory usage under
Configure->Settings->Memory Allocationto 4096 MB minimum to prevent gateway crashes when loading bulk data.
The ibapi package from IB is not needed. ib_async implements the IBKR API protocol itself.
Build Manually
First, install the environment manager:
pip install uv -U
Install the project
uv sync
Install everything for development and docs
uv sync --group dev --group docs
Development loop (v3.0+)
The protobuf send / receive path landed in v3.0 generates bindings
from IBKR's .proto schemas at build time. The generated modules
live under ib_async/_pb/ and are gitignored — they're
build artifacts, not source. Local dev needs them on disk before
mypy / pytest will run; release builds regenerate them
before bundling into the wheel and sdist so end users of
pip install ib_async get a working package without protoc
or grpcio-tools.
The Makefile encapsulates this. After uv sync --all-groups:
# 1. Generate protobuf bindings into ib_async/_pb/. Fetches and
# SHA256-verifies the TWS API archive pinned in pyproject.toml
# on first run, then builds from the local cache.
make protos
# 2. Test suite.
make test
# 3. Linters.
make lint
# 4. Full release build (regenerates protos, then `uv build`).
make build
IBKR prunes old TWS API archives without notice. make twsapi-status
shows whether the pinned archive is still downloadable next to the
versions IBKR currently publishes, and make twsapi-bump V=<version>
re-pins after checking the new archive carries the .proto schemas
the build needs. From 10.53 IBKR publishes only installers, so pass
the Linux installer's URL:
make twsapi-bump V=1053.01 FROM=https://download2.interactivebrokers.com/installers/tws-api/latest/tws-api-latest-linux-x64.sh.
The installer is read, never run. To keep building a pruned pin, point
IB_TWSAPI_ARCHIVE at a copy of its archive; the pinned SHA256 still
applies.
make twsapi-unpack FROM=<zip or installer> DEST=<dir> writes the whole
TWS API to a directory, IBKR's Python, Java and C++ clients included,
to read how IBKR's own client handles a protocol change.
make help lists every target. make build regenerates the bindings
before building, so the wheel and sdist never depend on what is already
in _pb/.
Generate Docs
uv sync --group docs
uv run sphinx-build -b html docs html
Check Types
uv run mypy ib_async
Build Package
make build regenerates the protobuf bindings first, then builds the
sdist + wheel with bundled _pb/:
make build
Upload Package (if maintaining)
make publish runs the full release pipeline (protos, lint, parity
audit, tests, build, clean-venv smoke install) and only then uploads:
make publish
uv publish reads the token from UV_PUBLISH_TOKEN (or
--token your-api-token).
Setup Interactive Brokers
1. Download IB Gateway or TWS
- IB Gateway (Stable) — Updated every few months, more stable
- IB Gateway (Latest) — Updated weekly, newest features
- Trader Workstation (TWS) — Full trading platform
2. Configure API Access
- Enable API: Go to
Configure → API → Settingsand check "Enable ActiveX and Socket Clients" - Set Port: Default ports are 7497 (TWS) and 4001 (Gateway). You can change these if needed.
- Allow Connections: Add
127.0.0.1to "Trusted IPs" if connecting locally - Download Orders: Check "Download open orders on connection" to see existing orders
3. Performance Settings
- Memory: Go to
Configure → Settings → Memory Allocationand set to 4096 MB minimum to prevent crashes with bulk data - Timeouts: Increase API timeout settings if you experience disconnections during large data requests
4. Common Connection Issues
Connection Refused
# Make sure TWS/Gateway is running and API is enabled
# Check that ports match (7497 for TWS, 4001 for Gateway)
ib.connect("127.0.0.1", 7497, clientId=1) # TWS
ib.connect("127.0.0.1", 4001, clientId=1) # Gateway
Client ID Conflicts
# Each connection needs a unique client ID
ib.connect(
"127.0.0.1", 7497, clientId=1
) # Use different numbers for multiple connections
Market Data Issues
# For free delayed data (no subscription required)
ib.reqMarketDataType(3) # Delayed
ib.reqMarketDataType(4) # Delayed frozen
# For real-time data (requires subscription)
ib.reqMarketDataType(1) # Real-time
Connection Patterns
Basic Script Usage
from ib_async import *
ib = IB()
ib.connect("127.0.0.1", 7497, clientId=1)
# Your code here
ib.disconnect()
Notebook Usage
In a marimo notebook, cells run inside an event loop, so use the async API directly. The examples include a marimo notebook for each topic:
ib = IB()
await ib.connectAsync("127.0.0.1", 7497, clientId=1)
contract = Stock("TSLA", "SMART", "USD")
await ib.qualifyContractsAsync(contract)
bars = await ib.reqHistoricalDataAsync(contract, "", "1 D", "1 hour", "TRADES", True)
In Jupyter, util.startLoop() lets the synchronous API run inside the
notebook's event loop:
from ib_async import *
util.startLoop() # Required for Jupyter notebooks
ib = IB()
ib.connect("127.0.0.1", 7497, clientId=1)
# Your code here - no need to call ib.run()
Async Application
import asyncio
from ib_async import *
async def main():
ib = IB()
await ib.connectAsync("127.0.0.1", 7497, clientId=1)
# Your async code here
ib.disconnect()
asyncio.run(main())
Quick Start
Basic Connection
from ib_async import *
# Connect to TWS or IB Gateway
ib = IB()
ib.connect("127.0.0.1", 7497, clientId=1)
print("Connected")
# Disconnect when done
ib.disconnect()
Get Account Information
from ib_async import *
ib = IB()
ib.connect("127.0.0.1", 7497, clientId=1)
# Get account summary
account = ib.managedAccounts()[0]
summary = ib.accountSummary(account)
for item in summary:
print(f"{item.tag}: {item.value}")
ib.disconnect()
Historical Data
from ib_async import *
# util.startLoop() # uncomment this line when in a notebook
ib = IB()
ib.connect("127.0.0.1", 7497, clientId=1)
# Request historical data
contract = Forex("EURUSD")
ib.qualifyContracts(contract)
bars = ib.reqHistoricalData(
contract,
endDateTime="",
durationStr="30 D",
barSizeSetting="1 hour",
whatToShow="MIDPOINT",
useRTH=True,
)
# Convert to a polars DataFrame (pip install "ib_async[polars]"):
df = util.df(bars)
print(df.head())
ib.disconnect()
Live Market Data
from ib_async import *
import time
ib = IB()
ib.connect("127.0.0.1", 7497, clientId=1)
# Subscribe to live market data
contract = Stock("AAPL", "SMART", "USD")
ib.qualifyContracts(contract)
ticker = ib.reqMktData(contract, "", False, False)
# Print live quotes for 30 seconds
for i in range(30):
ib.sleep(1) # Wait 1 second
if ticker.last:
print(f"AAPL: ${ticker.last} (bid: ${ticker.bid}, ask: ${ticker.ask})")
ib.disconnect()
Place a Simple Order
from ib_async import *
ib = IB()
ib.connect("127.0.0.1", 7497, clientId=1)
# Create a contract and order
contract = Stock("AAPL", "SMART", "USD")
ib.qualifyContracts(contract)
order = MarketOrder("BUY", 100)
# Place the order
trade = ib.placeOrder(contract, order)
print(f"Order placed: {trade}")
# Monitor order status
while not trade.isDone():
ib.sleep(1)
print(f"Order status: {trade.orderStatus.status}")
ib.disconnect()
More Complete Examples
Portfolio Monitoring
from ib_async import *
ib = IB()
ib.connect("127.0.0.1", 7497, clientId=1)
# Get current positions
positions = ib.positions()
print("Current Positions:")
for pos in positions:
print(f"{pos.contract.symbol}: {pos.position} @ {pos.avgCost}")
# Get open orders
orders = ib.openTrades()
print(f"\nOpen Orders: {len(orders)}")
for trade in orders:
print(f"{trade.contract.symbol}: {trade.order.action} {trade.order.totalQuantity}")
ib.disconnect()
Real-time P&L Tracking
from ib_async import *
def onPnL(pnl):
print(
f"P&L Update: Unrealized: ${pnl.unrealizedPnL:.2f}, Realized: ${pnl.realizedPnL:.2f}"
)
ib = IB()
ib.connect("127.0.0.1", 7497, clientId=1)
# Subscribe to P&L updates
account = ib.managedAccounts()[0]
pnl = ib.reqPnL(account)
pnl.updateEvent += onPnL
# Keep running to receive updates
try:
ib.run() # Run until interrupted
except KeyboardInterrupt:
ib.disconnect()
Advanced Order Management
from ib_async import *
ib = IB()
ib.connect("127.0.0.1", 7497, clientId=1)
# Create a bracket order (entry + stop loss + take profit)
contract = Stock("TSLA", "SMART", "USD")
ib.qualifyContracts(contract)
# Parent order
parent = LimitOrder("BUY", 100, 250.00)
parent.orderId = ib.client.getReqId()
parent.transmit = False
# Stop loss
stopLoss = StopOrder("SELL", 100, 240.00)
stopLoss.orderId = ib.client.getReqId()
stopLoss.parentId = parent.orderId
stopLoss.transmit = False
# Take profit
takeProfit = LimitOrder("SELL", 100, 260.00)
takeProfit.orderId = ib.client.getReqId()
takeProfit.parentId = parent.orderId
takeProfit.transmit = True
# Place bracket order
trades = []
trades.append(ib.placeOrder(contract, parent))
trades.append(ib.placeOrder(contract, stopLoss))
trades.append(ib.placeOrder(contract, takeProfit))
print(f"Bracket order placed: {len(trades)} orders")
ib.disconnect()
Historical Data Analysis
from ib_async import *
import polars as pl
ib = IB()
ib.connect("127.0.0.1", 7497, clientId=1)
# Get multiple timeframes
contract = Stock("SPY", "SMART", "USD")
ib.qualifyContracts(contract)
# Daily bars for 1 year
daily_bars = ib.reqHistoricalData(
contract,
endDateTime="",
durationStr="1 Y",
barSizeSetting="1 day",
whatToShow="TRADES",
useRTH=True,
)
# 5-minute bars for last 5 days
intraday_bars = ib.reqHistoricalData(
contract,
endDateTime="",
durationStr="5 D",
barSizeSetting="5 mins",
whatToShow="TRADES",
useRTH=True,
)
# Convert to DataFrames
daily_df = util.df(daily_bars)
intraday_df = util.df(intraday_bars)
print(f"Daily bars: {len(daily_df)} rows")
print(f"Intraday bars: {len(intraday_df)} rows")
# Calculate simple moving average
daily_df = daily_df.with_columns(pl.col("close").rolling_mean(20).alias("SMA_20"))
print(daily_df.select("date", "close", "SMA_20").tail())
ib.disconnect()
Library Structure
Core Components
ib_async.ib.IB - Main interface class
- Connection management (
connect(),disconnect(),connectAsync()) - Market data requests (
reqMktData(),reqHistoricalData()) - Order management (
placeOrder(),cancelOrder()) - Account data (
positions(),accountSummary(),reqPnL())
ib_async.contract - Financial instruments
Stock,Option,Future,Forex,Index,BondContract- Base class for all instrumentsComboLeg,DeltaNeutralContract- Complex instruments
ib_async.ordertypes - Order types
- One constructor per IBKR order type:
MarketOrder,LimitOrder,StopOrder,StopLimitOrder,MarketOnCloseOrder,TrailingStopOrder,MidpriceOrder,SnapToMidpointOrder,RelativeOrderand more; each returns anOrderwith the fields IBKR expects, validated (Order types) - IB algos, combo routing and adjustable stops as modifiers of an order type:
LimitOrder("BUY", 100, 50.00, algo=Adaptive(priority="Urgent")) specOf(order)names an order's type;checkOrder(contract or details, order)lists what IBKR's documentation and the contract's details say against it;modifiedOrder(trade.order, ...)prepares a live order for modification
ib_async.order - Order management
Order- Base order class with all parametersOrderStatus,OrderState- Order execution trackingTrade- Complete order lifecycle tracking
ib_async.ticker - Real-time market data
Ticker- Live quotes, trades, and market data- Automatic field updates (bid, ask, last, volume, etc.)
- Event-driven updates via
updateEvent
ib_async.objects - Data structures
BarData- Historical price barsPosition- Portfolio positionsPortfolioItem- Portfolio details with P&LAccountValue- Account metrics
Key Patterns
Synchronous vs Asynchronous
# Synchronous (blocks until complete)
bars = ib.reqHistoricalData(contract, ...)
# Asynchronous (yields to event loop)
bars = await ib.reqHistoricalDataAsync(contract, ...)
Event Handling
# Subscribe to events
def onOrderUpdate(trade):
print(f"Order update: {trade.orderStatus.status}")
ib.orderStatusEvent += onOrderUpdate
# Or with async
async def onTicker(ticker):
print(f"Price update: {ticker.last}")
ticker.updateEvent += onTicker
Error Handling
try:
ib.connect("127.0.0.1", 7497, clientId=1)
except ConnectionRefusedError:
print("TWS/Gateway not running or API not enabled")
except Exception as e:
print(f"Connection error: {e}")
Documentation
The complete API documentation.
Development
Running Tests
The protobuf bindings under ib_async/_pb/ are generated, not committed,
so generate them once after syncing (and again after a TWS API bump):
uv sync --group dev
make protos # fetch the pinned TWS API archive, generate ib_async/_pb/
make test # the suite on the default interpreter
make test-matrix # the suite on each Python in [tool.releasekit.matrix],
# each in its own environment and time-boxed; logs in
# .venvs/logs/
make test-matrix LOOP=shared # every test on one event loop, as an
# application runs (each test has its own
# by default)
Linting, Type Checking and Formatting
make lint # ruff check, mypy and prettier --check
make format # ruff format and prettier --write
Local Development
- Clone the repository:
git clone https://github.com/ib-api-reloaded/ib_async.git
cd ib_async
- Install dependencies:
uv sync --group dev --group docs
- Generate the protobuf bindings, make your changes, and check them:
make protos
make test-matrix
make lint
- Submit a pull request with:
- Clear description of changes
- Tests for new functionality
- Updated documentation if needed
Contributing Guidelines
- Follow existing code style (enforced by ruff)
- Add tests for new features
- Update documentation for user-facing changes
- Keep commits focused and well-described
- Be responsive to code review feedback
Community Resources
If you have other public work related to ib_async or ib_insync open an issue and we can keep an active list here.
Projects below are not endorsed by any entity and are purely for reference or entertainment purposes.
- Adi's livestream VODs about using IBKR APIs: Interactive Brokers API in Python
- Matt's IBKR python CLI: icli
- A dockerized Jupyter quant research environment with ib_async: jupyter-quant
Disclaimer
The software is provided on the conditions of the simplified BSD license.
This project is not affiliated with Interactive Brokers Group, Inc.
Official Interactive Brokers API Docs
History
This library was originally created by Ewald de Wit as tws_async in early-2017 then became the more prominent ib_insync library in mid-2017. He maintained and improved the library for the world to use for free until his unexpected passing in early 2024. Afterward, we decided to rename the project to ib_async under a new github organization since we lost access to modify anything in the original repos and packaging and docs infrastructure.
The library is currently maintained by Matt Stancliff and we are open to adding more committers and org contributors if people show interest in helping out.
Metadata
Release files for ib_async 3.0.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| ib_async-3.0.0.tar.gz | 329.0 kB | Without provenance | Details for ib_async-3.0.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| ib_async-3.0.0-py3-none-any.whl | Python 3 | none | any | Details for ib_async-3.0.0-py3-none-any.whl |
Total release size: 913.9 kB
Release files / ib_async-3.0.0.tar.gz
| Download URL | ib_async-3.0.0.tar.gz |
|---|---|
| Size | 329.0 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
b26ac287d4be1e6b759921e1f392e126953cac91a8b6f6068b4068f04d4919dc
|
|
BLAKE2b-256 checksum How to use checksums |
459a386dbda3d92b93f83400da96414149dc66cf85654e0c60a356643a2b1a1d
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.13.8 {"installer":{"name":"uv","version":"0.13.8","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}
|
Release files / ib_async-3.0.0-py3-none-any.whl
| Download URL | ib_async-3.0.0-py3-none-any.whl |
|---|---|
| Size | 584.9 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
85b3dc937b1ed816b2fb35dd69f1ece266e5aa0a0d8d3ecf81bf74d37157203a
|
|
BLAKE2b-256 checksum How to use checksums |
83c8f6d1b3c367b378df67202b5dae9a9f8444bca6c778bfece80f6d1457643d
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.13.8 {"installer":{"name":"uv","version":"0.13.8","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}
|
Security for ib_async 3.0.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.