ib_async 2.0.1__tar.gz → 2.1.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.1.0}/PKG-INFO +6 -5
- {ib_async-2.0.1 → ib_async-2.1.0}/ib_async/client.py +7 -8
- {ib_async-2.0.1 → ib_async-2.1.0}/ib_async/connection.py +2 -3
- {ib_async-2.0.1 → ib_async-2.1.0}/ib_async/contract.py +9 -9
- {ib_async-2.0.1 → ib_async-2.1.0}/ib_async/decoder.py +1 -1
- {ib_async-2.0.1 → ib_async-2.1.0}/ib_async/flexreport.py +36 -6
- {ib_async-2.0.1 → ib_async-2.1.0}/ib_async/ib.py +28 -28
- {ib_async-2.0.1 → ib_async-2.1.0}/ib_async/objects.py +51 -19
- {ib_async-2.0.1 → ib_async-2.1.0}/ib_async/order.py +1 -2
- {ib_async-2.0.1 → ib_async-2.1.0}/ib_async/ticker.py +60 -13
- {ib_async-2.0.1 → ib_async-2.1.0}/ib_async/util.py +45 -30
- {ib_async-2.0.1 → ib_async-2.1.0}/ib_async/wrapper.py +137 -57
- {ib_async-2.0.1 → ib_async-2.1.0}/pyproject.toml +26 -2
- {ib_async-2.0.1 → ib_async-2.1.0}/LICENSE +0 -0
- {ib_async-2.0.1 → ib_async-2.1.0}/README.md +0 -0
- {ib_async-2.0.1 → ib_async-2.1.0}/ib_async/__init__.py +1 -1
- {ib_async-2.0.1 → ib_async-2.1.0}/ib_async/ibcontroller.py +0 -0
- {ib_async-2.0.1 → ib_async-2.1.0}/ib_async/py.typed +0 -0
- {ib_async-2.0.1 → ib_async-2.1.0}/ib_async/version.py +0 -0
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
Metadata-Version: 2.
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
2
|
Name: ib_async
|
|
3
|
-
Version: 2.0
|
|
3
|
+
Version: 2.1.0
|
|
4
4
|
Summary: Python sync/async framework for Interactive Brokers API
|
|
5
|
-
Home-page: https://github.com/ib-api-reloaded/ib_async
|
|
6
5
|
License: BSD
|
|
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
|
|
@@ -11,17 +11,18 @@ Maintainer-email: matt@matt.sh
|
|
|
11
11
|
Requires-Python: >=3.10
|
|
12
12
|
Classifier: Development Status :: 5 - Production/Stable
|
|
13
13
|
Classifier: Intended Audience :: Developers
|
|
14
|
-
Classifier: License :: OSI Approved :: BSD License
|
|
15
14
|
Classifier: License :: Other/Proprietary License
|
|
16
15
|
Classifier: Programming Language :: Python :: 3
|
|
17
16
|
Classifier: Programming Language :: Python :: 3.10
|
|
18
17
|
Classifier: Programming Language :: Python :: 3.11
|
|
19
18
|
Classifier: Programming Language :: Python :: 3.12
|
|
20
|
-
Classifier: Programming Language :: Python :: 3 :: Only
|
|
21
19
|
Classifier: Programming Language :: Python :: 3.13
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
21
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
22
22
|
Classifier: Topic :: Office/Business :: Financial :: Investment
|
|
23
23
|
Requires-Dist: aeventkit (>=2.1.0,<3.0.0)
|
|
24
24
|
Requires-Dist: nest_asyncio
|
|
25
|
+
Requires-Dist: tzdata (>=2025.2,<2026.0)
|
|
25
26
|
Project-URL: Bug Tracker, https://github.com/ib-api-reloaded/ib_async/issues
|
|
26
27
|
Project-URL: Repository, https://github.com/ib-api-reloaded/ib_async
|
|
27
28
|
Description-Content-Type: text/markdown
|
|
@@ -7,7 +7,8 @@ import math
|
|
|
7
7
|
import struct
|
|
8
8
|
import time
|
|
9
9
|
from collections import deque
|
|
10
|
-
from
|
|
10
|
+
from collections.abc import Callable
|
|
11
|
+
from typing import Any
|
|
11
12
|
|
|
12
13
|
from eventkit import Event
|
|
13
14
|
|
|
@@ -15,7 +16,7 @@ from .connection import Connection
|
|
|
15
16
|
from .contract import Contract
|
|
16
17
|
from .decoder import Decoder
|
|
17
18
|
from .objects import ConnectionStats, WshEventData
|
|
18
|
-
from .util import
|
|
19
|
+
from .util import UNSET_DOUBLE, UNSET_INTEGER, dataclassAsTuple, getLoop, run
|
|
19
20
|
|
|
20
21
|
|
|
21
22
|
class Client:
|
|
@@ -127,8 +128,8 @@ class Client:
|
|
|
127
128
|
self._numBytesRecv = 0
|
|
128
129
|
self._numMsgRecv = 0
|
|
129
130
|
self._isThrottling = False
|
|
130
|
-
self._msgQ:
|
|
131
|
-
self._timeQ:
|
|
131
|
+
self._msgQ: deque[str] = deque()
|
|
132
|
+
self._timeQ: deque[float] = deque()
|
|
132
133
|
|
|
133
134
|
def serverVersion(self) -> int:
|
|
134
135
|
return self._serverVersion
|
|
@@ -171,7 +172,7 @@ class Client:
|
|
|
171
172
|
"""Update the next reqId to be at least ``minReqId``."""
|
|
172
173
|
self._reqIdSeq = max(self._reqIdSeq, minReqId)
|
|
173
174
|
|
|
174
|
-
def getAccounts(self) ->
|
|
175
|
+
def getAccounts(self) -> list[str]:
|
|
175
176
|
"""Get the list of account names that are under management."""
|
|
176
177
|
if not self.isReady():
|
|
177
178
|
raise ConnectionError("Not connected")
|
|
@@ -187,9 +188,7 @@ class Client:
|
|
|
187
188
|
"""
|
|
188
189
|
self.connectOptions = connectOptions.encode()
|
|
189
190
|
|
|
190
|
-
def connect(
|
|
191
|
-
self, host: str, port: int, clientId: int, timeout: Optional[float] = 2.0
|
|
192
|
-
):
|
|
191
|
+
def connect(self, host: str, port: int, clientId: int, timeout: float | None = 2.0):
|
|
193
192
|
"""
|
|
194
193
|
Connect to a running TWS or IB gateway application.
|
|
195
194
|
|
|
@@ -4,8 +4,6 @@ import asyncio
|
|
|
4
4
|
|
|
5
5
|
from eventkit import Event
|
|
6
6
|
|
|
7
|
-
from ib_async.util import getLoop
|
|
8
|
-
|
|
9
7
|
|
|
10
8
|
class Connection(asyncio.Protocol):
|
|
11
9
|
"""
|
|
@@ -35,7 +33,8 @@ class Connection(asyncio.Protocol):
|
|
|
35
33
|
self.disconnect()
|
|
36
34
|
await self.disconnected
|
|
37
35
|
self.reset()
|
|
38
|
-
|
|
36
|
+
# Use get_running_loop() directly for optimal performance in async context
|
|
37
|
+
loop = asyncio.get_running_loop()
|
|
39
38
|
self.transport, _ = await loop.create_connection(lambda: self, host, port)
|
|
40
39
|
|
|
41
40
|
def disconnect(self):
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
import datetime as dt
|
|
4
4
|
from dataclasses import dataclass, field
|
|
5
|
-
from typing import
|
|
5
|
+
from typing import NamedTuple, Optional
|
|
6
6
|
|
|
7
7
|
import ib_async.util as util
|
|
8
8
|
|
|
@@ -100,7 +100,7 @@ class Contract:
|
|
|
100
100
|
description: str = ""
|
|
101
101
|
issuerId: str = ""
|
|
102
102
|
comboLegsDescrip: str = ""
|
|
103
|
-
comboLegs:
|
|
103
|
+
comboLegs: list["ComboLeg"] = field(default_factory=list)
|
|
104
104
|
deltaNeutralContract: Optional["DeltaNeutralContract"] = None
|
|
105
105
|
|
|
106
106
|
@staticmethod
|
|
@@ -550,7 +550,7 @@ class TradingSession(NamedTuple):
|
|
|
550
550
|
|
|
551
551
|
@dataclass
|
|
552
552
|
class ContractDetails:
|
|
553
|
-
contract:
|
|
553
|
+
contract: Contract | None = None
|
|
554
554
|
marketName: str = ""
|
|
555
555
|
minTick: float = 0.0
|
|
556
556
|
orderTypes: str = ""
|
|
@@ -572,7 +572,7 @@ class ContractDetails:
|
|
|
572
572
|
underSymbol: str = ""
|
|
573
573
|
underSecType: str = ""
|
|
574
574
|
marketRuleIds: str = ""
|
|
575
|
-
secIdList:
|
|
575
|
+
secIdList: list[TagValue] = field(default_factory=list)
|
|
576
576
|
realExpirationDate: str = ""
|
|
577
577
|
lastTradeTime: str = ""
|
|
578
578
|
stockType: str = ""
|
|
@@ -596,13 +596,13 @@ class ContractDetails:
|
|
|
596
596
|
nextOptionPartial: bool = False
|
|
597
597
|
notes: str = ""
|
|
598
598
|
|
|
599
|
-
def tradingSessions(self) ->
|
|
599
|
+
def tradingSessions(self) -> list[TradingSession]:
|
|
600
600
|
return self._parseSessions(self.tradingHours)
|
|
601
601
|
|
|
602
|
-
def liquidSessions(self) ->
|
|
602
|
+
def liquidSessions(self) -> list[TradingSession]:
|
|
603
603
|
return self._parseSessions(self.liquidHours)
|
|
604
604
|
|
|
605
|
-
def _parseSessions(self, s: str) ->
|
|
605
|
+
def _parseSessions(self, s: str) -> list[TradingSession]:
|
|
606
606
|
"""Parse the IBKR session date range text format into native Python objects.
|
|
607
607
|
|
|
608
608
|
Note: The IBKR date range format looks like:
|
|
@@ -637,8 +637,8 @@ class ContractDetails:
|
|
|
637
637
|
|
|
638
638
|
@dataclass
|
|
639
639
|
class ContractDescription:
|
|
640
|
-
contract:
|
|
641
|
-
derivativeSecTypes:
|
|
640
|
+
contract: Contract | None = None
|
|
641
|
+
derivativeSecTypes: list[str] = field(default_factory=list)
|
|
642
642
|
|
|
643
643
|
|
|
644
644
|
@dataclass
|
|
@@ -32,7 +32,7 @@ from .objects import (
|
|
|
32
32
|
TickAttribLast,
|
|
33
33
|
)
|
|
34
34
|
from .order import Order, OrderComboLeg, OrderCondition, OrderState
|
|
35
|
-
from .util import
|
|
35
|
+
from .util import UNSET_DOUBLE, ZoneInfo, parseIBDatetime
|
|
36
36
|
from .wrapper import Wrapper
|
|
37
37
|
|
|
38
38
|
|
|
@@ -1,9 +1,12 @@
|
|
|
1
1
|
"""Access to account statement webservice."""
|
|
2
2
|
|
|
3
3
|
import logging
|
|
4
|
+
import os
|
|
4
5
|
import time
|
|
5
6
|
import xml.etree.ElementTree as et
|
|
6
7
|
from contextlib import suppress
|
|
8
|
+
from typing import Final
|
|
9
|
+
from urllib.parse import urlparse
|
|
7
10
|
from urllib.request import urlopen
|
|
8
11
|
|
|
9
12
|
from ib_async import util
|
|
@@ -11,6 +14,14 @@ from ib_async.objects import DynamicObject
|
|
|
11
14
|
|
|
12
15
|
_logger = logging.getLogger("ib_async.flexreport")
|
|
13
16
|
|
|
17
|
+
FLEXREPORT_URL: Final = (
|
|
18
|
+
"https://ndcdyn.interactivebrokers.com/AccountManagement/"
|
|
19
|
+
"FlexWebService/SendRequest?"
|
|
20
|
+
)
|
|
21
|
+
"""
|
|
22
|
+
https://www.interactivebrokers.com/campus/ibkr-api-page/flex-web-service/#flex-generate-report
|
|
23
|
+
"""
|
|
24
|
+
|
|
14
25
|
|
|
15
26
|
class FlexError(Exception):
|
|
16
27
|
pass
|
|
@@ -33,6 +44,8 @@ class FlexReport:
|
|
|
33
44
|
"""
|
|
34
45
|
Download a report by giving a valid ``token`` and ``queryId``,
|
|
35
46
|
or load from file by giving a valid ``path``.
|
|
47
|
+
|
|
48
|
+
To overwrite default URL, set env variable ``IB_FLEXREPORT_URL``.
|
|
36
49
|
"""
|
|
37
50
|
if token and queryId:
|
|
38
51
|
self.download(token, queryId)
|
|
@@ -65,13 +78,30 @@ class FlexReport:
|
|
|
65
78
|
"""Same as extract but return the result as a pandas DataFrame."""
|
|
66
79
|
return util.df(self.extract(topic, parseNumbers))
|
|
67
80
|
|
|
81
|
+
def get_url(self):
|
|
82
|
+
"""Generate flexreport URL."""
|
|
83
|
+
|
|
84
|
+
def is_valid_url(url: str) -> bool:
|
|
85
|
+
try:
|
|
86
|
+
result = urlparse(url)
|
|
87
|
+
# Must have scheme (http/https) and netloc (domain)
|
|
88
|
+
return all([result.scheme, result.netloc])
|
|
89
|
+
except Exception:
|
|
90
|
+
return False
|
|
91
|
+
|
|
92
|
+
_url = os.getenv("IB_FLEXREPORT_URL", FLEXREPORT_URL)
|
|
93
|
+
if is_valid_url(_url):
|
|
94
|
+
return _url
|
|
95
|
+
raise FlexError(
|
|
96
|
+
"Invalid URL, please check that env variable IB_FLEXREPORT_URL is set correctly."
|
|
97
|
+
)
|
|
98
|
+
|
|
68
99
|
def download(self, token, queryId):
|
|
69
100
|
"""Download report for the given ``token`` and ``queryId``."""
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
)
|
|
101
|
+
base_url = self.get_url()
|
|
102
|
+
query = f"t={token}&q={queryId}&v=3"
|
|
103
|
+
url = base_url + query
|
|
104
|
+
|
|
75
105
|
resp = urlopen(url)
|
|
76
106
|
data = resp.read()
|
|
77
107
|
|
|
@@ -94,7 +124,7 @@ class FlexReport:
|
|
|
94
124
|
|
|
95
125
|
while True:
|
|
96
126
|
time.sleep(1)
|
|
97
|
-
url = f"{baseUrl}?q={code}&t={token}"
|
|
127
|
+
url = f"{baseUrl}?q={code}&t={token}&v=3"
|
|
98
128
|
resp = urlopen(url)
|
|
99
129
|
self.data = resp.read()
|
|
100
130
|
self.root = et.fromstring(self.data)
|
|
@@ -5,8 +5,9 @@ import copy
|
|
|
5
5
|
import datetime
|
|
6
6
|
import logging
|
|
7
7
|
import time
|
|
8
|
-
from
|
|
9
|
-
from
|
|
8
|
+
from collections.abc import Awaitable, Iterator
|
|
9
|
+
from enum import Flag, auto
|
|
10
|
+
from typing import Any
|
|
10
11
|
|
|
11
12
|
from eventkit import Event
|
|
12
13
|
|
|
@@ -48,7 +49,6 @@ from ib_async.order import (
|
|
|
48
49
|
LimitOrder,
|
|
49
50
|
Order,
|
|
50
51
|
OrderState,
|
|
51
|
-
OrderStateNumeric,
|
|
52
52
|
OrderStatus,
|
|
53
53
|
StopOrder,
|
|
54
54
|
Trade,
|
|
@@ -623,7 +623,7 @@ class IB:
|
|
|
623
623
|
"""List of all executions from this session."""
|
|
624
624
|
return list(fill.execution for fill in self.wrapper.fills.values())
|
|
625
625
|
|
|
626
|
-
def ticker(self, contract: Contract) ->
|
|
626
|
+
def ticker(self, contract: Contract) -> Ticker | None:
|
|
627
627
|
"""
|
|
628
628
|
Get ticker of the given contract. It must have been requested before
|
|
629
629
|
with reqMktData with the same contract object. The ticker may not be
|
|
@@ -642,7 +642,7 @@ class IB:
|
|
|
642
642
|
"""Get a list of all tickers that have pending ticks or domTicks."""
|
|
643
643
|
return list(self.wrapper.pendingTickers)
|
|
644
644
|
|
|
645
|
-
def realtimeBars(self) -> list[
|
|
645
|
+
def realtimeBars(self) -> list[BarDataList | RealTimeBarList]:
|
|
646
646
|
"""
|
|
647
647
|
Get a list of all live updated bars. These can be 5 second realtime
|
|
648
648
|
bars or live updated historical bars.
|
|
@@ -815,7 +815,7 @@ class IB:
|
|
|
815
815
|
|
|
816
816
|
def cancelOrder(
|
|
817
817
|
self, order: Order, manualCancelOrderTime: str = ""
|
|
818
|
-
) ->
|
|
818
|
+
) -> Trade | None:
|
|
819
819
|
"""
|
|
820
820
|
Cancel the order and return the Trade it belongs to.
|
|
821
821
|
|
|
@@ -957,7 +957,7 @@ class IB:
|
|
|
957
957
|
"""
|
|
958
958
|
return self._run(self.reqCompletedOrdersAsync(apiOnly))
|
|
959
959
|
|
|
960
|
-
def reqExecutions(self, execFilter:
|
|
960
|
+
def reqExecutions(self, execFilter: ExecutionFilter | None = None) -> list[Fill]:
|
|
961
961
|
"""
|
|
962
962
|
It is recommended to use :meth:`.fills` or
|
|
963
963
|
:meth:`.executions` instead.
|
|
@@ -1167,7 +1167,7 @@ class IB:
|
|
|
1167
1167
|
def reqHistoricalData(
|
|
1168
1168
|
self,
|
|
1169
1169
|
contract: Contract,
|
|
1170
|
-
endDateTime:
|
|
1170
|
+
endDateTime: datetime.datetime | datetime.date | str | None,
|
|
1171
1171
|
durationStr: str,
|
|
1172
1172
|
barSizeSetting: str,
|
|
1173
1173
|
whatToShow: str,
|
|
@@ -1250,7 +1250,7 @@ class IB:
|
|
|
1250
1250
|
self,
|
|
1251
1251
|
contract: Contract,
|
|
1252
1252
|
numDays: int,
|
|
1253
|
-
endDateTime:
|
|
1253
|
+
endDateTime: datetime.datetime | datetime.date | str | None = "",
|
|
1254
1254
|
useRTH: bool = True,
|
|
1255
1255
|
) -> HistoricalSchedule:
|
|
1256
1256
|
"""
|
|
@@ -1275,14 +1275,14 @@ class IB:
|
|
|
1275
1275
|
def reqHistoricalTicks(
|
|
1276
1276
|
self,
|
|
1277
1277
|
contract: Contract,
|
|
1278
|
-
startDateTime:
|
|
1279
|
-
endDateTime:
|
|
1278
|
+
startDateTime: str | datetime.date,
|
|
1279
|
+
endDateTime: str | datetime.date,
|
|
1280
1280
|
numberOfTicks: int,
|
|
1281
1281
|
whatToShow: str,
|
|
1282
1282
|
useRth: bool,
|
|
1283
1283
|
ignoreSize: bool = False,
|
|
1284
1284
|
miscOptions: list[TagValue] = [],
|
|
1285
|
-
) ->
|
|
1285
|
+
) -> list:
|
|
1286
1286
|
"""
|
|
1287
1287
|
Request historical ticks. The time resolution of the ticks
|
|
1288
1288
|
is one second.
|
|
@@ -1837,8 +1837,8 @@ class IB:
|
|
|
1837
1837
|
self,
|
|
1838
1838
|
conId: int,
|
|
1839
1839
|
providerCodes: str,
|
|
1840
|
-
startDateTime:
|
|
1841
|
-
endDateTime:
|
|
1840
|
+
startDateTime: str | datetime.date,
|
|
1841
|
+
endDateTime: str | datetime.date,
|
|
1842
1842
|
totalResults: int,
|
|
1843
1843
|
historicalNewsOptions: list[TagValue] = [],
|
|
1844
1844
|
) -> HistoricalNews:
|
|
@@ -2029,7 +2029,7 @@ class IB:
|
|
|
2029
2029
|
host: str = "127.0.0.1",
|
|
2030
2030
|
port: int = 7497,
|
|
2031
2031
|
clientId: int = 1,
|
|
2032
|
-
timeout:
|
|
2032
|
+
timeout: float | None = 4,
|
|
2033
2033
|
readonly: bool = False,
|
|
2034
2034
|
account: str = "",
|
|
2035
2035
|
raiseSyncErrors: bool = False,
|
|
@@ -2276,7 +2276,7 @@ class IB:
|
|
|
2276
2276
|
return future
|
|
2277
2277
|
|
|
2278
2278
|
def reqExecutionsAsync(
|
|
2279
|
-
self, execFilter:
|
|
2279
|
+
self, execFilter: ExecutionFilter | None = None
|
|
2280
2280
|
) -> Awaitable[list[Fill]]:
|
|
2281
2281
|
execFilter = execFilter or ExecutionFilter()
|
|
2282
2282
|
reqId = self.client.getReqId()
|
|
@@ -2299,7 +2299,7 @@ class IB:
|
|
|
2299
2299
|
|
|
2300
2300
|
async def reqMatchingSymbolsAsync(
|
|
2301
2301
|
self, pattern: str
|
|
2302
|
-
) ->
|
|
2302
|
+
) -> list[ContractDescription] | None:
|
|
2303
2303
|
reqId = self.client.getReqId()
|
|
2304
2304
|
future = self.wrapper.startReq(reqId)
|
|
2305
2305
|
self.client.reqMatchingSymbols(reqId, pattern)
|
|
@@ -2312,7 +2312,7 @@ class IB:
|
|
|
2312
2312
|
|
|
2313
2313
|
async def reqMarketRuleAsync(
|
|
2314
2314
|
self, marketRuleId: int
|
|
2315
|
-
) ->
|
|
2315
|
+
) -> list[PriceIncrement] | None:
|
|
2316
2316
|
future = self.wrapper.startReq(f"marketRule-{marketRuleId}")
|
|
2317
2317
|
try:
|
|
2318
2318
|
self.client.reqMarketRule(marketRuleId)
|
|
@@ -2325,7 +2325,7 @@ class IB:
|
|
|
2325
2325
|
async def reqHistoricalDataAsync(
|
|
2326
2326
|
self,
|
|
2327
2327
|
contract: Contract,
|
|
2328
|
-
endDateTime:
|
|
2328
|
+
endDateTime: datetime.datetime | datetime.date | str | None,
|
|
2329
2329
|
durationStr: str,
|
|
2330
2330
|
barSizeSetting: str,
|
|
2331
2331
|
whatToShow: str,
|
|
@@ -2377,7 +2377,7 @@ class IB:
|
|
|
2377
2377
|
self,
|
|
2378
2378
|
contract: Contract,
|
|
2379
2379
|
numDays: int,
|
|
2380
|
-
endDateTime:
|
|
2380
|
+
endDateTime: datetime.datetime | datetime.date | str | None = "",
|
|
2381
2381
|
useRTH: bool = True,
|
|
2382
2382
|
) -> Awaitable[HistoricalSchedule]:
|
|
2383
2383
|
reqId = self.client.getReqId()
|
|
@@ -2401,14 +2401,14 @@ class IB:
|
|
|
2401
2401
|
def reqHistoricalTicksAsync(
|
|
2402
2402
|
self,
|
|
2403
2403
|
contract: Contract,
|
|
2404
|
-
startDateTime:
|
|
2405
|
-
endDateTime:
|
|
2404
|
+
startDateTime: str | datetime.date,
|
|
2405
|
+
endDateTime: str | datetime.date,
|
|
2406
2406
|
numberOfTicks: int,
|
|
2407
2407
|
whatToShow: str,
|
|
2408
2408
|
useRth: bool,
|
|
2409
2409
|
ignoreSize: bool = False,
|
|
2410
2410
|
miscOptions: list[TagValue] = [],
|
|
2411
|
-
) -> Awaitable[
|
|
2411
|
+
) -> Awaitable[list]:
|
|
2412
2412
|
reqId = self.client.getReqId()
|
|
2413
2413
|
future = self.wrapper.startReq(reqId, contract)
|
|
2414
2414
|
start = util.formatIBDatetime(startDateTime)
|
|
@@ -2502,7 +2502,7 @@ class IB:
|
|
|
2502
2502
|
optionPrice: float,
|
|
2503
2503
|
underPrice: float,
|
|
2504
2504
|
implVolOptions: list[TagValue] = [],
|
|
2505
|
-
) ->
|
|
2505
|
+
) -> OptionComputation | None:
|
|
2506
2506
|
reqId = self.client.getReqId()
|
|
2507
2507
|
future = self.wrapper.startReq(reqId, contract)
|
|
2508
2508
|
self.client.calculateImpliedVolatility(
|
|
@@ -2523,7 +2523,7 @@ class IB:
|
|
|
2523
2523
|
volatility: float,
|
|
2524
2524
|
underPrice: float,
|
|
2525
2525
|
optPrcOptions: list[TagValue] = [],
|
|
2526
|
-
) ->
|
|
2526
|
+
) -> OptionComputation | None:
|
|
2527
2527
|
reqId = self.client.getReqId()
|
|
2528
2528
|
future = self.wrapper.startReq(reqId, contract)
|
|
2529
2529
|
self.client.calculateOptionPrice(
|
|
@@ -2571,11 +2571,11 @@ class IB:
|
|
|
2571
2571
|
self,
|
|
2572
2572
|
conId: int,
|
|
2573
2573
|
providerCodes: str,
|
|
2574
|
-
startDateTime:
|
|
2575
|
-
endDateTime:
|
|
2574
|
+
startDateTime: str | datetime.date,
|
|
2575
|
+
endDateTime: str | datetime.date,
|
|
2576
2576
|
totalResults: int,
|
|
2577
2577
|
historicalNewsOptions: list[TagValue] = [],
|
|
2578
|
-
) ->
|
|
2578
|
+
) -> HistoricalNews | None:
|
|
2579
2579
|
reqId = self.client.getReqId()
|
|
2580
2580
|
|
|
2581
2581
|
future = self.wrapper.startReq(reqId)
|
|
@@ -3,8 +3,9 @@
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
5
|
from dataclasses import dataclass, field
|
|
6
|
-
from datetime import date as date_
|
|
7
|
-
from
|
|
6
|
+
from datetime import date as date_
|
|
7
|
+
from datetime import datetime, timezone, tzinfo
|
|
8
|
+
from typing import Any, NamedTuple
|
|
8
9
|
|
|
9
10
|
from eventkit import Event
|
|
10
11
|
|
|
@@ -95,7 +96,7 @@ class ExecutionFilter:
|
|
|
95
96
|
|
|
96
97
|
@dataclass
|
|
97
98
|
class BarData:
|
|
98
|
-
date:
|
|
99
|
+
date: date_ | datetime = EPOCH
|
|
99
100
|
open: float = 0.0
|
|
100
101
|
high: float = 0.0
|
|
101
102
|
low: float = 0.0
|
|
@@ -199,7 +200,7 @@ class HistoricalSchedule:
|
|
|
199
200
|
startDateTime: str = ""
|
|
200
201
|
endDateTime: str = ""
|
|
201
202
|
timeZone: str = ""
|
|
202
|
-
sessions:
|
|
203
|
+
sessions: list[HistoricalSession] = field(default_factory=list)
|
|
203
204
|
|
|
204
205
|
|
|
205
206
|
@dataclass
|
|
@@ -323,6 +324,37 @@ class Fill(NamedTuple):
|
|
|
323
324
|
time: datetime
|
|
324
325
|
|
|
325
326
|
|
|
327
|
+
@dataclass(slots=True, frozen=True)
|
|
328
|
+
class EfpData:
|
|
329
|
+
"""
|
|
330
|
+
Exchange for Physical (EFP) futures data.
|
|
331
|
+
|
|
332
|
+
EFP allows trading a position in a single stock for a position
|
|
333
|
+
in the corresponding single stock future.
|
|
334
|
+
"""
|
|
335
|
+
|
|
336
|
+
# Annualized basis points (financing rate comparable to broker rates)
|
|
337
|
+
basisPoints: float
|
|
338
|
+
|
|
339
|
+
# Basis points formatted as percentage string
|
|
340
|
+
formattedBasisPoints: str
|
|
341
|
+
|
|
342
|
+
# The implied Futures price
|
|
343
|
+
impliedFuture: float
|
|
344
|
+
|
|
345
|
+
# Number of days until the future's last trade date
|
|
346
|
+
holdDays: int
|
|
347
|
+
|
|
348
|
+
# Expiration date of the single stock future
|
|
349
|
+
futureLastTradeDate: str
|
|
350
|
+
|
|
351
|
+
# Dividend impact on the annualized basis points interest rate
|
|
352
|
+
dividendImpact: float
|
|
353
|
+
|
|
354
|
+
# Expected dividends until future expiration
|
|
355
|
+
dividendsToLastTradeDate: float
|
|
356
|
+
|
|
357
|
+
|
|
326
358
|
@dataclass(slots=True, frozen=True)
|
|
327
359
|
class OptionComputation:
|
|
328
360
|
tickAttrib: int
|
|
@@ -366,7 +398,7 @@ class OptionComputation:
|
|
|
366
398
|
)
|
|
367
399
|
|
|
368
400
|
def __mul__(self, other: int | float) -> OptionComputation:
|
|
369
|
-
if not isinstance(other,
|
|
401
|
+
if not isinstance(other, int | float):
|
|
370
402
|
raise TypeError(f"Cannot multiply {type(self)} and {type(other)}")
|
|
371
403
|
|
|
372
404
|
return self.__class__(
|
|
@@ -387,16 +419,16 @@ class OptionChain:
|
|
|
387
419
|
underlyingConId: int
|
|
388
420
|
tradingClass: str
|
|
389
421
|
multiplier: str
|
|
390
|
-
expirations:
|
|
391
|
-
strikes:
|
|
422
|
+
expirations: list[str]
|
|
423
|
+
strikes: list[float]
|
|
392
424
|
|
|
393
425
|
|
|
394
426
|
@dataclass(slots=True, frozen=True)
|
|
395
427
|
class Dividends:
|
|
396
|
-
past12Months:
|
|
397
|
-
next12Months:
|
|
398
|
-
nextDate:
|
|
399
|
-
nextAmount:
|
|
428
|
+
past12Months: float | None
|
|
429
|
+
next12Months: float | None
|
|
430
|
+
nextDate: date_ | None
|
|
431
|
+
nextAmount: float | None
|
|
400
432
|
|
|
401
433
|
|
|
402
434
|
@dataclass(slots=True, frozen=True)
|
|
@@ -453,7 +485,7 @@ class ConnectionStats:
|
|
|
453
485
|
numMsgSent: int
|
|
454
486
|
|
|
455
487
|
|
|
456
|
-
class BarDataList(
|
|
488
|
+
class BarDataList(list[BarData]):
|
|
457
489
|
"""
|
|
458
490
|
List of :class:`.BarData` that also stores all request parameters.
|
|
459
491
|
|
|
@@ -465,14 +497,14 @@ class BarDataList(List[BarData]):
|
|
|
465
497
|
|
|
466
498
|
reqId: int
|
|
467
499
|
contract: Contract
|
|
468
|
-
endDateTime:
|
|
500
|
+
endDateTime: datetime | date_ | str | None
|
|
469
501
|
durationStr: str
|
|
470
502
|
barSizeSetting: str
|
|
471
503
|
whatToShow: str
|
|
472
504
|
useRTH: bool
|
|
473
505
|
formatDate: int
|
|
474
506
|
keepUpToDate: bool
|
|
475
|
-
chartOptions:
|
|
507
|
+
chartOptions: list[TagValue]
|
|
476
508
|
|
|
477
509
|
def __init__(self, *args):
|
|
478
510
|
super().__init__(*args)
|
|
@@ -482,7 +514,7 @@ class BarDataList(List[BarData]):
|
|
|
482
514
|
return self is other
|
|
483
515
|
|
|
484
516
|
|
|
485
|
-
class RealTimeBarList(
|
|
517
|
+
class RealTimeBarList(list[RealTimeBar]):
|
|
486
518
|
"""
|
|
487
519
|
List of :class:`.RealTimeBar` that also stores all request parameters.
|
|
488
520
|
|
|
@@ -497,7 +529,7 @@ class RealTimeBarList(List[RealTimeBar]):
|
|
|
497
529
|
barSize: int
|
|
498
530
|
whatToShow: str
|
|
499
531
|
useRTH: bool
|
|
500
|
-
realTimeBarsOptions:
|
|
532
|
+
realTimeBarsOptions: list[TagValue]
|
|
501
533
|
|
|
502
534
|
def __init__(self, *args):
|
|
503
535
|
super().__init__(*args)
|
|
@@ -507,7 +539,7 @@ class RealTimeBarList(List[RealTimeBar]):
|
|
|
507
539
|
return self is other
|
|
508
540
|
|
|
509
541
|
|
|
510
|
-
class ScanDataList(
|
|
542
|
+
class ScanDataList(list[ScanData]):
|
|
511
543
|
"""
|
|
512
544
|
List of :class:`.ScanData` that also stores all request parameters.
|
|
513
545
|
|
|
@@ -517,8 +549,8 @@ class ScanDataList(List[ScanData]):
|
|
|
517
549
|
|
|
518
550
|
reqId: int
|
|
519
551
|
subscription: ScannerSubscription
|
|
520
|
-
scannerSubscriptionOptions:
|
|
521
|
-
scannerSubscriptionFilterOptions:
|
|
552
|
+
scannerSubscriptionOptions: list[TagValue]
|
|
553
|
+
scannerSubscriptionFilterOptions: list[TagValue]
|
|
522
554
|
|
|
523
555
|
def __init__(self, *args):
|
|
524
556
|
super().__init__(*args)
|
|
@@ -3,7 +3,6 @@
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
5
|
import dataclasses
|
|
6
|
-
|
|
7
6
|
from dataclasses import dataclass, field
|
|
8
7
|
from decimal import Decimal
|
|
9
8
|
from typing import ClassVar, NamedTuple
|
|
@@ -12,7 +11,7 @@ from eventkit import Event
|
|
|
12
11
|
|
|
13
12
|
from .contract import Contract, TagValue
|
|
14
13
|
from .objects import Fill, SoftDollarTier, TradeLogEntry
|
|
15
|
-
from .util import
|
|
14
|
+
from .util import UNSET_DOUBLE, UNSET_INTEGER, dataclassNonDefaults
|
|
16
15
|
|
|
17
16
|
|
|
18
17
|
@dataclass
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
from dataclasses import dataclass, field
|
|
4
4
|
from datetime import datetime
|
|
5
|
-
from typing import ClassVar
|
|
5
|
+
from typing import ClassVar
|
|
6
6
|
|
|
7
7
|
from eventkit import Event, Op
|
|
8
8
|
|
|
@@ -10,6 +10,7 @@ from ib_async.contract import Contract
|
|
|
10
10
|
from ib_async.objects import (
|
|
11
11
|
Dividends,
|
|
12
12
|
DOMLevel,
|
|
13
|
+
EfpData,
|
|
13
14
|
FundamentalRatios,
|
|
14
15
|
IBDefaults,
|
|
15
16
|
MktDepthData,
|
|
@@ -90,7 +91,7 @@ class Ticker:
|
|
|
90
91
|
rtHistVolatility: float = nan
|
|
91
92
|
rtVolume: float = nan
|
|
92
93
|
rtTradeVolume: float = nan
|
|
93
|
-
rtTime:
|
|
94
|
+
rtTime: datetime | None = None
|
|
94
95
|
avVolume: float = nan
|
|
95
96
|
tradeCount: float = nan
|
|
96
97
|
tradeRate: float = nan
|
|
@@ -109,21 +110,51 @@ class Ticker:
|
|
|
109
110
|
avOptionVolume: float = nan
|
|
110
111
|
histVolatility: float = nan
|
|
111
112
|
impliedVolatility: float = nan
|
|
112
|
-
|
|
113
|
-
|
|
113
|
+
openInterest: float = nan
|
|
114
|
+
lastRthTrade: float = nan
|
|
115
|
+
lastRegTime: str = ""
|
|
116
|
+
optionBidExch: str = ""
|
|
117
|
+
optionAskExch: str = ""
|
|
118
|
+
bondFactorMultiplier: float = nan
|
|
119
|
+
creditmanMarkPrice: float = nan
|
|
120
|
+
creditmanSlowMarkPrice: float = nan
|
|
121
|
+
delayedLastTimestamp: datetime | None = None
|
|
122
|
+
delayedHalted: float = nan
|
|
123
|
+
reutersMutualFunds: str = ""
|
|
124
|
+
etfNavClose: float = nan
|
|
125
|
+
etfNavPriorClose: float = nan
|
|
126
|
+
etfNavBid: float = nan
|
|
127
|
+
etfNavAsk: float = nan
|
|
128
|
+
etfNavLast: float = nan
|
|
129
|
+
etfFrozenNavLast: float = nan
|
|
130
|
+
etfNavHigh: float = nan
|
|
131
|
+
etfNavLow: float = nan
|
|
132
|
+
socialMarketAnalytics: str = ""
|
|
133
|
+
estimatedIpoMidpoint: float = nan
|
|
134
|
+
finalIpoLast: float = nan
|
|
135
|
+
dividends: Dividends | None = None
|
|
136
|
+
fundamentalRatios: FundamentalRatios | None = None
|
|
114
137
|
ticks: list[TickData] = field(default_factory=list)
|
|
115
|
-
tickByTicks: list[
|
|
116
|
-
|
|
117
|
-
|
|
138
|
+
tickByTicks: list[TickByTickAllLast | TickByTickBidAsk | TickByTickMidPoint] = (
|
|
139
|
+
field(default_factory=list)
|
|
140
|
+
)
|
|
118
141
|
domBids: list[DOMLevel] = field(default_factory=list)
|
|
119
142
|
domBidsDict: dict[int, DOMLevel] = field(default_factory=dict)
|
|
120
143
|
domAsks: list[DOMLevel] = field(default_factory=list)
|
|
121
144
|
domAsksDict: dict[int, DOMLevel] = field(default_factory=dict)
|
|
122
145
|
domTicks: list[MktDepthData] = field(default_factory=list)
|
|
123
|
-
bidGreeks:
|
|
124
|
-
askGreeks:
|
|
125
|
-
lastGreeks:
|
|
126
|
-
modelGreeks:
|
|
146
|
+
bidGreeks: OptionComputation | None = None
|
|
147
|
+
askGreeks: OptionComputation | None = None
|
|
148
|
+
lastGreeks: OptionComputation | None = None
|
|
149
|
+
modelGreeks: OptionComputation | None = None
|
|
150
|
+
custGreeks: OptionComputation | None = None
|
|
151
|
+
bidEfp: EfpData | None = None
|
|
152
|
+
askEfp: EfpData | None = None
|
|
153
|
+
lastEfp: EfpData | None = None
|
|
154
|
+
openEfp: EfpData | None = None
|
|
155
|
+
highEfp: EfpData | None = None
|
|
156
|
+
lowEfp: EfpData | None = None
|
|
157
|
+
closeEfp: EfpData | None = None
|
|
127
158
|
auctionVolume: float = nan
|
|
128
159
|
auctionPrice: float = nan
|
|
129
160
|
auctionImbalance: float = nan
|
|
@@ -195,6 +226,22 @@ class Ticker:
|
|
|
195
226
|
self.auctionPrice = self.defaults.unset
|
|
196
227
|
self.auctionImbalance = self.defaults.unset
|
|
197
228
|
self.regulatoryImbalance = self.defaults.unset
|
|
229
|
+
self.openInterest = self.defaults.unset
|
|
230
|
+
self.lastRthTrade = self.defaults.unset
|
|
231
|
+
self.bondFactorMultiplier = self.defaults.unset
|
|
232
|
+
self.creditmanMarkPrice = self.defaults.unset
|
|
233
|
+
self.creditmanSlowMarkPrice = self.defaults.unset
|
|
234
|
+
self.delayedHalted = self.defaults.unset
|
|
235
|
+
self.etfNavClose = self.defaults.unset
|
|
236
|
+
self.etfNavPriorClose = self.defaults.unset
|
|
237
|
+
self.etfNavBid = self.defaults.unset
|
|
238
|
+
self.etfNavAsk = self.defaults.unset
|
|
239
|
+
self.etfNavLast = self.defaults.unset
|
|
240
|
+
self.etfFrozenNavLast = self.defaults.unset
|
|
241
|
+
self.etfNavHigh = self.defaults.unset
|
|
242
|
+
self.etfNavLow = self.defaults.unset
|
|
243
|
+
self.estimatedIpoMidpoint = self.defaults.unset
|
|
244
|
+
self.finalIpoLast = self.defaults.unset
|
|
198
245
|
|
|
199
246
|
self.created = True
|
|
200
247
|
|
|
@@ -338,7 +385,7 @@ class Midpoints(Tickfilter):
|
|
|
338
385
|
|
|
339
386
|
@dataclass
|
|
340
387
|
class Bar:
|
|
341
|
-
time:
|
|
388
|
+
time: datetime | None
|
|
342
389
|
open: float = nan
|
|
343
390
|
high: float = nan
|
|
344
391
|
low: float = nan
|
|
@@ -389,7 +436,7 @@ class TimeBars(Op):
|
|
|
389
436
|
def _on_timer(self, time):
|
|
390
437
|
if self.bars:
|
|
391
438
|
bar = self.bars[-1]
|
|
392
|
-
if
|
|
439
|
+
if isNan(bar.close) and len(self.bars) > 1:
|
|
393
440
|
bar.open = bar.high = bar.low = bar.close = self.bars[-2].close
|
|
394
441
|
|
|
395
442
|
self.bars.updateEvent.emit(self.bars, True)
|
|
@@ -2,34 +2,22 @@
|
|
|
2
2
|
|
|
3
3
|
import asyncio
|
|
4
4
|
import datetime as dt
|
|
5
|
-
import functools
|
|
6
5
|
import logging
|
|
7
6
|
import math
|
|
8
7
|
import signal
|
|
9
8
|
import sys
|
|
10
9
|
import time
|
|
10
|
+
from collections.abc import AsyncIterator, Awaitable, Callable, Iterator
|
|
11
11
|
from dataclasses import fields, is_dataclass
|
|
12
12
|
from typing import (
|
|
13
13
|
Any,
|
|
14
|
-
AsyncIterator,
|
|
15
|
-
Awaitable,
|
|
16
|
-
Callable,
|
|
17
14
|
Final,
|
|
18
|
-
Iterator,
|
|
19
|
-
List,
|
|
20
|
-
Optional,
|
|
21
15
|
TypeAlias,
|
|
22
|
-
Union,
|
|
23
16
|
)
|
|
17
|
+
from zoneinfo import ZoneInfo
|
|
24
18
|
|
|
25
19
|
import eventkit as ev
|
|
26
20
|
|
|
27
|
-
try:
|
|
28
|
-
from zoneinfo import ZoneInfo
|
|
29
|
-
except ImportError:
|
|
30
|
-
from backports.zoneinfo import ZoneInfo # type: ignore
|
|
31
|
-
|
|
32
|
-
|
|
33
21
|
globalErrorEvent = ev.Event()
|
|
34
22
|
"""
|
|
35
23
|
Event to emit global exceptions.
|
|
@@ -42,7 +30,7 @@ UNSET_DOUBLE: Final = sys.float_info.max
|
|
|
42
30
|
Time_t: TypeAlias = dt.time | dt.datetime
|
|
43
31
|
|
|
44
32
|
|
|
45
|
-
def df(objs, labels:
|
|
33
|
+
def df(objs, labels: list[str] | None = None):
|
|
46
34
|
"""
|
|
47
35
|
Create pandas DataFrame from the sequence of same-type objects.
|
|
48
36
|
|
|
@@ -169,10 +157,10 @@ def tree(obj):
|
|
|
169
157
|
Convert object to a tree of lists, dicts and simple values.
|
|
170
158
|
The result can be serialized to JSON.
|
|
171
159
|
"""
|
|
172
|
-
if isinstance(obj,
|
|
160
|
+
if isinstance(obj, bool | int | float | str | bytes):
|
|
173
161
|
return obj
|
|
174
162
|
|
|
175
|
-
if isinstance(obj,
|
|
163
|
+
if isinstance(obj, dt.date | dt.time):
|
|
176
164
|
return obj.isoformat()
|
|
177
165
|
|
|
178
166
|
if isinstance(obj, dict):
|
|
@@ -181,7 +169,7 @@ def tree(obj):
|
|
|
181
169
|
if isnamedtupleinstance(obj):
|
|
182
170
|
return {f: tree(getattr(obj, f)) for f in obj._fields}
|
|
183
171
|
|
|
184
|
-
if isinstance(obj,
|
|
172
|
+
if isinstance(obj, list | tuple | set):
|
|
185
173
|
return [tree(i) for i in obj]
|
|
186
174
|
|
|
187
175
|
if is_dataclass(obj):
|
|
@@ -299,7 +287,7 @@ def formatSI(n: float) -> str:
|
|
|
299
287
|
log = int(math.floor(math.log10(n)))
|
|
300
288
|
i, j = divmod(log, 3)
|
|
301
289
|
for _try in range(2):
|
|
302
|
-
templ = "%.{
|
|
290
|
+
templ = f"%.{2 - j}f"
|
|
303
291
|
val = templ % (n * 10 ** (-3 * i))
|
|
304
292
|
if val != "1000":
|
|
305
293
|
break
|
|
@@ -325,7 +313,7 @@ class timeit:
|
|
|
325
313
|
print(self.title + " took " + formatSI(time.time() - self.t0) + "s")
|
|
326
314
|
|
|
327
315
|
|
|
328
|
-
def run(*awaitables: Awaitable, timeout:
|
|
316
|
+
def run(*awaitables: Awaitable, timeout: float | None = None):
|
|
329
317
|
"""
|
|
330
318
|
By default run the event loop forever.
|
|
331
319
|
|
|
@@ -343,10 +331,7 @@ def run(*awaitables: Awaitable, timeout: Optional[float] = None):
|
|
|
343
331
|
|
|
344
332
|
loop.run_forever()
|
|
345
333
|
result = None
|
|
346
|
-
|
|
347
|
-
all_tasks = asyncio.all_tasks(loop) # type: ignore
|
|
348
|
-
else:
|
|
349
|
-
all_tasks = asyncio.Task.all_tasks() # type: ignore
|
|
334
|
+
all_tasks = asyncio.all_tasks(loop) # type: ignore
|
|
350
335
|
|
|
351
336
|
if all_tasks:
|
|
352
337
|
# cancel pending tasks
|
|
@@ -364,7 +349,8 @@ def run(*awaitables: Awaitable, timeout: Optional[float] = None):
|
|
|
364
349
|
|
|
365
350
|
if timeout:
|
|
366
351
|
future = asyncio.wait_for(future, timeout)
|
|
367
|
-
|
|
352
|
+
# Pass loop explicitly to avoid deprecation warnings in Python 3.10+
|
|
353
|
+
task = asyncio.ensure_future(future, loop=loop)
|
|
368
354
|
|
|
369
355
|
def onError(_):
|
|
370
356
|
task.cancel()
|
|
@@ -495,13 +481,42 @@ def patchAsyncio():
|
|
|
495
481
|
nest_asyncio.apply()
|
|
496
482
|
|
|
497
483
|
|
|
498
|
-
@functools.cache
|
|
499
484
|
def getLoop():
|
|
500
|
-
"""
|
|
485
|
+
"""
|
|
486
|
+
Get asyncio event loop with smart fallback handling.
|
|
487
|
+
|
|
488
|
+
This function is designed for use in synchronous contexts or when the
|
|
489
|
+
execution context is unknown. It will:
|
|
490
|
+
1. Try to get the currently running event loop (if in async context)
|
|
491
|
+
2. Fall back to getting the current thread's event loop via policy
|
|
492
|
+
3. Create a new event loop if none exists or if the existing one is closed
|
|
493
|
+
|
|
494
|
+
For performance-critical async code paths, prefer using
|
|
495
|
+
asyncio.get_running_loop() directly instead of this function.
|
|
496
|
+
|
|
497
|
+
Note: This function does NOT cache the loop to avoid stale loop bugs
|
|
498
|
+
when loops are closed and recreated (e.g., in testing, Jupyter notebooks).
|
|
499
|
+
"""
|
|
501
500
|
try:
|
|
502
|
-
#
|
|
501
|
+
# Fast path: we're in an async context (coroutine or callback)
|
|
503
502
|
loop = asyncio.get_running_loop()
|
|
503
|
+
return loop
|
|
504
|
+
except RuntimeError:
|
|
505
|
+
pass
|
|
506
|
+
|
|
507
|
+
# We're in a sync context or no loop is running
|
|
508
|
+
# Use the event loop policy to get the loop for this thread
|
|
509
|
+
# This avoids deprecation warnings from get_event_loop() in Python 3.10+
|
|
510
|
+
try:
|
|
511
|
+
loop = asyncio.get_event_loop_policy().get_event_loop()
|
|
504
512
|
except RuntimeError:
|
|
513
|
+
# No event loop exists for this thread, create one
|
|
514
|
+
loop = asyncio.new_event_loop()
|
|
515
|
+
asyncio.set_event_loop(loop)
|
|
516
|
+
return loop
|
|
517
|
+
|
|
518
|
+
# Check if the loop we got is closed - if so, create a new one
|
|
519
|
+
if loop.is_closed():
|
|
505
520
|
loop = asyncio.new_event_loop()
|
|
506
521
|
asyncio.set_event_loop(loop)
|
|
507
522
|
|
|
@@ -556,7 +571,7 @@ def useQt(qtLib: str = "PyQt5", period: float = 0.01):
|
|
|
556
571
|
qt_step()
|
|
557
572
|
|
|
558
573
|
|
|
559
|
-
def formatIBDatetime(t:
|
|
574
|
+
def formatIBDatetime(t: dt.date | dt.datetime | str | None) -> str:
|
|
560
575
|
"""Format date or datetime to string that IB uses."""
|
|
561
576
|
if not t:
|
|
562
577
|
s = ""
|
|
@@ -575,7 +590,7 @@ def formatIBDatetime(t: Union[dt.date, dt.datetime, str, None]) -> str:
|
|
|
575
590
|
return s
|
|
576
591
|
|
|
577
592
|
|
|
578
|
-
def parseIBDatetime(s: str) ->
|
|
593
|
+
def parseIBDatetime(s: str) -> dt.date | dt.datetime:
|
|
579
594
|
"""Parse string in IB date or datetime format to datetime."""
|
|
580
595
|
if len(s) == 8:
|
|
581
596
|
# YYYYmmdd
|
|
@@ -3,12 +3,11 @@
|
|
|
3
3
|
import asyncio
|
|
4
4
|
import logging
|
|
5
5
|
import time
|
|
6
|
-
|
|
7
6
|
from collections import defaultdict
|
|
8
7
|
from contextlib import suppress
|
|
9
8
|
from dataclasses import dataclass, field
|
|
10
9
|
from datetime import datetime
|
|
11
|
-
from typing import
|
|
10
|
+
from typing import TYPE_CHECKING, Any, Final, TypeAlias, cast
|
|
12
11
|
|
|
13
12
|
from ib_async.contract import (
|
|
14
13
|
Contract,
|
|
@@ -25,6 +24,7 @@ from ib_async.objects import (
|
|
|
25
24
|
DepthMktDataDescription,
|
|
26
25
|
Dividends,
|
|
27
26
|
DOMLevel,
|
|
27
|
+
EfpData,
|
|
28
28
|
Execution,
|
|
29
29
|
FamilyCode,
|
|
30
30
|
Fill,
|
|
@@ -63,13 +63,13 @@ from ib_async.objects import (
|
|
|
63
63
|
from ib_async.order import Order, OrderState, OrderStatus, Trade
|
|
64
64
|
from ib_async.ticker import Ticker
|
|
65
65
|
from ib_async.util import (
|
|
66
|
+
UNSET_DOUBLE,
|
|
67
|
+
UNSET_INTEGER,
|
|
66
68
|
dataclassAsDict,
|
|
67
69
|
dataclassUpdate,
|
|
68
70
|
getLoop,
|
|
69
71
|
globalErrorEvent,
|
|
70
72
|
parseIBDatetime,
|
|
71
|
-
UNSET_DOUBLE,
|
|
72
|
-
UNSET_INTEGER,
|
|
73
73
|
)
|
|
74
74
|
|
|
75
75
|
if TYPE_CHECKING:
|
|
@@ -101,6 +101,19 @@ PRICE_TICK_MAP: Final[TickDict] = {
|
|
|
101
101
|
51: "askYield",
|
|
102
102
|
104: "askYield",
|
|
103
103
|
52: "lastYield",
|
|
104
|
+
57: "lastRthTrade",
|
|
105
|
+
78: "creditmanMarkPrice",
|
|
106
|
+
79: "creditmanSlowMarkPrice",
|
|
107
|
+
92: "etfNavClose",
|
|
108
|
+
93: "etfNavPriorClose",
|
|
109
|
+
94: "etfNavBid",
|
|
110
|
+
95: "etfNavAsk",
|
|
111
|
+
96: "etfNavLast",
|
|
112
|
+
97: "etfFrozenNavLast",
|
|
113
|
+
98: "etfNavHigh",
|
|
114
|
+
99: "etfNavLow",
|
|
115
|
+
101: "estimatedIpoMidpoint",
|
|
116
|
+
102: "finalIpoLast",
|
|
104
117
|
}
|
|
105
118
|
|
|
106
119
|
|
|
@@ -111,6 +124,7 @@ SIZE_TICK_MAP: Final[TickDict] = {
|
|
|
111
124
|
64: "volumeRate5Min",
|
|
112
125
|
65: "volumeRate10Min",
|
|
113
126
|
21: "avVolume",
|
|
127
|
+
22: "openInterest",
|
|
114
128
|
27: "callOpenInterest",
|
|
115
129
|
28: "putOpenInterest",
|
|
116
130
|
29: "callVolume",
|
|
@@ -133,6 +147,8 @@ GENERIC_TICK_MAP: Final[TickDict] = {
|
|
|
133
147
|
55: "tradeRate",
|
|
134
148
|
56: "volumeRate",
|
|
135
149
|
58: "rtHistVolatility",
|
|
150
|
+
60: "bondFactorMultiplier",
|
|
151
|
+
90: "delayedHalted",
|
|
136
152
|
}
|
|
137
153
|
|
|
138
154
|
GREEKS_TICK_MAP: Final[TickDict] = {
|
|
@@ -144,6 +160,38 @@ GREEKS_TICK_MAP: Final[TickDict] = {
|
|
|
144
160
|
82: "lastGreeks",
|
|
145
161
|
13: "modelGreeks",
|
|
146
162
|
83: "modelGreeks",
|
|
163
|
+
53: "custGreeks",
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
EFP_TICK_MAP: Final[TickDict] = {
|
|
167
|
+
38: "bidEfp",
|
|
168
|
+
39: "askEfp",
|
|
169
|
+
40: "lastEfp",
|
|
170
|
+
41: "openEfp",
|
|
171
|
+
42: "highEfp",
|
|
172
|
+
43: "lowEfp",
|
|
173
|
+
44: "closeEfp",
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
STRING_TICK_MAP: Final[TickDict] = {
|
|
177
|
+
25: "optionBidExch",
|
|
178
|
+
26: "optionAskExch",
|
|
179
|
+
32: "bidExchange",
|
|
180
|
+
33: "askExchange",
|
|
181
|
+
84: "lastExchange",
|
|
182
|
+
85: "lastRegTime",
|
|
183
|
+
91: "reutersMutualFunds",
|
|
184
|
+
100: "socialMarketAnalytics",
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
TIMESTAMP_TICK_MAP: Final[TickDict] = {
|
|
188
|
+
45: "lastTimestamp",
|
|
189
|
+
88: "delayedLastTimestamp",
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
RT_VOLUME_TICK_MAP: Final[TickDict] = {
|
|
193
|
+
48: "rtVolume",
|
|
194
|
+
77: "rtTradeVolume",
|
|
147
195
|
}
|
|
148
196
|
|
|
149
197
|
|
|
@@ -207,7 +255,7 @@ class Wrapper:
|
|
|
207
255
|
reqId2Ticker: dict[int, Ticker] = field(init=False)
|
|
208
256
|
""" reqId -> Ticker """
|
|
209
257
|
|
|
210
|
-
ticker2ReqId: dict[
|
|
258
|
+
ticker2ReqId: dict[int | str, dict[Ticker, int]] = field(init=False)
|
|
211
259
|
""" tickType -> Ticker -> reqId """
|
|
212
260
|
|
|
213
261
|
reqId2Subscriber: dict[int, Any] = field(init=False)
|
|
@@ -350,7 +398,7 @@ class Wrapper:
|
|
|
350
398
|
else:
|
|
351
399
|
future.set_exception(result)
|
|
352
400
|
|
|
353
|
-
def startTicker(self, reqId: int, contract: Contract, tickType:
|
|
401
|
+
def startTicker(self, reqId: int, contract: Contract, tickType: int | str):
|
|
354
402
|
"""
|
|
355
403
|
Start a tick request that has the reqId associated with the contract.
|
|
356
404
|
Return the ticker.
|
|
@@ -365,7 +413,7 @@ class Wrapper:
|
|
|
365
413
|
self.ticker2ReqId[tickType][ticker] = reqId
|
|
366
414
|
return ticker
|
|
367
415
|
|
|
368
|
-
def endTicker(self, ticker: Ticker, tickType:
|
|
416
|
+
def endTicker(self, ticker: Ticker, tickType: int | str):
|
|
369
417
|
reqId = self.ticker2ReqId[tickType].pop(ticker, 0)
|
|
370
418
|
self._reqId2Contract.pop(reqId, None)
|
|
371
419
|
return reqId
|
|
@@ -418,6 +466,50 @@ class Wrapper:
|
|
|
418
466
|
self.setTimeout(0)
|
|
419
467
|
self.ib.timeoutEvent.emit(diff)
|
|
420
468
|
|
|
469
|
+
# Helper methods for tick processing
|
|
470
|
+
|
|
471
|
+
def _processTimestampTick(self, ticker: Ticker, fieldName: str, value: str):
|
|
472
|
+
"""Convert timestamp string to datetime and set on ticker field."""
|
|
473
|
+
timestamp = int(value)
|
|
474
|
+
# Only populate if timestamp isn't '0' (we don't want to report "last trade: 20,000 days ago")
|
|
475
|
+
if timestamp:
|
|
476
|
+
setattr(
|
|
477
|
+
ticker,
|
|
478
|
+
fieldName,
|
|
479
|
+
datetime.fromtimestamp(timestamp, self.defaultTimezone),
|
|
480
|
+
)
|
|
481
|
+
|
|
482
|
+
def _processRtVolumeTick(
|
|
483
|
+
self, ticker: Ticker, tickType: int, value: str
|
|
484
|
+
) -> tuple[float, float] | None:
|
|
485
|
+
"""
|
|
486
|
+
Parse RT Volume or RT Trade Volume tick.
|
|
487
|
+
|
|
488
|
+
Format: price;size;ms since epoch;total volume;VWAP;single trade
|
|
489
|
+
Example: 701.28;1;1348075471534;67854;701.46918464;true
|
|
490
|
+
|
|
491
|
+
Returns (price, size) tuple if valid, None otherwise.
|
|
492
|
+
"""
|
|
493
|
+
priceStr, sizeStr, rtTime, volume, vwap, _ = value.split(";")
|
|
494
|
+
|
|
495
|
+
if volume:
|
|
496
|
+
# Set volume field based on tick type
|
|
497
|
+
volumeField = RT_VOLUME_TICK_MAP[tickType]
|
|
498
|
+
setattr(ticker, volumeField, float(volume))
|
|
499
|
+
|
|
500
|
+
if vwap:
|
|
501
|
+
ticker.vwap = float(vwap)
|
|
502
|
+
|
|
503
|
+
if rtTime:
|
|
504
|
+
ticker.rtTime = datetime.fromtimestamp(
|
|
505
|
+
int(rtTime) / 1000, self.defaultTimezone
|
|
506
|
+
)
|
|
507
|
+
|
|
508
|
+
if priceStr == "":
|
|
509
|
+
return None
|
|
510
|
+
|
|
511
|
+
return (float(priceStr), float(sizeStr))
|
|
512
|
+
|
|
421
513
|
# wrapper methods
|
|
422
514
|
|
|
423
515
|
def connectAck(self):
|
|
@@ -657,7 +749,7 @@ class Wrapper:
|
|
|
657
749
|
key = self.orderKey(clientId, orderId, permId)
|
|
658
750
|
trade = self.trades.get(key)
|
|
659
751
|
if trade:
|
|
660
|
-
msg:
|
|
752
|
+
msg: str | None
|
|
661
753
|
oldStatus = trade.orderStatus.status
|
|
662
754
|
new = dict(
|
|
663
755
|
status=status,
|
|
@@ -1107,20 +1199,12 @@ class Wrapper:
|
|
|
1107
1199
|
return
|
|
1108
1200
|
|
|
1109
1201
|
try:
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
ticker
|
|
1116
|
-
elif tickType == 45:
|
|
1117
|
-
timestamp = int(value)
|
|
1118
|
-
|
|
1119
|
-
# only populate if timestamp isn't '0' (we don't want to report "last trade: 20,000 days ago")
|
|
1120
|
-
if timestamp:
|
|
1121
|
-
ticker.lastTimestamp = datetime.fromtimestamp(
|
|
1122
|
-
timestamp, self.defaultTimezone
|
|
1123
|
-
)
|
|
1202
|
+
# Simple string assignments (O(1) dict lookup)
|
|
1203
|
+
if tickType in STRING_TICK_MAP:
|
|
1204
|
+
setattr(ticker, STRING_TICK_MAP[tickType], value)
|
|
1205
|
+
elif tickType in TIMESTAMP_TICK_MAP:
|
|
1206
|
+
# Timestamp conversion (O(1) dict lookup)
|
|
1207
|
+
self._processTimestampTick(ticker, TIMESTAMP_TICK_MAP[tickType], value)
|
|
1124
1208
|
elif tickType == 47:
|
|
1125
1209
|
# https://web.archive.org/web/20200725010343/https://interactivebrokers.github.io/tws-api/fundamental_ratios_tags.html
|
|
1126
1210
|
d = dict(
|
|
@@ -1135,40 +1219,17 @@ class Wrapper:
|
|
|
1135
1219
|
d[k] = float(v) # type: ignore
|
|
1136
1220
|
d[k] = int(v) # type: ignore
|
|
1137
1221
|
ticker.fundamentalRatios = FundamentalRatios(**d)
|
|
1138
|
-
elif tickType in
|
|
1139
|
-
# RT Volume or RT Trade Volume
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
if vwap:
|
|
1151
|
-
ticker.vwap = float(vwap)
|
|
1152
|
-
|
|
1153
|
-
if rtTime:
|
|
1154
|
-
ticker.rtTime = datetime.fromtimestamp(
|
|
1155
|
-
int(rtTime) / 1000, self.defaultTimezone
|
|
1156
|
-
)
|
|
1157
|
-
|
|
1158
|
-
if priceStr == "":
|
|
1159
|
-
return
|
|
1160
|
-
|
|
1161
|
-
price = float(priceStr)
|
|
1162
|
-
size = float(sizeStr)
|
|
1163
|
-
|
|
1164
|
-
ticker.prevLast = ticker.last
|
|
1165
|
-
ticker.prevLastSize = ticker.lastSize
|
|
1166
|
-
|
|
1167
|
-
ticker.last = price
|
|
1168
|
-
ticker.lastSize = size
|
|
1169
|
-
|
|
1170
|
-
tick = TickData(self.lastTime, tickType, price, size)
|
|
1171
|
-
ticker.ticks.append(tick)
|
|
1222
|
+
elif tickType in RT_VOLUME_TICK_MAP:
|
|
1223
|
+
# RT Volume or RT Trade Volume (O(1) dict lookup + helper)
|
|
1224
|
+
result = self._processRtVolumeTick(ticker, tickType, value)
|
|
1225
|
+
if result:
|
|
1226
|
+
price, size = result
|
|
1227
|
+
ticker.prevLast = ticker.last
|
|
1228
|
+
ticker.prevLastSize = ticker.lastSize
|
|
1229
|
+
ticker.last = price
|
|
1230
|
+
ticker.lastSize = size
|
|
1231
|
+
tick = TickData(self.lastTime, tickType, price, size)
|
|
1232
|
+
ticker.ticks.append(tick)
|
|
1172
1233
|
elif tickType == 59:
|
|
1173
1234
|
# Dividend tick:
|
|
1174
1235
|
# https://interactivebrokers.github.io/tws-api/tick_types.html#ib_dividends
|
|
@@ -1467,7 +1528,26 @@ class Wrapper:
|
|
|
1467
1528
|
dividendImpact: float,
|
|
1468
1529
|
dividendsToLastTradeDate: float,
|
|
1469
1530
|
):
|
|
1470
|
-
|
|
1531
|
+
ticker = self.reqId2Ticker.get(reqId)
|
|
1532
|
+
if not ticker:
|
|
1533
|
+
return
|
|
1534
|
+
|
|
1535
|
+
# Create EFP data object with all available information
|
|
1536
|
+
# Note: totalDividends parameter is actually the implied future price per IBKR docs
|
|
1537
|
+
efpData = EfpData(
|
|
1538
|
+
basisPoints=basisPoints,
|
|
1539
|
+
formattedBasisPoints=formattedBasisPoints,
|
|
1540
|
+
impliedFuture=totalDividends,
|
|
1541
|
+
holdDays=holdDays,
|
|
1542
|
+
futureLastTradeDate=futureLastTradeDate,
|
|
1543
|
+
dividendImpact=dividendImpact,
|
|
1544
|
+
dividendsToLastTradeDate=dividendsToLastTradeDate,
|
|
1545
|
+
)
|
|
1546
|
+
|
|
1547
|
+
# Store in appropriate field based on tick type (O(1) dict lookup)
|
|
1548
|
+
if tickType in EFP_TICK_MAP:
|
|
1549
|
+
setattr(ticker, EFP_TICK_MAP[tickType], efpData)
|
|
1550
|
+
self.pendingTickers.add(ticker)
|
|
1471
1551
|
|
|
1472
1552
|
def historicalSchedule(
|
|
1473
1553
|
self,
|
|
@@ -1,6 +1,13 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "ib_async"
|
|
3
|
+
requires-python = ">=3.10"
|
|
4
|
+
version = "2.1.0"
|
|
5
|
+
license = "BSD"
|
|
6
|
+
license-files = ["LICENSE"]
|
|
7
|
+
|
|
1
8
|
[tool.poetry]
|
|
2
9
|
name = "ib_async"
|
|
3
|
-
version = "2.0
|
|
10
|
+
version = "2.1.0"
|
|
4
11
|
description = "Python sync/async framework for Interactive Brokers API"
|
|
5
12
|
authors = ["Ewald de Wit"]
|
|
6
13
|
maintainers = ["Matt Stancliff <matt@matt.sh>"]
|
|
@@ -12,7 +19,6 @@ classifiers = [
|
|
|
12
19
|
"Development Status :: 5 - Production/Stable",
|
|
13
20
|
"Intended Audience :: Developers",
|
|
14
21
|
"Topic :: Office/Business :: Financial :: Investment",
|
|
15
|
-
"License :: OSI Approved :: BSD License",
|
|
16
22
|
"Programming Language :: Python :: 3.10",
|
|
17
23
|
"Programming Language :: Python :: 3.11",
|
|
18
24
|
"Programming Language :: Python :: 3.12",
|
|
@@ -26,6 +32,7 @@ python = ">=3.10"
|
|
|
26
32
|
aeventkit = "^2.1.0"
|
|
27
33
|
# aeventkit = { path = "../eventkit", develop = true }
|
|
28
34
|
nest_asyncio = "*"
|
|
35
|
+
tzdata = "^2025.2"
|
|
29
36
|
|
|
30
37
|
[tool.poetry.urls]
|
|
31
38
|
"Bug Tracker" = "https://github.com/ib-api-reloaded/ib_async/issues"
|
|
@@ -63,3 +70,20 @@ asyncio_mode="auto"
|
|
|
63
70
|
[build-system]
|
|
64
71
|
requires = ["poetry-core"]
|
|
65
72
|
build-backend = "poetry.core.masonry.api"
|
|
73
|
+
|
|
74
|
+
[tool.ruff]
|
|
75
|
+
target-version = "py310"
|
|
76
|
+
exclude = [
|
|
77
|
+
"notebooks/",
|
|
78
|
+
"upstream_api_architecture/",
|
|
79
|
+
"examples/",
|
|
80
|
+
]
|
|
81
|
+
|
|
82
|
+
[tool.ruff.lint]
|
|
83
|
+
extend-select = [
|
|
84
|
+
# convert legacy python syntax to modern syntax
|
|
85
|
+
"UP",
|
|
86
|
+
# isort imports
|
|
87
|
+
"I",
|
|
88
|
+
]
|
|
89
|
+
ignore = ["E402"] # Ignore Module level import not at top of file
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|