Registry / http-networking / ib-insync

ib-insync

JSON →
library0.9.86pypypiunverified

ib-insync is a Pythonic framework for Interactive Brokers API, offering both synchronous and asynchronous interfaces. It abstracts much of the complexity of the underlying `ibapi` library, providing a high-level, event-driven API for trading, market data, and account management. The current version is 0.9.86, and the library maintains a frequent release cadence with minor updates and bug fixes.

pip install ib-insync ibapi
INSTALL
IMPORT
SIG · IB-INSYNC
I
ib-insync
http-networkingpythonv0.9.86
Install
4.8s avg
Import
711ms
Disk
92MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v0.9.86 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.920 runs
installs and imports cleanly · install 0.0s · import 0.729s · 92.4MB
glibc
py 3.103.920 runs
installs and imports cleanly · install 4.8s · import 0.693s · 89MB
92MB installed
● package 92MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

IB
from ib_insync import IB
Stock
from ib_insync import Stock
Contract
from ib_insync import Contract
While Contract is available, specific contract types like Stock, Option, Future are often preferred for clarity.
util
from ib_insync import util
Contains utility functions like `util.startLoop()` for Jupyter environments.

This quickstart demonstrates how to connect to the Interactive Brokers API using `ib-insync`, qualify a stock contract, and retrieve historical data. It uses the asynchronous interface, which is the recommended modern approach. Ensure TWS (Trader Workstation) or IB Gateway is running and configured to accept API connections on the specified port.

import asyncio from ib_insync import IB, Stock, util async def main(): ib = IB() # Connect to TWS or IB Gateway on default port 7497 (TWS) or 4002 (Gateway) # Ensure TWS/Gateway is running and API settings allow connection (File -> Global Configuration -> API -> Settings). try: await ib.connect('127.0.0.1', 7497, clientId=1) print("Connected to Interactive Brokers API.") # Define a contract (e.g., Apple stock) contract = Stock('AAPL', 'SMART', 'USD') # Qualify the contract to ensure it's valid and get full details # This step is crucial to avoid 'No security definition' errors await ib.qualifyContracts(contract) print(f"Qualified contract: {contract.conId} - {contract.longName}") # Request historical data for the contract # Requires an active market data subscription for 'TRADES' or 'MIDPOINT' bars = await ib.reqHistoricalData( contract, endDateTime='', durationStr='1 D', # Request 1 day of data barSizeSetting='1 min', whatToShow='TRADES', useRTH=True, # Use regular trading hours formatDate=1 # Return datetime objects ) print(f"Received {len(bars)} historical bars for {contract.symbol}.") if bars: print(f"Last bar: Time={bars[-1].date}, Open={bars[-1].open}, Close={bars[-1].close}") except Exception as e: print(f"An error occurred: {e}") finally: if ib.isConnected(): ib.disconnect() print("Disconnected from Interactive Brokers API.") if __name__ == '__main__': asyncio.run(main())
Debug
Known issues
breakingibapi (Interactive Brokers API) version compatibility. ib-insync relies on the underlying ibapi library, which receives frequent updates. Mismatches between ib-insync and ibapi versions can lead to unexpected behavior or API errors.
fix
Always install `ibapi` alongside `ib-insync` and keep both libraries reasonably up-to-date. Refer to `ib-insync`'s official documentation for recommended `ibapi` version ranges. If issues occur, try upgrading or downgrading `ibapi`.
affects: All versions
gotchaSynchronous vs. Asynchronous execution. ib-insync supports both. Using `ib.run()` directly blocks the main thread, while `await ib.run()` (or `asyncio.run(main())`) is for asynchronous use. Mixing these incorrectly or forgetting `await` can lead to deadlocks or `RuntimeWarning`s.
fix
For script-based execution, `asyncio.run(your_async_main_function())` is preferred. For synchronous interactive use (e.g., in Jupyter), `ib.run()` can be used, but be mindful of its blocking nature. Ensure all `ib-insync` methods are `await`ed in an `async` context.
affects: All versions
gotchaTWS/Gateway connection issues. Common problems include 'Connection refused', 'errorCode=502', or 'Not connected' due to TWS/Gateway not running, incorrect port, firewall blocking, or API settings not allowing socket connections.
fix
Verify TWS/IB Gateway is running. Check your firewall settings. Confirm the port (default TWS: 7497, Gateway: 4002) and Client ID. In TWS/Gateway, go to File -> Global Configuration -> API -> Settings and ensure 'Enable ActiveX and Socket Clients' is checked.
affects: All versions
gotchaMarket Data Subscriptions. Many market data requests (e.g., `reqMktData`, `reqHistoricalData` for certain `whatToShow` values) will fail with 'Market data farm is disconnected' or 'Not subscribed to market data' errors if you do not have the required market data subscriptions on your Interactive Brokers account.
fix
Check your IB account subscriptions to ensure you have the necessary data packages (e.g., Level 1, Level 2, specific exchanges) for the data you are requesting. Paper trading accounts often have fewer default subscriptions.
affects: All versions
Upgrade
Version history
0.9.86latest on PyPI · released Jul 2, 2023
Audit
Dependencies
ibapirequiredThe underlying client library for connecting to Interactive Brokers TWS/Gateway. ib-insync requires it to function.
Agent activity
37 hits · last 30 days
node
35
Resources
ib-insync — pip install ib-insync · libregistry