{"id":9043,"library":"ib-async","title":"ib-async: Interactive Brokers API Wrapper","description":"ib-async is an asynchronous and synchronous Python framework for the Interactive Brokers API, providing a user-friendly interface to TWS/Gateway for trading, market data, and account management. It is a fork/continuation of the popular ib_insync library. The current version is 2.1.0, with releases occurring semi-regularly, focusing on bug fixes and usability improvements.","status":"active","version":"2.1.0","language":"en","source_language":"en","source_url":"https://github.com/ib-api-reloaded/ib_async","tags":["finance","trading","interactive brokers","brokerage","api","asyncio","quantitative finance","market data"],"install":[{"cmd":"pip install ib-async","lang":"bash","label":"Install ib-async"}],"dependencies":[],"imports":[{"note":"Despite `pip install ib-async`, the actual Python package name is `ib_insync`. Attempting to import `ib_async` will result in a `ModuleNotFoundError`.","wrong":"from ib_async import IB","symbol":"IB","correct":"from ib_insync import IB"},{"symbol":"Contract","correct":"from ib_insync import Contract"},{"note":"The `util` module provides helper functions, including `util.run()` for running async code synchronously, though `IB.run()` is often preferred.","symbol":"util","correct":"from ib_insync import util"}],"quickstart":{"code":"from ib_insync import IB, Contract, util\nimport asyncio\n\nasync def main():\n    ib = IB()\n    try:\n        # Connect to TWS/Gateway. Default is localhost:7497 for TWS, 4002 for Gateway.\n        # Change host/port if TWS/Gateway is running elsewhere.\n        await ib.connect('127.0.0.1', 7497, clientId=1)\n\n        print(\"Connected to IB TWS/Gateway\")\n\n        # Define a contract\n        contract = Contract(symbol='SPY', secType='STK', exchange='SMART', currency='USD')\n\n        # Request market data\n        # Ensure you have subscribed to market data for SPY in TWS/Gateway\n        # Data from reqMktData is real-time, consider historical data for backtesting\n        # for data in ib.reqMktData(contract):\n        #    print(f\"Time: {data.time}, Bid: {data.bid}, Ask: {data.ask}\")\n\n        # Request historical data for the last 10 minutes\n        bars = await ib.reqHistoricalData(\n            contract, \n            endDateTime='', \n            durationStr='10 T', \n            barSizeSetting='1 min', \n            whatToShow='TRADES', \n            useRTH=True\n        )\n\n        if bars:\n            print(f\"Retrieved {len(bars)} historical bars for {contract.symbol}\")\n            for bar in bars:\n                print(f\"Time: {bar.date}, Open: {bar.open}, Close: {bar.close}, Volume: {bar.volume}\")\n        else:\n            print(f\"No historical data found for {contract.symbol}\")\n\n    except ConnectionRefusedError:\n        print(\"Connection refused. Is TWS/Gateway running and configured for API access?\")\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 IB TWS/Gateway\")\n\n# ib-async recommends using IB.run() for managing the event loop for simpler cases\n# or asyncio.run() for more complex applications.\n\n# To run the async main function:\nif __name__ == '__main__':\n    # Use IB.run() for simple script execution without manually managing asyncio loop\n    IB.run(main())\n    # Alternatively, for more control over the asyncio event loop:\n    # asyncio.run(main())\n","lang":"python","description":"This quickstart demonstrates how to connect to the Interactive Brokers TWS/Gateway, define a stock contract, and retrieve 1-minute historical trade data for the last 10 minutes using the `IB.run()` method to manage the asyncio event loop. Ensure TWS/Gateway is running and API access is enabled."},"warnings":[{"fix":"Always use `from ib_insync import ...` in your Python code after `pip install ib-async`.","message":"The PyPI package name is `ib-async`, but the actual Python package to import is `ib_insync`.","severity":"gotcha","affected_versions":"All versions (2.x)"},{"fix":"Ensure TWS or IB Gateway is running and configured to allow API connections on the specified host and port (default TWS: 7497, Gateway: 4002). Check TWS/Gateway API settings for `Enable ActiveX and Socket Clients` and `Read-Only API` permissions.","message":"ib-async requires a running Interactive Brokers TWS (Trader Workstation) or IB Gateway instance to connect to. It does not connect directly to IB servers.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Review the official ib-async documentation for the latest API usage, especially for event loop management and certain data request methods. Update your code to use `IB.run()` or `asyncio.run()` to start your main async function.","message":"Between versions 1.x (original ib_insync) and 2.x (ib-async fork), there were significant internal changes and some API adjustments. For example, `util.startLoop()` is less commonly used, with `IB.run()` or direct `asyncio.run()` preferred for managing the event loop.","severity":"breaking","affected_versions":"Upgrading from ib_insync 1.x to ib-async 2.x"},{"fix":"Use either `IB.run()` (which manages the asyncio loop internally for convenience) OR `asyncio.run()` (for direct asyncio control), but not both to start the main application. If using `IB.run()`, ensure it's called only once per application run.","message":"Incorrectly mixing `asyncio.run()` with `IB.run()` or calling `IB.run()` multiple times in a single script can lead to `RuntimeError: Event loop is already running.`","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":"Change your import statements from `from ib_async import ...` to `from ib_insync import ...`.","cause":"Attempting to import the library using its PyPI install name (`ib_async`) instead of its internal package name.","error":"ModuleNotFoundError: No module named 'ib_async'"},{"fix":"1. Ensure TWS or IB Gateway is running. 2. Verify the host (e.g., '127.0.0.1') and port (e.g., 7497) in your `ib.connect()` call match your TWS/Gateway API settings. 3. Check your firewall settings to allow connections on the specified port.","cause":"The Python client could not establish a connection to the specified host and port. Usually, TWS/Gateway is not running, is running on a different port/host, or firewall is blocking the connection.","error":"ConnectionRefusedError: [Errno 111] Connection refused"},{"fix":"Ensure you are calling `IB.run()` or `asyncio.run()` only once to start your main async function. If you are integrating `ib-async` into an existing async application, avoid starting a new loop; instead, schedule `ib-async` coroutines within the existing event loop.","cause":"This typically occurs when you try to start an asyncio event loop (e.g., with `asyncio.run()` or `IB.run()`) when one is already active.","error":"RuntimeError: Event loop is already running."},{"fix":"1. Double-check your `Contract` definition (symbol, secType, exchange, currency). 2. Ensure your IB account has the required market data subscriptions. 3. Verify `whatToShow`, `barSizeSetting`, and `useRTH` parameters are valid for the given contract and time period. Use `ib.reqContractDetails(contract)` to get valid contract information.","cause":"The contract definition or historical data parameters are incorrect or not supported by IB for that specific security/exchange, or you lack the necessary market data subscriptions.","error":"Historical data request error: Not a valid historical data subscription for contract..."}]}