ib_async 1.0.2__tar.gz → 2.0.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,582 @@
1
+ Metadata-Version: 2.1
2
+ Name: ib_async
3
+ Version: 2.0.1
4
+ Summary: Python sync/async framework for Interactive Brokers API
5
+ Home-page: https://github.com/ib-api-reloaded/ib_async
6
+ License: BSD
7
+ Keywords: ibapi,tws,asyncio,jupyter,interactive,brokers,async,ib_async,ib_insync
8
+ Author: Ewald de Wit
9
+ Maintainer: Matt Stancliff
10
+ Maintainer-email: matt@matt.sh
11
+ Requires-Python: >=3.10
12
+ Classifier: Development Status :: 5 - Production/Stable
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: BSD License
15
+ Classifier: License :: Other/Proprietary License
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3 :: Only
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Topic :: Office/Business :: Financial :: Investment
23
+ Requires-Dist: aeventkit (>=2.1.0,<3.0.0)
24
+ Requires-Dist: nest_asyncio
25
+ Project-URL: Bug Tracker, https://github.com/ib-api-reloaded/ib_async/issues
26
+ Project-URL: Repository, https://github.com/ib-api-reloaded/ib_async
27
+ Description-Content-Type: text/markdown
28
+
29
+ [![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)](#) <!-- [![Status](https://img.shields.io/badge/status-beta-green.svg)](#) --> [![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)](#) <!-- [![Downloads](https://static.pepy.tech/badge/ib-insync)](https://pepy.tech/project/ib-insync) --> [![Docs](https://img.shields.io/badge/Documentation-green.svg)](https://ib-api-reloaded.github.io/ib_async/)
30
+
31
+ # ib_async
32
+
33
+ ## Update
34
+
35
+ ## Introduction
36
+
37
+ `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.
38
+
39
+ ### What You Can Build
40
+
41
+ * **Market Data Applications**: Stream live quotes, historical data, and market depth
42
+ * **Trading Systems**: Place, modify, and monitor orders programmatically
43
+ * **Portfolio Tools**: Track positions, account balances, and P&L in real-time
44
+ * **Research Platforms**: Analyze contract details, option chains, and fundamental data
45
+ * **Risk Management**: Monitor exposures and implement automated controls
46
+
47
+ ### Key Features
48
+
49
+ * **Simple and Intuitive**: Write straightforward Python code without dealing with callback complexity
50
+ * **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
51
+ * **Async-Ready**: Built on [asyncio](https://docs.python.org/3/library/asyncio.html) and [eventkit](https://github.com/erdewit/eventkit) for high-performance applications
52
+ * **Jupyter-Friendly**: Interactive development with live data in notebooks
53
+ * **Production-Ready**: Robust error handling, reconnection logic, and comprehensive logging
54
+
55
+ Be sure to take a look at the
56
+ [notebooks](https://ib-api-reloaded.github.io/ib_async/notebooks.html),
57
+ the [recipes](https://ib-api-reloaded.github.io/ib_async/recipes.html)
58
+ and the [API docs](https://ib-api-reloaded.github.io/ib_async/api.html).
59
+
60
+
61
+ ## Installation
62
+
63
+ ```
64
+ pip install ib_async
65
+ ```
66
+
67
+ Requirements:
68
+
69
+ - Python 3.10 or higher
70
+ - 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.
71
+ - A running IB Gateway application (or TWS with API mode enabled)
72
+ - [stable gateway](https://www.interactivebrokers.com/en/trading/ibgateway-stable.php) — updated every few months
73
+ - [latest gateway](https://www.interactivebrokers.com/en/trading/ibgateway-latest.php) — updated weekly
74
+ - 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.
75
+ - You may also want to increase the Java memory usage under `Configure->Settings->Memory Allocation` to 4096 MB minimum to prevent gateway crashes when loading bulk data.
76
+
77
+ The ibapi package from IB is not needed. `ib_async` implements the full IBKR API binary protocol internally.
78
+
79
+ ## Build Manually
80
+
81
+ First, install poetry:
82
+
83
+ ```
84
+ pip install poetry -U
85
+ ```
86
+
87
+ ### Installing Only Library
88
+
89
+ ```
90
+ poetry install
91
+ ```
92
+
93
+ ### Install Everything (enable docs + dev testing)
94
+
95
+ ```
96
+ poetry install --with=docs,dev
97
+ ```
98
+
99
+ ## Generate Docs
100
+
101
+ ```
102
+ poetry install --with=docs
103
+ poetry run sphinx-build -b html docs html
104
+ ```
105
+
106
+ ## Check Types
107
+
108
+ ```
109
+ poetry run mypy ib_async
110
+ ```
111
+
112
+ ## Build Package
113
+
114
+ ```
115
+ poetry build
116
+ ```
117
+
118
+ ## Upload Package (if maintaining)
119
+
120
+ ```
121
+ poetry install
122
+ poetry config pypi-token.pypi your-api-token
123
+ poetry publish --build
124
+ ```
125
+
126
+ ## Setup Interactive Brokers
127
+
128
+ ### 1. Download IB Gateway or TWS
129
+
130
+ - [IB Gateway (Stable)](https://www.interactivebrokers.com/en/trading/ibgateway-stable.php) — Updated every few months, more stable
131
+ - [IB Gateway (Latest)](https://www.interactivebrokers.com/en/trading/ibgateway-latest.php) — Updated weekly, newest features
132
+ - [Trader Workstation (TWS)](https://www.interactivebrokers.com/en/trading/tws.php) — Full trading platform
133
+
134
+ ### 2. Configure API Access
135
+
136
+ 1. **Enable API**: Go to `Configure → API → Settings` and check "Enable ActiveX and Socket Clients"
137
+ 2. **Set Port**: Default ports are 7497 (TWS) and 4001 (Gateway). You can change these if needed.
138
+ 3. **Allow Connections**: Add `127.0.0.1` to "Trusted IPs" if connecting locally
139
+ 4. **Download Orders**: Check "Download open orders on connection" to see existing orders
140
+
141
+ ### 3. Performance Settings
142
+
143
+ - **Memory**: Go to `Configure → Settings → Memory Allocation` and set to 4096 MB minimum to prevent crashes with bulk data
144
+ - **Timeouts**: Increase API timeout settings if you experience disconnections during large data requests
145
+
146
+ ### 4. Common Connection Issues
147
+
148
+ **Connection Refused**
149
+ ```python
150
+ # Make sure TWS/Gateway is running and API is enabled
151
+ # Check that ports match (7497 for TWS, 4001 for Gateway)
152
+ ib.connect('127.0.0.1', 7497, clientId=1) # TWS
153
+ ib.connect('127.0.0.1', 4001, clientId=1) # Gateway
154
+ ```
155
+
156
+ **Client ID Conflicts**
157
+ ```python
158
+ # Each connection needs a unique client ID
159
+ ib.connect('127.0.0.1', 7497, clientId=1) # Use different numbers for multiple connections
160
+ ```
161
+
162
+ **Market Data Issues**
163
+ ```python
164
+ # For free delayed data (no subscription required)
165
+ ib.reqMarketDataType(3) # Delayed
166
+ ib.reqMarketDataType(4) # Delayed frozen
167
+
168
+ # For real-time data (requires subscription)
169
+ ib.reqMarketDataType(1) # Real-time
170
+ ```
171
+
172
+ ## Connection Patterns
173
+
174
+ ### Basic Script Usage
175
+ ```python
176
+ from ib_async import *
177
+
178
+ ib = IB()
179
+ ib.connect('127.0.0.1', 7497, clientId=1)
180
+ # Your code here
181
+ ib.disconnect()
182
+ ```
183
+
184
+ ### Jupyter Notebook Usage
185
+ ```python
186
+ from ib_async import *
187
+ util.startLoop() # Required for notebooks
188
+
189
+ ib = IB()
190
+ ib.connect('127.0.0.1', 7497, clientId=1)
191
+ # Your code here - no need to call ib.run()
192
+ ```
193
+
194
+ ### Async Application
195
+ ```python
196
+ import asyncio
197
+ from ib_async import *
198
+
199
+ async def main():
200
+ ib = IB()
201
+ await ib.connectAsync('127.0.0.1', 7497, clientId=1)
202
+ # Your async code here
203
+ ib.disconnect()
204
+
205
+ asyncio.run(main())
206
+ ```
207
+
208
+ ## Quick Start
209
+
210
+ ### Basic Connection
211
+
212
+ ```python
213
+ from ib_async import *
214
+
215
+ # Connect to TWS or IB Gateway
216
+ ib = IB()
217
+ ib.connect('127.0.0.1', 7497, clientId=1)
218
+ print("Connected")
219
+
220
+ # Disconnect when done
221
+ ib.disconnect()
222
+ ```
223
+
224
+ ### Get Account Information
225
+
226
+ ```python
227
+ from ib_async import *
228
+
229
+ ib = IB()
230
+ ib.connect('127.0.0.1', 7497, clientId=1)
231
+
232
+ # Get account summary
233
+ account = ib.managedAccounts()[0]
234
+ summary = ib.accountSummary(account)
235
+ for item in summary:
236
+ print(f"{item.tag}: {item.value}")
237
+
238
+ ib.disconnect()
239
+ ```
240
+
241
+ ### Historical Data
242
+
243
+ ```python
244
+ from ib_async import *
245
+ # util.startLoop() # uncomment this line when in a notebook
246
+
247
+ ib = IB()
248
+ ib.connect('127.0.0.1', 7497, clientId=1)
249
+
250
+ # Request historical data
251
+ contract = Forex('EURUSD')
252
+ bars = ib.reqHistoricalData(
253
+ contract, endDateTime='', durationStr='30 D',
254
+ barSizeSetting='1 hour', whatToShow='MIDPOINT', useRTH=True)
255
+
256
+ # Convert to pandas dataframe (pandas needs to be installed):
257
+ df = util.df(bars)
258
+ print(df.head())
259
+
260
+ ib.disconnect()
261
+ ```
262
+
263
+ ### Live Market Data
264
+
265
+ ```python
266
+ from ib_async import *
267
+ import time
268
+
269
+ ib = IB()
270
+ ib.connect('127.0.0.1', 7497, clientId=1)
271
+
272
+ # Subscribe to live market data
273
+ contract = Stock('AAPL', 'SMART', 'USD')
274
+ ticker = ib.reqMktData(contract, '', False, False)
275
+
276
+ # Print live quotes for 30 seconds
277
+ for i in range(30):
278
+ ib.sleep(1) # Wait 1 second
279
+ if ticker.last:
280
+ print(f"AAPL: ${ticker.last} (bid: ${ticker.bid}, ask: ${ticker.ask})")
281
+
282
+ ib.disconnect()
283
+ ```
284
+
285
+ ### Place a Simple Order
286
+
287
+ ```python
288
+ from ib_async import *
289
+
290
+ ib = IB()
291
+ ib.connect('127.0.0.1', 7497, clientId=1)
292
+
293
+ # Create a contract and order
294
+ contract = Stock('AAPL', 'SMART', 'USD')
295
+ order = MarketOrder('BUY', 100)
296
+
297
+ # Place the order
298
+ trade = ib.placeOrder(contract, order)
299
+ print(f"Order placed: {trade}")
300
+
301
+ # Monitor order status
302
+ while not trade.isDone():
303
+ ib.sleep(1)
304
+ print(f"Order status: {trade.orderStatus.status}")
305
+
306
+ ib.disconnect()
307
+ ```
308
+
309
+ ## More Complete Examples
310
+
311
+ ### Portfolio Monitoring
312
+
313
+ ```python
314
+ from ib_async import *
315
+
316
+ ib = IB()
317
+ ib.connect('127.0.0.1', 7497, clientId=1)
318
+
319
+ # Get current positions
320
+ positions = ib.positions()
321
+ print("Current Positions:")
322
+ for pos in positions:
323
+ print(f"{pos.contract.symbol}: {pos.position} @ {pos.avgCost}")
324
+
325
+ # Get open orders
326
+ orders = ib.openTrades()
327
+ print(f"\nOpen Orders: {len(orders)}")
328
+ for trade in orders:
329
+ print(f"{trade.contract.symbol}: {trade.order.action} {trade.order.totalQuantity}")
330
+
331
+ ib.disconnect()
332
+ ```
333
+
334
+ ### Real-time P&L Tracking
335
+
336
+ ```python
337
+ from ib_async import *
338
+
339
+ def onPnL(pnl):
340
+ print(f"P&L Update: Unrealized: ${pnl.unrealizedPnL:.2f}, Realized: ${pnl.realizedPnL:.2f}")
341
+
342
+ ib = IB()
343
+ ib.connect('127.0.0.1', 7497, clientId=1)
344
+
345
+ # Subscribe to P&L updates
346
+ account = ib.managedAccounts()[0]
347
+ pnl = ib.reqPnL(account)
348
+ pnl.updateEvent += onPnL
349
+
350
+ # Keep running to receive updates
351
+ try:
352
+ ib.run() # Run until interrupted
353
+ except KeyboardInterrupt:
354
+ ib.disconnect()
355
+ ```
356
+
357
+ ### Advanced Order Management
358
+
359
+ ```python
360
+ from ib_async import *
361
+
362
+ ib = IB()
363
+ ib.connect('127.0.0.1', 7497, clientId=1)
364
+
365
+ # Create a bracket order (entry + stop loss + take profit)
366
+ contract = Stock('TSLA', 'SMART', 'USD')
367
+
368
+ # Parent order
369
+ parent = LimitOrder('BUY', 100, 250.00)
370
+ parent.orderId = ib.client.getReqId()
371
+ parent.transmit = False
372
+
373
+ # Stop loss
374
+ stopLoss = StopOrder('SELL', 100, 240.00)
375
+ stopLoss.orderId = ib.client.getReqId()
376
+ stopLoss.parentId = parent.orderId
377
+ stopLoss.transmit = False
378
+
379
+ # Take profit
380
+ takeProfit = LimitOrder('SELL', 100, 260.00)
381
+ takeProfit.orderId = ib.client.getReqId()
382
+ takeProfit.parentId = parent.orderId
383
+ takeProfit.transmit = True
384
+
385
+ # Place bracket order
386
+ trades = []
387
+ trades.append(ib.placeOrder(contract, parent))
388
+ trades.append(ib.placeOrder(contract, stopLoss))
389
+ trades.append(ib.placeOrder(contract, takeProfit))
390
+
391
+ print(f"Bracket order placed: {len(trades)} orders")
392
+ ib.disconnect()
393
+ ```
394
+
395
+ ### Historical Data Analysis
396
+
397
+ ```python
398
+ from ib_async import *
399
+ import pandas as pd
400
+
401
+ ib = IB()
402
+ ib.connect('127.0.0.1', 7497, clientId=1)
403
+
404
+ # Get multiple timeframes
405
+ contract = Stock('SPY', 'SMART', 'USD')
406
+
407
+ # Daily bars for 1 year
408
+ daily_bars = ib.reqHistoricalData(
409
+ contract, endDateTime='', durationStr='1 Y',
410
+ barSizeSetting='1 day', whatToShow='TRADES', useRTH=True)
411
+
412
+ # 5-minute bars for last 5 days
413
+ intraday_bars = ib.reqHistoricalData(
414
+ contract, endDateTime='', durationStr='5 D',
415
+ barSizeSetting='5 mins', whatToShow='TRADES', useRTH=True)
416
+
417
+ # Convert to DataFrames
418
+ daily_df = util.df(daily_bars)
419
+ intraday_df = util.df(intraday_bars)
420
+
421
+ print(f"Daily bars: {len(daily_df)} rows")
422
+ print(f"Intraday bars: {len(intraday_df)} rows")
423
+
424
+ # Calculate simple moving average
425
+ daily_df['SMA_20'] = daily_df['close'].rolling(20).mean()
426
+ print(daily_df[['date', 'close', 'SMA_20']].tail())
427
+
428
+ ib.disconnect()
429
+ ```
430
+
431
+ ## Library Structure
432
+
433
+ ### Core Components
434
+
435
+ **`ib_async.ib.IB`** - Main interface class
436
+ - Connection management (`connect()`, `disconnect()`, `connectAsync()`)
437
+ - Market data requests (`reqMktData()`, `reqHistoricalData()`)
438
+ - Order management (`placeOrder()`, `cancelOrder()`)
439
+ - Account data (`positions()`, `accountSummary()`, `reqPnL()`)
440
+
441
+ **`ib_async.contract`** - Financial instruments
442
+ - `Stock`, `Option`, `Future`, `Forex`, `Index`, `Bond`
443
+ - `Contract` - Base class for all instruments
444
+ - `ComboLeg`, `DeltaNeutralContract` - Complex instruments
445
+
446
+ **`ib_async.order`** - Order types and management
447
+ - `MarketOrder`, `LimitOrder`, `StopOrder`, `StopLimitOrder`
448
+ - `Order` - Base order class with all parameters
449
+ - `OrderStatus`, `OrderState` - Order execution tracking
450
+ - `Trade` - Complete order lifecycle tracking
451
+
452
+ **`ib_async.ticker`** - Real-time market data
453
+ - `Ticker` - Live quotes, trades, and market data
454
+ - Automatic field updates (bid, ask, last, volume, etc.)
455
+ - Event-driven updates via `updateEvent`
456
+
457
+ **`ib_async.objects`** - Data structures
458
+ - `BarData` - Historical price bars
459
+ - `Position` - Portfolio positions
460
+ - `PortfolioItem` - Portfolio details with P&L
461
+ - `AccountValue` - Account metrics
462
+
463
+ ### Key Patterns
464
+
465
+ **Synchronous vs Asynchronous**
466
+ ```python
467
+ # Synchronous (blocks until complete)
468
+ bars = ib.reqHistoricalData(contract, ...)
469
+
470
+ # Asynchronous (yields to event loop)
471
+ bars = await ib.reqHistoricalDataAsync(contract, ...)
472
+ ```
473
+
474
+ **Event Handling**
475
+ ```python
476
+ # Subscribe to events
477
+ def onOrderUpdate(trade):
478
+ print(f"Order update: {trade.orderStatus.status}")
479
+
480
+ ib.orderStatusEvent += onOrderUpdate
481
+
482
+ # Or with async
483
+ async def onTicker(ticker):
484
+ print(f"Price update: {ticker.last}")
485
+
486
+ ticker.updateEvent += onTicker
487
+ ```
488
+
489
+ **Error Handling**
490
+ ```python
491
+ try:
492
+ ib.connect('127.0.0.1', 7497, clientId=1)
493
+ except ConnectionRefusedError:
494
+ print("TWS/Gateway not running or API not enabled")
495
+ except Exception as e:
496
+ print(f"Connection error: {e}")
497
+ ```
498
+
499
+ ## Documentation
500
+
501
+ The complete [API documentation](https://ib-api-reloaded.github.io/ib_async/api.html).
502
+
503
+ [Changelog](https://ib-api-reloaded.github.io/ib_async/changelog.html).
504
+
505
+ ## Development
506
+
507
+ ### Running Tests
508
+
509
+ ```bash
510
+ poetry install --with=dev
511
+ poetry run pytest
512
+ ```
513
+
514
+ ### Type Checking
515
+
516
+ ```bash
517
+ poetry run mypy ib_async
518
+ ```
519
+
520
+ ### Code Formatting
521
+
522
+ ```bash
523
+ poetry run ruff format
524
+ poetry run ruff check --fix
525
+ ```
526
+
527
+ ### Local Development
528
+
529
+ 1. Clone the repository:
530
+ ```bash
531
+ git clone https://github.com/ib-api-reloaded/ib_async.git
532
+ cd ib_async
533
+ ```
534
+
535
+ 2. Install dependencies:
536
+ ```bash
537
+ poetry install --with=dev,docs
538
+ ```
539
+
540
+ 3. Make your changes and run tests:
541
+ ```bash
542
+ poetry run pytest
543
+ poetry run mypy ib_async
544
+ ```
545
+
546
+ 4. Submit a pull request with:
547
+ - Clear description of changes
548
+ - Tests for new functionality
549
+ - Updated documentation if needed
550
+
551
+ ### Contributing Guidelines
552
+
553
+ - Follow existing code style (enforced by ruff)
554
+ - Add tests for new features
555
+ - Update documentation for user-facing changes
556
+ - Keep commits focused and well-described
557
+ - Be responsive to code review feedback
558
+
559
+ ## Community Resources
560
+
561
+ If you have other public work related to `ib_async` or `ib_insync` open an issue and we can keep an active list here.
562
+
563
+ Projects below are not endorsed by any entity and are purely for reference or entertainment purposes.
564
+
565
+ - Adi's livestream VODs about using IBKR APIs: [Interactive Brokers API in Python](https://www.youtube.com/playlist?list=PLCZZtBmmgxn8CFKysCkcl-B1tqRgCCNIX)
566
+ - Matt's IBKR python CLI: [icli](http://github.com/mattsta/icli)
567
+ - Corporate data parsing via IBKR API: [ib_fundamental](https://github.com/quantbelt/ib_fundamental)
568
+
569
+ ## Disclaimer
570
+
571
+ The software is provided on the conditions of the simplified BSD license.
572
+
573
+ This project is not affiliated with Interactive Brokers Group, Inc.
574
+
575
+ [Official Interactive Brokers API Docs](https://ibkrcampus.com/ibkr-api-page/twsapi-doc/)
576
+
577
+ ## History
578
+
579
+ This 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.
580
+
581
+ The 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.
582
+