ib_async 2.0.1__tar.gz → 2.2.0__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.
- {ib_async-2.0.1 → ib_async-2.2.0}/PKG-INFO +68 -20
- {ib_async-2.0.1 → ib_async-2.2.0}/README.md +59 -9
- ib_async-2.2.0/ib_async/_requests.py +316 -0
- ib_async-2.2.0/ib_async/_subscriptions.py +536 -0
- {ib_async-2.0.1 → ib_async-2.2.0}/ib_async/client.py +83 -59
- {ib_async-2.0.1 → ib_async-2.2.0}/ib_async/connection.py +2 -3
- {ib_async-2.0.1 → ib_async-2.2.0}/ib_async/contract.py +9 -9
- {ib_async-2.0.1 → ib_async-2.2.0}/ib_async/decoder.py +90 -44
- {ib_async-2.0.1 → ib_async-2.2.0}/ib_async/flexreport.py +36 -6
- {ib_async-2.0.1 → ib_async-2.2.0}/ib_async/ib.py +553 -260
- {ib_async-2.0.1 → ib_async-2.2.0}/ib_async/objects.py +53 -20
- {ib_async-2.0.1 → ib_async-2.2.0}/ib_async/order.py +17 -3
- {ib_async-2.0.1 → ib_async-2.2.0}/ib_async/ticker.py +66 -14
- {ib_async-2.0.1 → ib_async-2.2.0}/ib_async/util.py +271 -70
- {ib_async-2.0.1 → ib_async-2.2.0}/ib_async/wrapper.py +681 -344
- {ib_async-2.0.1 → ib_async-2.2.0}/pyproject.toml +55 -16
- {ib_async-2.0.1 → ib_async-2.2.0}/LICENSE +0 -0
- {ib_async-2.0.1 → ib_async-2.2.0}/ib_async/__init__.py +1 -1
- {ib_async-2.0.1 → ib_async-2.2.0}/ib_async/ibcontroller.py +0 -0
- {ib_async-2.0.1 → ib_async-2.2.0}/ib_async/py.typed +0 -0
- {ib_async-2.0.1 → ib_async-2.2.0}/ib_async/version.py +0 -0
|
@@ -1,36 +1,42 @@
|
|
|
1
|
-
Metadata-Version: 2.
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
2
|
Name: ib_async
|
|
3
|
-
Version: 2.0
|
|
3
|
+
Version: 2.2.0
|
|
4
4
|
Summary: Python sync/async framework for Interactive Brokers API
|
|
5
|
-
|
|
6
|
-
License:
|
|
5
|
+
License-Expression: BSD-2-Clause
|
|
6
|
+
License-File: LICENSE
|
|
7
7
|
Keywords: ibapi,tws,asyncio,jupyter,interactive,brokers,async,ib_async,ib_insync
|
|
8
8
|
Author: Ewald de Wit
|
|
9
9
|
Maintainer: Matt Stancliff
|
|
10
10
|
Maintainer-email: matt@matt.sh
|
|
11
|
-
Requires-Python: >=3.
|
|
11
|
+
Requires-Python: >=3.11
|
|
12
12
|
Classifier: Development Status :: 5 - Production/Stable
|
|
13
13
|
Classifier: Intended Audience :: Developers
|
|
14
|
-
Classifier:
|
|
15
|
-
Classifier: License :: Other/Proprietary License
|
|
16
|
-
Classifier: Programming Language :: Python :: 3
|
|
17
|
-
Classifier: Programming Language :: Python :: 3.10
|
|
14
|
+
Classifier: Topic :: Office/Business :: Financial :: Investment
|
|
18
15
|
Classifier: Programming Language :: Python :: 3.11
|
|
19
16
|
Classifier: Programming Language :: Python :: 3.12
|
|
20
|
-
Classifier: Programming Language :: Python :: 3 :: Only
|
|
21
17
|
Classifier: Programming Language :: Python :: 3.13
|
|
22
|
-
Classifier:
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
19
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
23
20
|
Requires-Dist: aeventkit (>=2.1.0,<3.0.0)
|
|
24
21
|
Requires-Dist: nest_asyncio
|
|
22
|
+
Requires-Dist: tzdata (>=2025.2)
|
|
25
23
|
Project-URL: Bug Tracker, https://github.com/ib-api-reloaded/ib_async/issues
|
|
26
24
|
Project-URL: Repository, https://github.com/ib-api-reloaded/ib_async
|
|
27
25
|
Description-Content-Type: text/markdown
|
|
28
26
|
|
|
29
|
-
[](https://github.com/ib-api-reloaded/ib_async/actions) [](#) <!-- [](#) --> [](https://pypi.python.org/pypi/ib_async) [](#) <!-- [](https://pepy.tech/project/ib-insync) --> [](https://ib-api-reloaded.github.io/ib_async/)
|
|
30
28
|
|
|
31
29
|
# ib_async
|
|
32
30
|
|
|
33
|
-
##
|
|
31
|
+
## Legacy 2.x
|
|
32
|
+
|
|
33
|
+
This is the `legacy-2.x` branch: ib_async 2.2.0, released on 2026-12-02,
|
|
34
|
+
the last 2.x release. The branch gets no further changes.
|
|
35
|
+
|
|
36
|
+
In December 2026, IBKR will require TWS / IB Gateway 10.51 or later for
|
|
37
|
+
API connections. ib_async 2.x speaks IBKR's text protocol up to API
|
|
38
|
+
server version 178 and does not support that; ib_async 3.0, on the
|
|
39
|
+
`main` branch, does. See the 3.0 changelog and upgrade guide there.
|
|
34
40
|
|
|
35
41
|
## Introduction
|
|
36
42
|
|
|
@@ -60,13 +66,29 @@ and the [API docs](https://ib-api-reloaded.github.io/ib_async/api.html).
|
|
|
60
66
|
|
|
61
67
|
## Installation
|
|
62
68
|
|
|
69
|
+
`ib_async` now targets Python 3.11+ and publishes standard PEP 621 metadata, so the project installs cleanly with `pip`, `uv`, and `poetry`.
|
|
70
|
+
|
|
71
|
+
### Install with pip
|
|
72
|
+
|
|
63
73
|
```
|
|
64
74
|
pip install ib_async
|
|
65
75
|
```
|
|
66
76
|
|
|
77
|
+
### Install with uv
|
|
78
|
+
|
|
79
|
+
```
|
|
80
|
+
uv add ib_async
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
### Install with poetry
|
|
84
|
+
|
|
85
|
+
```
|
|
86
|
+
poetry add ib_async
|
|
87
|
+
```
|
|
88
|
+
|
|
67
89
|
Requirements:
|
|
68
90
|
|
|
69
|
-
- Python 3.
|
|
91
|
+
- Python 3.11 or higher
|
|
70
92
|
- 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
93
|
- A running IB Gateway application (or TWS with API mode enabled)
|
|
72
94
|
- [stable gateway](https://www.interactivebrokers.com/en/trading/ibgateway-stable.php) — updated every few months
|
|
@@ -78,41 +100,59 @@ The ibapi package from IB is not needed. `ib_async` implements the full IBKR API
|
|
|
78
100
|
|
|
79
101
|
## Build Manually
|
|
80
102
|
|
|
81
|
-
First, install
|
|
103
|
+
First, install your preferred environment manager:
|
|
82
104
|
|
|
83
105
|
```
|
|
84
106
|
pip install poetry -U
|
|
85
107
|
```
|
|
86
108
|
|
|
87
|
-
|
|
109
|
+
or:
|
|
110
|
+
|
|
111
|
+
```
|
|
112
|
+
pip install uv -U
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
### Install the project with poetry
|
|
88
116
|
|
|
89
117
|
```
|
|
90
118
|
poetry install
|
|
91
119
|
```
|
|
92
120
|
|
|
93
|
-
### Install
|
|
121
|
+
### Install the project with uv
|
|
94
122
|
|
|
95
123
|
```
|
|
124
|
+
uv sync
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
### Install everything for development and docs
|
|
128
|
+
|
|
129
|
+
```bash
|
|
96
130
|
poetry install --with=docs,dev
|
|
131
|
+
uv sync --group dev --group docs
|
|
97
132
|
```
|
|
98
133
|
|
|
99
134
|
## Generate Docs
|
|
100
135
|
|
|
101
|
-
```
|
|
136
|
+
```bash
|
|
102
137
|
poetry install --with=docs
|
|
103
138
|
poetry run sphinx-build -b html docs html
|
|
139
|
+
|
|
140
|
+
uv sync --group docs
|
|
141
|
+
uv run sphinx-build -b html docs html
|
|
104
142
|
```
|
|
105
143
|
|
|
106
144
|
## Check Types
|
|
107
145
|
|
|
108
|
-
```
|
|
146
|
+
```bash
|
|
109
147
|
poetry run mypy ib_async
|
|
148
|
+
uv run mypy ib_async
|
|
110
149
|
```
|
|
111
150
|
|
|
112
151
|
## Build Package
|
|
113
152
|
|
|
114
|
-
```
|
|
153
|
+
```bash
|
|
115
154
|
poetry build
|
|
155
|
+
python -m build
|
|
116
156
|
```
|
|
117
157
|
|
|
118
158
|
## Upload Package (if maintaining)
|
|
@@ -509,12 +549,16 @@ The complete [API documentation](https://ib-api-reloaded.github.io/ib_async/api.
|
|
|
509
549
|
```bash
|
|
510
550
|
poetry install --with=dev
|
|
511
551
|
poetry run pytest
|
|
552
|
+
|
|
553
|
+
uv sync --group dev
|
|
554
|
+
uv run pytest
|
|
512
555
|
```
|
|
513
556
|
|
|
514
557
|
### Type Checking
|
|
515
558
|
|
|
516
559
|
```bash
|
|
517
560
|
poetry run mypy ib_async
|
|
561
|
+
uv run mypy ib_async
|
|
518
562
|
```
|
|
519
563
|
|
|
520
564
|
### Code Formatting
|
|
@@ -522,6 +566,9 @@ poetry run mypy ib_async
|
|
|
522
566
|
```bash
|
|
523
567
|
poetry run ruff format
|
|
524
568
|
poetry run ruff check --fix
|
|
569
|
+
|
|
570
|
+
uv run ruff format
|
|
571
|
+
uv run ruff check --fix
|
|
525
572
|
```
|
|
526
573
|
|
|
527
574
|
### Local Development
|
|
@@ -535,6 +582,7 @@ cd ib_async
|
|
|
535
582
|
2. Install dependencies:
|
|
536
583
|
```bash
|
|
537
584
|
poetry install --with=dev,docs
|
|
585
|
+
uv sync --group dev --group docs
|
|
538
586
|
```
|
|
539
587
|
|
|
540
588
|
3. Make your changes and run tests:
|
|
@@ -1,8 +1,16 @@
|
|
|
1
|
-
[](https://github.com/ib-api-reloaded/ib_async/actions) [](#) <!-- [](#) --> [](https://pypi.python.org/pypi/ib_async) [](#) <!-- [](https://pepy.tech/project/ib-insync) --> [](https://ib-api-reloaded.github.io/ib_async/)
|
|
2
2
|
|
|
3
3
|
# ib_async
|
|
4
4
|
|
|
5
|
-
##
|
|
5
|
+
## Legacy 2.x
|
|
6
|
+
|
|
7
|
+
This is the `legacy-2.x` branch: ib_async 2.2.0, released on 2026-12-02,
|
|
8
|
+
the last 2.x release. The branch gets no further changes.
|
|
9
|
+
|
|
10
|
+
In December 2026, IBKR will require TWS / IB Gateway 10.51 or later for
|
|
11
|
+
API connections. ib_async 2.x speaks IBKR's text protocol up to API
|
|
12
|
+
server version 178 and does not support that; ib_async 3.0, on the
|
|
13
|
+
`main` branch, does. See the 3.0 changelog and upgrade guide there.
|
|
6
14
|
|
|
7
15
|
## Introduction
|
|
8
16
|
|
|
@@ -32,13 +40,29 @@ and the [API docs](https://ib-api-reloaded.github.io/ib_async/api.html).
|
|
|
32
40
|
|
|
33
41
|
## Installation
|
|
34
42
|
|
|
43
|
+
`ib_async` now targets Python 3.11+ and publishes standard PEP 621 metadata, so the project installs cleanly with `pip`, `uv`, and `poetry`.
|
|
44
|
+
|
|
45
|
+
### Install with pip
|
|
46
|
+
|
|
35
47
|
```
|
|
36
48
|
pip install ib_async
|
|
37
49
|
```
|
|
38
50
|
|
|
51
|
+
### Install with uv
|
|
52
|
+
|
|
53
|
+
```
|
|
54
|
+
uv add ib_async
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
### Install with poetry
|
|
58
|
+
|
|
59
|
+
```
|
|
60
|
+
poetry add ib_async
|
|
61
|
+
```
|
|
62
|
+
|
|
39
63
|
Requirements:
|
|
40
64
|
|
|
41
|
-
- Python 3.
|
|
65
|
+
- Python 3.11 or higher
|
|
42
66
|
- 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.
|
|
43
67
|
- A running IB Gateway application (or TWS with API mode enabled)
|
|
44
68
|
- [stable gateway](https://www.interactivebrokers.com/en/trading/ibgateway-stable.php) — updated every few months
|
|
@@ -50,41 +74,59 @@ The ibapi package from IB is not needed. `ib_async` implements the full IBKR API
|
|
|
50
74
|
|
|
51
75
|
## Build Manually
|
|
52
76
|
|
|
53
|
-
First, install
|
|
77
|
+
First, install your preferred environment manager:
|
|
54
78
|
|
|
55
79
|
```
|
|
56
80
|
pip install poetry -U
|
|
57
81
|
```
|
|
58
82
|
|
|
59
|
-
|
|
83
|
+
or:
|
|
84
|
+
|
|
85
|
+
```
|
|
86
|
+
pip install uv -U
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
### Install the project with poetry
|
|
60
90
|
|
|
61
91
|
```
|
|
62
92
|
poetry install
|
|
63
93
|
```
|
|
64
94
|
|
|
65
|
-
### Install
|
|
95
|
+
### Install the project with uv
|
|
66
96
|
|
|
67
97
|
```
|
|
98
|
+
uv sync
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
### Install everything for development and docs
|
|
102
|
+
|
|
103
|
+
```bash
|
|
68
104
|
poetry install --with=docs,dev
|
|
105
|
+
uv sync --group dev --group docs
|
|
69
106
|
```
|
|
70
107
|
|
|
71
108
|
## Generate Docs
|
|
72
109
|
|
|
73
|
-
```
|
|
110
|
+
```bash
|
|
74
111
|
poetry install --with=docs
|
|
75
112
|
poetry run sphinx-build -b html docs html
|
|
113
|
+
|
|
114
|
+
uv sync --group docs
|
|
115
|
+
uv run sphinx-build -b html docs html
|
|
76
116
|
```
|
|
77
117
|
|
|
78
118
|
## Check Types
|
|
79
119
|
|
|
80
|
-
```
|
|
120
|
+
```bash
|
|
81
121
|
poetry run mypy ib_async
|
|
122
|
+
uv run mypy ib_async
|
|
82
123
|
```
|
|
83
124
|
|
|
84
125
|
## Build Package
|
|
85
126
|
|
|
86
|
-
```
|
|
127
|
+
```bash
|
|
87
128
|
poetry build
|
|
129
|
+
python -m build
|
|
88
130
|
```
|
|
89
131
|
|
|
90
132
|
## Upload Package (if maintaining)
|
|
@@ -481,12 +523,16 @@ The complete [API documentation](https://ib-api-reloaded.github.io/ib_async/api.
|
|
|
481
523
|
```bash
|
|
482
524
|
poetry install --with=dev
|
|
483
525
|
poetry run pytest
|
|
526
|
+
|
|
527
|
+
uv sync --group dev
|
|
528
|
+
uv run pytest
|
|
484
529
|
```
|
|
485
530
|
|
|
486
531
|
### Type Checking
|
|
487
532
|
|
|
488
533
|
```bash
|
|
489
534
|
poetry run mypy ib_async
|
|
535
|
+
uv run mypy ib_async
|
|
490
536
|
```
|
|
491
537
|
|
|
492
538
|
### Code Formatting
|
|
@@ -494,6 +540,9 @@ poetry run mypy ib_async
|
|
|
494
540
|
```bash
|
|
495
541
|
poetry run ruff format
|
|
496
542
|
poetry run ruff check --fix
|
|
543
|
+
|
|
544
|
+
uv run ruff format
|
|
545
|
+
uv run ruff check --fix
|
|
497
546
|
```
|
|
498
547
|
|
|
499
548
|
### Local Development
|
|
@@ -507,6 +556,7 @@ cd ib_async
|
|
|
507
556
|
2. Install dependencies:
|
|
508
557
|
```bash
|
|
509
558
|
poetry install --with=dev,docs
|
|
559
|
+
uv sync --group dev --group docs
|
|
510
560
|
```
|
|
511
561
|
|
|
512
562
|
3. Make your changes and run tests:
|
|
@@ -0,0 +1,316 @@
|
|
|
1
|
+
"""Internal request correlation registry.
|
|
2
|
+
|
|
3
|
+
Each in-flight request from the IB API client side is tracked here as a
|
|
4
|
+
:class:`Request` keyed by a typed :class:`RequestKey`. The registry is
|
|
5
|
+
the single source of truth for:
|
|
6
|
+
|
|
7
|
+
* the awaitable :class:`asyncio.Future` the caller is blocked on,
|
|
8
|
+
* the streaming-accumulation container that response handlers append to,
|
|
9
|
+
* metadata: started time (monotonic), originating contract, refcount for
|
|
10
|
+
single-flight deduplication.
|
|
11
|
+
|
|
12
|
+
Discriminated key types prevent accidental cross-namespace lookups.
|
|
13
|
+
The IBKR wire protocol shares one monotonic counter for request IDs and
|
|
14
|
+
order IDs; tagging keys keeps the internal mapping unambiguous even
|
|
15
|
+
while the wire space stays unified.
|
|
16
|
+
|
|
17
|
+
Designed to be used only by :mod:`ib_async.wrapper`. The hot per-tick
|
|
18
|
+
dispatch path does NOT go through this module — it touches a flat
|
|
19
|
+
``reqId -> Ticker`` view maintained separately for the per-packet inner
|
|
20
|
+
loop.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
import asyncio
|
|
26
|
+
from collections.abc import Iterator
|
|
27
|
+
from dataclasses import dataclass
|
|
28
|
+
from typing import Any
|
|
29
|
+
|
|
30
|
+
from ib_async.util import getLoop
|
|
31
|
+
|
|
32
|
+
# Sentinel that lets `set_result` distinguish "use the accumulator"
|
|
33
|
+
# from "explicit None result". Module-private; never returned to callers.
|
|
34
|
+
_USE_CONTAINER: Any = object()
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
# --------------------------------------------------------------------------
|
|
38
|
+
# Discriminated key types
|
|
39
|
+
# --------------------------------------------------------------------------
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class RequestKey:
|
|
43
|
+
"""Tagged-union base class for request keys.
|
|
44
|
+
|
|
45
|
+
Use one of the four concrete subclasses so the registry's namespace
|
|
46
|
+
stays disjoint by type. Two keys are equal iff their concrete type
|
|
47
|
+
and field values match.
|
|
48
|
+
"""
|
|
49
|
+
|
|
50
|
+
__slots__ = ()
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@dataclass(frozen=True, slots=True)
|
|
54
|
+
class ReqIdKey(RequestKey):
|
|
55
|
+
"""Wraps an IBKR-allocated sequential request ID.
|
|
56
|
+
|
|
57
|
+
Used for one-shot data requests whose reqId is assigned client-side
|
|
58
|
+
via ``Client.getReqId()`` and echoed back on every response and the
|
|
59
|
+
end-of-stream callback (e.g. ``reqContractDetails``,
|
|
60
|
+
``reqHistoricalData``, ``reqExecutions``).
|
|
61
|
+
"""
|
|
62
|
+
|
|
63
|
+
reqId: int
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@dataclass(frozen=True, slots=True)
|
|
67
|
+
class SingletonKey(RequestKey):
|
|
68
|
+
"""A globally-named request whose response stream has no reqId on the
|
|
69
|
+
wire.
|
|
70
|
+
|
|
71
|
+
Examples: ``openOrders``, ``completedOrders``, ``positions``,
|
|
72
|
+
``currentTime``, ``mktDepthExchanges``, ``newsProviders``,
|
|
73
|
+
``scannerParams``, ``requestFA``, ``accountValues``.
|
|
74
|
+
"""
|
|
75
|
+
|
|
76
|
+
name: str
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
@dataclass(frozen=True, slots=True)
|
|
80
|
+
class CompositeKey(RequestKey):
|
|
81
|
+
"""Parameterised singleton: a name plus a tuple of arguments.
|
|
82
|
+
|
|
83
|
+
Example: ``CompositeKey("marketRule", (marketRuleId,))`` keeps
|
|
84
|
+
distinct in-flight requests for distinct rule IDs without colliding
|
|
85
|
+
in the global namespace.
|
|
86
|
+
"""
|
|
87
|
+
|
|
88
|
+
name: str
|
|
89
|
+
args: tuple = ()
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
@dataclass(frozen=True, slots=True)
|
|
93
|
+
class WhatIfKey(RequestKey):
|
|
94
|
+
"""Wraps the orderId of a ``placeOrder(whatIf=True)`` request.
|
|
95
|
+
|
|
96
|
+
Distinct from :class:`ReqIdKey` so a stray contract-details error
|
|
97
|
+
using the same numeric id cannot collide with a margin-impact
|
|
98
|
+
future.
|
|
99
|
+
"""
|
|
100
|
+
|
|
101
|
+
orderId: int
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
# --------------------------------------------------------------------------
|
|
105
|
+
# Request record
|
|
106
|
+
# --------------------------------------------------------------------------
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
@dataclass(slots=True)
|
|
110
|
+
class Request:
|
|
111
|
+
"""One in-flight request and its accumulated state.
|
|
112
|
+
|
|
113
|
+
Once ``settled`` is True the entry has been removed from the registry
|
|
114
|
+
and the future has either been fulfilled or rejected; further
|
|
115
|
+
callbacks for this key are safe no-ops.
|
|
116
|
+
"""
|
|
117
|
+
|
|
118
|
+
key: RequestKey
|
|
119
|
+
future: asyncio.Future
|
|
120
|
+
container: Any = None
|
|
121
|
+
contract: Any = None
|
|
122
|
+
refcount: int = 1
|
|
123
|
+
settled: bool = False
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
# --------------------------------------------------------------------------
|
|
127
|
+
# Registry
|
|
128
|
+
# --------------------------------------------------------------------------
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
class RequestRegistry:
|
|
132
|
+
"""Owns the lifecycle of in-flight :class:`Request` entries.
|
|
133
|
+
|
|
134
|
+
All operations are O(1); the hot per-tick dispatch path does not
|
|
135
|
+
touch this object. Methods are idempotent where it matters: late or
|
|
136
|
+
duplicate callbacks become no-ops rather than KeyErrors.
|
|
137
|
+
"""
|
|
138
|
+
|
|
139
|
+
__slots__ = ("_reqs",)
|
|
140
|
+
|
|
141
|
+
def __init__(self) -> None:
|
|
142
|
+
self._reqs: dict[RequestKey, Request] = {}
|
|
143
|
+
|
|
144
|
+
# -- queries ---------------------------------------------------------
|
|
145
|
+
|
|
146
|
+
def __contains__(self, key: RequestKey) -> bool:
|
|
147
|
+
req = self._reqs.get(key)
|
|
148
|
+
return req is not None and not req.settled
|
|
149
|
+
|
|
150
|
+
def __len__(self) -> int:
|
|
151
|
+
return len(self._reqs)
|
|
152
|
+
|
|
153
|
+
def __iter__(self) -> Iterator[Request]:
|
|
154
|
+
return iter(self._reqs.values())
|
|
155
|
+
|
|
156
|
+
def find_by_reqid(self, reqId: int) -> Request | None:
|
|
157
|
+
"""Return the :class:`Request` whose key is ``ReqIdKey(reqId)`` or
|
|
158
|
+
``WhatIfKey(reqId)``, or ``None``.
|
|
159
|
+
|
|
160
|
+
Used by the wire-level error handler, which sees only the raw
|
|
161
|
+
integer ``reqId`` and must resolve to the right request without
|
|
162
|
+
knowing which key flavour was used at open time.
|
|
163
|
+
"""
|
|
164
|
+
|
|
165
|
+
for key in (ReqIdKey(reqId), WhatIfKey(reqId)):
|
|
166
|
+
req = self._reqs.get(key)
|
|
167
|
+
if req is not None and not req.settled:
|
|
168
|
+
return req
|
|
169
|
+
return None
|
|
170
|
+
|
|
171
|
+
def get(self, key: RequestKey) -> Request | None:
|
|
172
|
+
"""Return the live :class:`Request` for ``key``, or ``None``.
|
|
173
|
+
|
|
174
|
+
A settled request is treated as absent.
|
|
175
|
+
"""
|
|
176
|
+
|
|
177
|
+
req = self._reqs.get(key)
|
|
178
|
+
if req is None or req.settled:
|
|
179
|
+
return None
|
|
180
|
+
return req
|
|
181
|
+
|
|
182
|
+
# -- lifecycle -------------------------------------------------------
|
|
183
|
+
|
|
184
|
+
def open(
|
|
185
|
+
self,
|
|
186
|
+
key: RequestKey,
|
|
187
|
+
*,
|
|
188
|
+
future: asyncio.Future | None = None,
|
|
189
|
+
container: Any = None,
|
|
190
|
+
contract: Any = None,
|
|
191
|
+
single_flight: bool = False,
|
|
192
|
+
) -> tuple[Request, bool]:
|
|
193
|
+
"""Open or attach to a request.
|
|
194
|
+
|
|
195
|
+
Returns ``(request, isNew)``.
|
|
196
|
+
|
|
197
|
+
With ``single_flight=True``: if a live request for ``key``
|
|
198
|
+
already exists, return it with ``isNew=False`` so the caller
|
|
199
|
+
skips re-issuing the underlying API request and attaches to the
|
|
200
|
+
in-flight result. The existing request's ``refcount`` is
|
|
201
|
+
incremented.
|
|
202
|
+
|
|
203
|
+
Without ``single_flight`` an attempt to re-open a live key
|
|
204
|
+
raises :class:`RuntimeError` — loud failure beats silent
|
|
205
|
+
overwrite.
|
|
206
|
+
|
|
207
|
+
``future`` may be passed in to re-use an externally-created
|
|
208
|
+
Future (used by the legacy :meth:`Wrapper.startReq` facade).
|
|
209
|
+
Otherwise a fresh future is created on the active loop.
|
|
210
|
+
|
|
211
|
+
``container`` defaults to a fresh empty list. Pass an explicit
|
|
212
|
+
object (string, dataclass instance, list of expected size) for
|
|
213
|
+
callbacks that need a specific accumulator type.
|
|
214
|
+
"""
|
|
215
|
+
|
|
216
|
+
existing = self._reqs.get(key)
|
|
217
|
+
if existing is not None and not existing.settled:
|
|
218
|
+
if single_flight:
|
|
219
|
+
existing.refcount += 1
|
|
220
|
+
return existing, False
|
|
221
|
+
raise RuntimeError(f"request already in flight: {key!r}")
|
|
222
|
+
|
|
223
|
+
if future is None:
|
|
224
|
+
future = getLoop().create_future()
|
|
225
|
+
if container is None:
|
|
226
|
+
container = []
|
|
227
|
+
|
|
228
|
+
req = Request(
|
|
229
|
+
key=key,
|
|
230
|
+
future=future,
|
|
231
|
+
container=container,
|
|
232
|
+
contract=contract,
|
|
233
|
+
)
|
|
234
|
+
self._reqs[key] = req
|
|
235
|
+
return req, True
|
|
236
|
+
|
|
237
|
+
def append(self, key: RequestKey, item: Any) -> None:
|
|
238
|
+
"""Append ``item`` to the request's accumulator.
|
|
239
|
+
|
|
240
|
+
No-op if the request is missing or already settled. Replaces
|
|
241
|
+
legacy ``_results[key].append(...)`` call sites that could
|
|
242
|
+
``KeyError`` on a late-callback race.
|
|
243
|
+
"""
|
|
244
|
+
|
|
245
|
+
req = self._reqs.get(key)
|
|
246
|
+
if req is None or req.settled:
|
|
247
|
+
return
|
|
248
|
+
req.container.append(item)
|
|
249
|
+
|
|
250
|
+
def extend(self, key: RequestKey, items: Any) -> None:
|
|
251
|
+
"""Extend the request's accumulator with ``items``.
|
|
252
|
+
|
|
253
|
+
Same semantics as :meth:`append` but for batch inserts where the
|
|
254
|
+
callback delivers a chunk of items at once (e.g. historical
|
|
255
|
+
tick streams).
|
|
256
|
+
"""
|
|
257
|
+
|
|
258
|
+
req = self._reqs.get(key)
|
|
259
|
+
if req is None or req.settled:
|
|
260
|
+
return
|
|
261
|
+
req.container.extend(items)
|
|
262
|
+
|
|
263
|
+
def set_result(self, key: RequestKey, value: Any = _USE_CONTAINER) -> None:
|
|
264
|
+
"""Settle the request's future with ``value``.
|
|
265
|
+
|
|
266
|
+
If no value is given, settles with the accumulator. Idempotent;
|
|
267
|
+
a second call for the same key is a no-op.
|
|
268
|
+
"""
|
|
269
|
+
|
|
270
|
+
req = self._reqs.pop(key, None)
|
|
271
|
+
if req is None:
|
|
272
|
+
return
|
|
273
|
+
req.settled = True
|
|
274
|
+
if req.future.done():
|
|
275
|
+
return
|
|
276
|
+
result = req.container if value is _USE_CONTAINER else value
|
|
277
|
+
req.future.set_result(result)
|
|
278
|
+
|
|
279
|
+
def set_error(self, key: RequestKey, exc: BaseException) -> None:
|
|
280
|
+
"""Settle the request's future with an exception. Idempotent."""
|
|
281
|
+
|
|
282
|
+
req = self._reqs.pop(key, None)
|
|
283
|
+
if req is None:
|
|
284
|
+
return
|
|
285
|
+
req.settled = True
|
|
286
|
+
if req.future.done():
|
|
287
|
+
return
|
|
288
|
+
req.future.set_exception(exc)
|
|
289
|
+
|
|
290
|
+
def cancel(self, key: RequestKey, reason: str = "") -> None:
|
|
291
|
+
"""Settle with :class:`asyncio.CancelledError`. Idempotent."""
|
|
292
|
+
|
|
293
|
+
self.set_error(key, asyncio.CancelledError(reason or repr(key)))
|
|
294
|
+
|
|
295
|
+
def fail_all(self, exc: BaseException) -> None:
|
|
296
|
+
"""Settle every live request with ``exc``.
|
|
297
|
+
|
|
298
|
+
Used on disconnect so every awaiter is woken instead of
|
|
299
|
+
silently hanging on a future that will never be resolved.
|
|
300
|
+
After this returns the registry is empty.
|
|
301
|
+
"""
|
|
302
|
+
|
|
303
|
+
for req in list(self._reqs.values()):
|
|
304
|
+
req.settled = True
|
|
305
|
+
if not req.future.done():
|
|
306
|
+
req.future.set_exception(exc)
|
|
307
|
+
self._reqs.clear()
|
|
308
|
+
|
|
309
|
+
def clear(self) -> None:
|
|
310
|
+
"""Drop all entries without settling.
|
|
311
|
+
|
|
312
|
+
Used by :meth:`Wrapper.reset` after :meth:`fail_all` has already
|
|
313
|
+
run, and by tests. Does not touch futures.
|
|
314
|
+
"""
|
|
315
|
+
|
|
316
|
+
self._reqs.clear()
|