{"id":33235929,"url":"https://github.com/ib-api-reloaded/ib_async","last_synced_at":"2025-11-16T18:03:02.035Z","repository":{"id":228307738,"uuid":"772323655","full_name":"ib-api-reloaded/ib_async","owner":"ib-api-reloaded","description":"Python sync/async framework for Interactive Brokers API (replaces ib_insync)","archived":false,"fork":false,"pushed_at":"2025-11-06T02:26:05.000Z","size":50380,"stargazers_count":1137,"open_issues_count":76,"forks_count":176,"subscribers_count":61,"default_branch":"main","last_synced_at":"2025-11-14T05:19:34.562Z","etag":null,"topics":["ib-async","ib-insync","ibkr","interactive-brokers","interactive-brokers-api","trading","twsapi"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"bsd-2-clause","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ib-api-reloaded.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null},"funding":{"github":"mattsta"}},"created_at":"2024-03-15T00:58:15.000Z","updated_at":"2025-11-11T22:43:22.000Z","dependencies_parsed_at":"2024-03-28T21:36:15.767Z","dependency_job_id":"2f5227d0-b1e3-4024-9344-c30225bb7429","html_url":"https://github.com/ib-api-reloaded/ib_async","commit_stats":null,"previous_names":["ib-api-reloaded/ib_async"],"tags_count":6,"template":false,"template_full_name":null,"purl":"pkg:github/ib-api-reloaded/ib_async","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ib-api-reloaded%2Fib_async","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ib-api-reloaded%2Fib_async/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ib-api-reloaded%2Fib_async/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ib-api-reloaded%2Fib_async/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ib-api-reloaded","download_url":"https://codeload.github.com/ib-api-reloaded/ib_async/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ib-api-reloaded%2Fib_async/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":284750955,"owners_count":27057456,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-11-16T02:00:05.974Z","response_time":65,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["ib-async","ib-insync","ibkr","interactive-brokers","interactive-brokers-api","trading","twsapi"],"created_at":"2025-11-16T18:02:03.899Z","updated_at":"2025-11-16T18:03:02.007Z","avatar_url":"https://github.com/ib-api-reloaded.png","language":"Python","funding_links":["https://github.com/sponsors/mattsta"],"categories":[],"sub_categories":[],"readme":"[![Build](https://github.com/ib-api-reloaded/ib_async/actions/workflows/test.yml/badge.svg?branch=next)](https://github.com/ib-api-reloaded/ib_async/actions) [![PyVersion](https://img.shields.io/badge/python-3.10+-blue.svg)](#) \u003c!-- [![Status](https://img.shields.io/badge/status-beta-green.svg)](#) --\u003e [![PyPiVersion](https://img.shields.io/pypi/v/ib_async.svg)](https://pypi.python.org/pypi/ib_async) [![License](https://img.shields.io/badge/license-BSD-blue.svg)](#) \u003c!-- [![Downloads](https://static.pepy.tech/badge/ib-insync)](https://pepy.tech/project/ib-insync) --\u003e [![Docs](https://img.shields.io/badge/Documentation-green.svg)](https://ib-api-reloaded.github.io/ib_async/)\n\n# ib_async\n\n## Update\n\n## Introduction\n\n`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](https://ibkrcampus.com/ibkr-api-page/twsapi-doc/) so you can focus on building trading applications, research tools, and market data analysis.\n\n### What You Can Build\n\n* **Market Data Applications**: Stream live quotes, historical data, and market depth\n* **Trading Systems**: Place, modify, and monitor orders programmatically\n* **Portfolio Tools**: Track positions, account balances, and P\u0026L in real-time\n* **Research Platforms**: Analyze contract details, option chains, and fundamental data\n* **Risk Management**: Monitor exposures and implement automated controls\n\n### Key Features\n\n* **Simple and Intuitive**: Write straightforward Python code without dealing with callback complexity\n* **Automatic Synchronization**: The [IB component](https://ib-api-reloaded.github.io/ib_async/api.html#module-ib_async.ib) stays in sync with TWS/Gateway automatically\n* **Async-Ready**: Built on [asyncio](https://docs.python.org/3/library/asyncio.html) and [eventkit](https://github.com/erdewit/eventkit) for high-performance applications\n* **Jupyter-Friendly**: Interactive development with live data in notebooks\n* **Production-Ready**: Robust error handling, reconnection logic, and comprehensive logging\n\nBe sure to take a look at the\n[notebooks](https://ib-api-reloaded.github.io/ib_async/notebooks.html),\nthe [recipes](https://ib-api-reloaded.github.io/ib_async/recipes.html)\nand the [API docs](https://ib-api-reloaded.github.io/ib_async/api.html).\n\n\n## Installation\n\n```\npip install ib_async\n```\n\nRequirements:\n\n- Python 3.10 or higher\n  - We plan to support Python releases [2 years back](https://devguide.python.org/versions/) which allows us to continue adding newer features and performance improvements over time.\n- A running IB Gateway application (or TWS with API mode enabled)\n    - [stable gateway](https://www.interactivebrokers.com/en/trading/ibgateway-stable.php) — updated every few months\n    - [latest gateway](https://www.interactivebrokers.com/en/trading/ibgateway-latest.php) — updated weekly\n- Make sure the [API port is enabled](https://ibkrcampus.com/ibkr-api-page/twsapi-doc/#tws-download) and 'Download open orders on connection' is checked.\n- You may also want to increase the Java memory usage under `Configure-\u003eSettings-\u003eMemory Allocation` to 4096 MB minimum to prevent gateway crashes when loading bulk data.\n\nThe ibapi package from IB is not needed. `ib_async` implements the full IBKR API binary protocol internally.\n\n## Build Manually\n\nFirst, install poetry:\n\n```\npip install poetry -U\n```\n\n### Installing Only Library\n\n```\npoetry install\n```\n\n### Install Everything (enable docs + dev testing)\n\n```\npoetry install --with=docs,dev\n```\n\n## Generate Docs\n\n```\npoetry install --with=docs\npoetry run sphinx-build -b html docs html\n```\n\n## Check Types\n\n```\npoetry run mypy ib_async\n```\n\n## Build Package\n\n```\npoetry build\n```\n\n## Upload Package (if maintaining)\n\n```\npoetry install\npoetry config pypi-token.pypi your-api-token\npoetry publish --build\n```\n\n## Setup Interactive Brokers\n\n### 1. Download IB Gateway or TWS\n\n- [IB Gateway (Stable)](https://www.interactivebrokers.com/en/trading/ibgateway-stable.php) — Updated every few months, more stable\n- [IB Gateway (Latest)](https://www.interactivebrokers.com/en/trading/ibgateway-latest.php) — Updated weekly, newest features\n- [Trader Workstation (TWS)](https://www.interactivebrokers.com/en/trading/tws.php) — Full trading platform\n\n### 2. Configure API Access\n\n1. **Enable API**: Go to `Configure → API → Settings` and check \"Enable ActiveX and Socket Clients\"\n2. **Set Port**: Default ports are 7497 (TWS) and 4001 (Gateway). You can change these if needed.\n3. **Allow Connections**: Add `127.0.0.1` to \"Trusted IPs\" if connecting locally\n4. **Download Orders**: Check \"Download open orders on connection\" to see existing orders\n\n### 3. Performance Settings\n\n- **Memory**: Go to `Configure → Settings → Memory Allocation` and set to 4096 MB minimum to prevent crashes with bulk data\n- **Timeouts**: Increase API timeout settings if you experience disconnections during large data requests\n\n### 4. Common Connection Issues\n\n**Connection Refused**\n```python\n# Make sure TWS/Gateway is running and API is enabled\n# Check that ports match (7497 for TWS, 4001 for Gateway)\nib.connect('127.0.0.1', 7497, clientId=1)  # TWS\nib.connect('127.0.0.1', 4001, clientId=1)  # Gateway\n```\n\n**Client ID Conflicts**\n```python\n# Each connection needs a unique client ID\nib.connect('127.0.0.1', 7497, clientId=1)  # Use different numbers for multiple connections\n```\n\n**Market Data Issues**\n```python\n# For free delayed data (no subscription required)\nib.reqMarketDataType(3)  # Delayed\nib.reqMarketDataType(4)  # Delayed frozen\n\n# For real-time data (requires subscription)\nib.reqMarketDataType(1)  # Real-time\n```\n\n## Connection Patterns\n\n### Basic Script Usage\n```python\nfrom ib_async import *\n\nib = IB()\nib.connect('127.0.0.1', 7497, clientId=1)\n# Your code here\nib.disconnect()\n```\n\n### Jupyter Notebook Usage\n```python\nfrom ib_async import *\nutil.startLoop()  # Required for notebooks\n\nib = IB()\nib.connect('127.0.0.1', 7497, clientId=1)\n# Your code here - no need to call ib.run()\n```\n\n### Async Application\n```python\nimport asyncio\nfrom ib_async import *\n\nasync def main():\n    ib = IB()\n    await ib.connectAsync('127.0.0.1', 7497, clientId=1)\n    # Your async code here\n    ib.disconnect()\n\nasyncio.run(main())\n```\n\n## Quick Start\n\n### Basic Connection\n\n```python\nfrom ib_async import *\n\n# Connect to TWS or IB Gateway\nib = IB()\nib.connect('127.0.0.1', 7497, clientId=1)\nprint(\"Connected\")\n\n# Disconnect when done\nib.disconnect()\n```\n\n### Get Account Information\n\n```python\nfrom ib_async import *\n\nib = IB()\nib.connect('127.0.0.1', 7497, clientId=1)\n\n# Get account summary\naccount = ib.managedAccounts()[0]\nsummary = ib.accountSummary(account)\nfor item in summary:\n    print(f\"{item.tag}: {item.value}\")\n\nib.disconnect()\n```\n\n### Historical Data\n\n```python\nfrom ib_async import *\n# util.startLoop()  # uncomment this line when in a notebook\n\nib = IB()\nib.connect('127.0.0.1', 7497, clientId=1)\n\n# Request historical data\ncontract = Forex('EURUSD')\nbars = ib.reqHistoricalData(\n    contract, endDateTime='', durationStr='30 D',\n    barSizeSetting='1 hour', whatToShow='MIDPOINT', useRTH=True)\n\n# Convert to pandas dataframe (pandas needs to be installed):\ndf = util.df(bars)\nprint(df.head())\n\nib.disconnect()\n```\n\n### Live Market Data\n\n```python\nfrom ib_async import *\nimport time\n\nib = IB()\nib.connect('127.0.0.1', 7497, clientId=1)\n\n# Subscribe to live market data\ncontract = Stock('AAPL', 'SMART', 'USD')\nticker = ib.reqMktData(contract, '', False, False)\n\n# Print live quotes for 30 seconds\nfor i in range(30):\n    ib.sleep(1)  # Wait 1 second\n    if ticker.last:\n        print(f\"AAPL: ${ticker.last} (bid: ${ticker.bid}, ask: ${ticker.ask})\")\n\nib.disconnect()\n```\n\n### Place a Simple Order\n\n```python\nfrom ib_async import *\n\nib = IB()\nib.connect('127.0.0.1', 7497, clientId=1)\n\n# Create a contract and order\ncontract = Stock('AAPL', 'SMART', 'USD')\norder = MarketOrder('BUY', 100)\n\n# Place the order\ntrade = ib.placeOrder(contract, order)\nprint(f\"Order placed: {trade}\")\n\n# Monitor order status\nwhile not trade.isDone():\n    ib.sleep(1)\n    print(f\"Order status: {trade.orderStatus.status}\")\n\nib.disconnect()\n```\n\n## More Complete Examples\n\n### Portfolio Monitoring\n\n```python\nfrom ib_async import *\n\nib = IB()\nib.connect('127.0.0.1', 7497, clientId=1)\n\n# Get current positions\npositions = ib.positions()\nprint(\"Current Positions:\")\nfor pos in positions:\n    print(f\"{pos.contract.symbol}: {pos.position} @ {pos.avgCost}\")\n\n# Get open orders\norders = ib.openTrades()\nprint(f\"\\nOpen Orders: {len(orders)}\")\nfor trade in orders:\n    print(f\"{trade.contract.symbol}: {trade.order.action} {trade.order.totalQuantity}\")\n\nib.disconnect()\n```\n\n### Real-time P\u0026L Tracking\n\n```python\nfrom ib_async import *\n\ndef onPnL(pnl):\n    print(f\"P\u0026L Update: Unrealized: ${pnl.unrealizedPnL:.2f}, Realized: ${pnl.realizedPnL:.2f}\")\n\nib = IB()\nib.connect('127.0.0.1', 7497, clientId=1)\n\n# Subscribe to P\u0026L updates\naccount = ib.managedAccounts()[0]\npnl = ib.reqPnL(account)\npnl.updateEvent += onPnL\n\n# Keep running to receive updates\ntry:\n    ib.run()  # Run until interrupted\nexcept KeyboardInterrupt:\n    ib.disconnect()\n```\n\n### Advanced Order Management\n\n```python\nfrom ib_async import *\n\nib = IB()\nib.connect('127.0.0.1', 7497, clientId=1)\n\n# Create a bracket order (entry + stop loss + take profit)\ncontract = Stock('TSLA', 'SMART', 'USD')\n\n# Parent order\nparent = LimitOrder('BUY', 100, 250.00)\nparent.orderId = ib.client.getReqId()\nparent.transmit = False\n\n# Stop loss\nstopLoss = StopOrder('SELL', 100, 240.00)\nstopLoss.orderId = ib.client.getReqId()\nstopLoss.parentId = parent.orderId\nstopLoss.transmit = False\n\n# Take profit\ntakeProfit = LimitOrder('SELL', 100, 260.00)\ntakeProfit.orderId = ib.client.getReqId()\ntakeProfit.parentId = parent.orderId\ntakeProfit.transmit = True\n\n# Place bracket order\ntrades = []\ntrades.append(ib.placeOrder(contract, parent))\ntrades.append(ib.placeOrder(contract, stopLoss))\ntrades.append(ib.placeOrder(contract, takeProfit))\n\nprint(f\"Bracket order placed: {len(trades)} orders\")\nib.disconnect()\n```\n\n### Historical Data Analysis\n\n```python\nfrom ib_async import *\nimport pandas as pd\n\nib = IB()\nib.connect('127.0.0.1', 7497, clientId=1)\n\n# Get multiple timeframes\ncontract = Stock('SPY', 'SMART', 'USD')\n\n# Daily bars for 1 year\ndaily_bars = ib.reqHistoricalData(\n    contract, endDateTime='', durationStr='1 Y',\n    barSizeSetting='1 day', whatToShow='TRADES', useRTH=True)\n\n# 5-minute bars for last 5 days\nintraday_bars = ib.reqHistoricalData(\n    contract, endDateTime='', durationStr='5 D',\n    barSizeSetting='5 mins', whatToShow='TRADES', useRTH=True)\n\n# Convert to DataFrames\ndaily_df = util.df(daily_bars)\nintraday_df = util.df(intraday_bars)\n\nprint(f\"Daily bars: {len(daily_df)} rows\")\nprint(f\"Intraday bars: {len(intraday_df)} rows\")\n\n# Calculate simple moving average\ndaily_df['SMA_20'] = daily_df['close'].rolling(20).mean()\nprint(daily_df[['date', 'close', 'SMA_20']].tail())\n\nib.disconnect()\n```\n\n## Library Structure\n\n### Core Components\n\n**`ib_async.ib.IB`** - Main interface class\n- Connection management (`connect()`, `disconnect()`, `connectAsync()`)\n- Market data requests (`reqMktData()`, `reqHistoricalData()`)\n- Order management (`placeOrder()`, `cancelOrder()`)\n- Account data (`positions()`, `accountSummary()`, `reqPnL()`)\n\n**`ib_async.contract`** - Financial instruments\n- `Stock`, `Option`, `Future`, `Forex`, `Index`, `Bond`\n- `Contract` - Base class for all instruments\n- `ComboLeg`, `DeltaNeutralContract` - Complex instruments\n\n**`ib_async.order`** - Order types and management\n- `MarketOrder`, `LimitOrder`, `StopOrder`, `StopLimitOrder`\n- `Order` - Base order class with all parameters\n- `OrderStatus`, `OrderState` - Order execution tracking\n- `Trade` - Complete order lifecycle tracking\n\n**`ib_async.ticker`** - Real-time market data\n- `Ticker` - Live quotes, trades, and market data\n- Automatic field updates (bid, ask, last, volume, etc.)\n- Event-driven updates via `updateEvent`\n\n**`ib_async.objects`** - Data structures\n- `BarData` - Historical price bars\n- `Position` - Portfolio positions\n- `PortfolioItem` - Portfolio details with P\u0026L\n- `AccountValue` - Account metrics\n\n### Key Patterns\n\n**Synchronous vs Asynchronous**\n```python\n# Synchronous (blocks until complete)\nbars = ib.reqHistoricalData(contract, ...)\n\n# Asynchronous (yields to event loop)\nbars = await ib.reqHistoricalDataAsync(contract, ...)\n```\n\n**Event Handling**\n```python\n# Subscribe to events\ndef onOrderUpdate(trade):\n    print(f\"Order update: {trade.orderStatus.status}\")\n\nib.orderStatusEvent += onOrderUpdate\n\n# Or with async\nasync def onTicker(ticker):\n    print(f\"Price update: {ticker.last}\")\n\nticker.updateEvent += onTicker\n```\n\n**Error Handling**\n```python\ntry:\n    ib.connect('127.0.0.1', 7497, clientId=1)\nexcept ConnectionRefusedError:\n    print(\"TWS/Gateway not running or API not enabled\")\nexcept Exception as e:\n    print(f\"Connection error: {e}\")\n```\n\n## Documentation\n\nThe complete [API documentation](https://ib-api-reloaded.github.io/ib_async/api.html).\n\n[Changelog](https://ib-api-reloaded.github.io/ib_async/changelog.html).\n\n## Development\n\n### Running Tests\n\n```bash\npoetry install --with=dev\npoetry run pytest\n```\n\n### Type Checking\n\n```bash\npoetry run mypy ib_async\n```\n\n### Code Formatting\n\n```bash\npoetry run ruff format\npoetry run ruff check --fix\n```\n\n### Local Development\n\n1. Clone the repository:\n```bash\ngit clone https://github.com/ib-api-reloaded/ib_async.git\ncd ib_async\n```\n\n2. Install dependencies:\n```bash\npoetry install --with=dev,docs\n```\n\n3. Make your changes and run tests:\n```bash\npoetry run pytest\npoetry run mypy ib_async\n```\n\n4. Submit a pull request with:\n   - Clear description of changes\n   - Tests for new functionality\n   - Updated documentation if needed\n\n### Contributing Guidelines\n\n- Follow existing code style (enforced by ruff)\n- Add tests for new features\n- Update documentation for user-facing changes\n- Keep commits focused and well-described\n- Be responsive to code review feedback\n\n## Community Resources\n\nIf you have other public work related to `ib_async` or `ib_insync` open an issue and we can keep an active list here.\n\nProjects below are not endorsed by any entity and are purely for reference or entertainment purposes.\n\n- Adi's livestream VODs about using IBKR APIs: [Interactive Brokers API in Python](https://www.youtube.com/playlist?list=PLCZZtBmmgxn8CFKysCkcl-B1tqRgCCNIX)\n- Matt's IBKR python CLI: [icli](http://github.com/mattsta/icli)\n- Corporate data parsing via IBKR API: [ib_fundamental](https://github.com/quantbelt/ib_fundamental)\n\n## Disclaimer\n\nThe software is provided on the conditions of the simplified BSD license.\n\nThis project is not affiliated with Interactive Brokers Group, Inc.\n\n[Official Interactive Brokers API Docs](https://ibkrcampus.com/ibkr-api-page/twsapi-doc/)\n\n## History\n\nThis library was originally created by [Ewald de Wit](https://github.com/erdewit) as [`tws_async` in early-2017](https://github.com/erdewit/tws_async) then became the more prominent [`ib_insync` library in mid-2017](https://github.com/erdewit/ib_insync). 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.\n\nThe library is currently maintained by [Matt Stancliff](https://github.com/mattsta) and we are open to adding more committers and org contributors if people show interest in helping out.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fib-api-reloaded%2Fib_async","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fib-api-reloaded%2Fib_async","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fib-api-reloaded%2Fib_async/lists"}