{"id":7297,"library":"ib-insync","title":"IB-insync","description":"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.","status":"active","version":"0.9.86","language":"en","source_language":"en","source_url":"https://github.com/erdewit/ib_insync","tags":["finance","trading","interactive brokers","api","async","sync"],"install":[{"cmd":"pip install ib-insync ibapi","lang":"bash","label":"Install ib-insync and ibapi"}],"dependencies":[{"reason":"The underlying client library for connecting to Interactive Brokers TWS/Gateway. ib-insync requires it to function.","package":"ibapi","optional":false}],"imports":[{"symbol":"IB","correct":"from ib_insync import IB"},{"symbol":"Stock","correct":"from ib_insync import Stock"},{"note":"While Contract is available, specific contract types like Stock, Option, Future are often preferred for clarity.","symbol":"Contract","correct":"from ib_insync import Contract"},{"note":"Contains utility functions like `util.startLoop()` for Jupyter environments.","symbol":"util","correct":"from ib_insync import util"}],"quickstart":{"code":"import asyncio\nfrom ib_insync import IB, Stock, util\n\nasync def main():\n    ib = IB()\n    # Connect to TWS or IB Gateway on default port 7497 (TWS) or 4002 (Gateway)\n    # Ensure TWS/Gateway is running and API settings allow connection (File -> Global Configuration -> API -> Settings).\n    try:\n        await ib.connect('127.0.0.1', 7497, clientId=1)\n        print(\"Connected to Interactive Brokers API.\")\n\n        # Define a contract (e.g., Apple stock)\n        contract = Stock('AAPL', 'SMART', 'USD')\n        \n        # Qualify the contract to ensure it's valid and get full details\n        # This step is crucial to avoid 'No security definition' errors\n        await ib.qualifyContracts(contract)\n        print(f\"Qualified contract: {contract.conId} - {contract.longName}\")\n\n        # Request historical data for the contract\n        # Requires an active market data subscription for 'TRADES' or 'MIDPOINT'\n        bars = await ib.reqHistoricalData(\n            contract,\n            endDateTime='',\n            durationStr='1 D', # Request 1 day of data\n            barSizeSetting='1 min',\n            whatToShow='TRADES',\n            useRTH=True, # Use regular trading hours\n            formatDate=1 # Return datetime objects\n        )\n        print(f\"Received {len(bars)} historical bars for {contract.symbol}.\")\n        if bars:\n            print(f\"Last bar: Time={bars[-1].date}, Open={bars[-1].open}, Close={bars[-1].close}\")\n\n    except Exception as e:\n        print(f\"An error occurred: {e}\")\n    finally:\n        if ib.isConnected():\n            ib.disconnect()\n            print(\"Disconnected from Interactive Brokers API.\")\n\nif __name__ == '__main__':\n    asyncio.run(main())","lang":"python","description":"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."},"warnings":[{"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`.","message":"ibapi (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.","severity":"breaking","affected_versions":"All versions"},{"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.","message":"Synchronous 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.","severity":"gotcha","affected_versions":"All versions"},{"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.","message":"TWS/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.","severity":"gotcha","affected_versions":"All versions"},{"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.","message":"Market 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.","severity":"gotcha","affected_versions":"All versions"}],"env_vars":null,"last_verified":"2026-04-16T00:00:00.000Z","next_check":"2026-07-15T00:00:00.000Z","problems":[{"fix":"Ensure TWS or IB Gateway is running. Verify the correct port (default TWS: 7497, Gateway: 4002) is being used. Check firewall settings on your machine.","cause":"The client (your Python script) tried to connect to a port where no TWS or IB Gateway listener was active, or a firewall blocked the connection.","error":"ConnectionRefusedError: [Errno 61] Connection refused"},{"fix":"Confirm TWS/IB Gateway is fully launched and logged in. Check API settings in TWS/Gateway (File -> Global Configuration -> API -> Settings) to ensure 'Enable ActiveX and Socket Clients' is active and a valid IP (127.0.0.1) is added if restricting by IP.","cause":"The Interactive Brokers API client library (`ibapi`) received an error from TWS/Gateway, typically indicating a connection problem or that the API is not ready to accept connections.","error":"ibapi.common.IBAPIError: API error (id=-1, errorCode=502, errorString=Can't connect to TWS. It is possible that TWS is not running.)"},{"fix":"Always call `await ib.qualifyContracts(contract)` after defining a contract. Double-check all contract fields (`symbol`, `secType`, `exchange`, `currency`, `primaryExchange`) for accuracy. Use `ib.reqContractDetails(contract)` to search for valid contract definitions.","cause":"The contract you defined is ambiguous or invalid according to Interactive Brokers' system. This often happens if key fields like `exchange`, `currency`, or `primaryExchange` are missing or incorrect, or if `ib.qualifyContracts()` wasn't called.","error":"ibapi.common.IBAPIError: No security definition has been found for the request."},{"fix":"Ensure all `ib-insync` methods that are designed to be `await`able (most network operations) are preceded by `await` when called from within an `async def` function. If in a synchronous context, consider using `ib.run()` or converting your script to use `asyncio.run()`.","cause":"An asynchronous `ib-insync` method (which returns a coroutine) was called but was not `await`ed, leading to it never being executed.","error":"RuntimeWarning: coroutine '...' was never awaited"}]}