pytdxdata 0.6.2__tar.gz → 0.6.4__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.
- {pytdxdata-0.6.2 → pytdxdata-0.6.4}/PKG-INFO +1 -1
- {pytdxdata-0.6.2 → pytdxdata-0.6.4}/pyproject.toml +1 -1
- {pytdxdata-0.6.2 → pytdxdata-0.6.4}/pyproject.toml.orig +1 -1
- {pytdxdata-0.6.2 → pytdxdata-0.6.4}/src/pytdxdata/__init__.py +1 -1
- {pytdxdata-0.6.2 → pytdxdata-0.6.4}/src/pytdxdata/api.py +97 -22
- {pytdxdata-0.6.2 → pytdxdata-0.6.4}/src/pytdxdata/models/__init__.py +24 -4
- pytdxdata-0.6.4/src/pytdxdata/pool/ex_pool.py +168 -0
- {pytdxdata-0.6.2 → pytdxdata-0.6.4}/src/pytdxdata/protocol/commands/quotes.py +13 -6
- {pytdxdata-0.6.2 → pytdxdata-0.6.4}/src/pytdxdata/protocol/commands/transaction.py +4 -1
- {pytdxdata-0.6.2 → pytdxdata-0.6.4}/src/pytdxdata/scheduler/paginator.py +7 -3
- {pytdxdata-0.6.2 → pytdxdata-0.6.4}/src/pytdxdata/servers.json +197 -140
- pytdxdata-0.6.2/src/pytdxdata/pool/ex_pool.py +0 -119
- {pytdxdata-0.6.2 → pytdxdata-0.6.4}/LICENSE +0 -0
- {pytdxdata-0.6.2 → pytdxdata-0.6.4}/README.md +0 -0
- {pytdxdata-0.6.2 → pytdxdata-0.6.4}/src/pytdxdata/_binary.py +0 -0
- {pytdxdata-0.6.2 → pytdxdata-0.6.4}/src/pytdxdata/cache/__init__.py +0 -0
- {pytdxdata-0.6.2 → pytdxdata-0.6.4}/src/pytdxdata/cache/disk.py +0 -0
- {pytdxdata-0.6.2 → pytdxdata-0.6.4}/src/pytdxdata/cache/key.py +0 -0
- {pytdxdata-0.6.2 → pytdxdata-0.6.4}/src/pytdxdata/cache/manager.py +0 -0
- {pytdxdata-0.6.2 → pytdxdata-0.6.4}/src/pytdxdata/cache/memory.py +0 -0
- {pytdxdata-0.6.2 → pytdxdata-0.6.4}/src/pytdxdata/cache/ttl.py +0 -0
- {pytdxdata-0.6.2 → pytdxdata-0.6.4}/src/pytdxdata/cli.py +0 -0
- {pytdxdata-0.6.2 → pytdxdata-0.6.4}/src/pytdxdata/codec/__init__.py +0 -0
- {pytdxdata-0.6.2 → pytdxdata-0.6.4}/src/pytdxdata/codec/block.py +0 -0
- {pytdxdata-0.6.2 → pytdxdata-0.6.4}/src/pytdxdata/codec/financial.py +0 -0
- {pytdxdata-0.6.2 → pytdxdata-0.6.4}/src/pytdxdata/codec/industry.py +0 -0
- {pytdxdata-0.6.2 → pytdxdata-0.6.4}/src/pytdxdata/codec/payload.py +0 -0
- {pytdxdata-0.6.2 → pytdxdata-0.6.4}/src/pytdxdata/config.py +0 -0
- {pytdxdata-0.6.2 → pytdxdata-0.6.4}/src/pytdxdata/indicator.py +0 -0
- {pytdxdata-0.6.2 → pytdxdata-0.6.4}/src/pytdxdata/pool/__init__.py +0 -0
- {pytdxdata-0.6.2 → pytdxdata-0.6.4}/src/pytdxdata/pool/connection.py +0 -0
- {pytdxdata-0.6.2 → pytdxdata-0.6.4}/src/pytdxdata/pool/ex_connection.py +0 -0
- {pytdxdata-0.6.2 → pytdxdata-0.6.4}/src/pytdxdata/pool/health.py +0 -0
- {pytdxdata-0.6.2 → pytdxdata-0.6.4}/src/pytdxdata/pool/pool.py +0 -0
- {pytdxdata-0.6.2 → pytdxdata-0.6.4}/src/pytdxdata/pool/probe_cache.py +0 -0
- {pytdxdata-0.6.2 → pytdxdata-0.6.4}/src/pytdxdata/protocol/__init__.py +0 -0
- {pytdxdata-0.6.2 → pytdxdata-0.6.4}/src/pytdxdata/protocol/commands/__init__.py +0 -0
- {pytdxdata-0.6.2 → pytdxdata-0.6.4}/src/pytdxdata/protocol/commands/base.py +0 -0
- {pytdxdata-0.6.2 → pytdxdata-0.6.4}/src/pytdxdata/protocol/commands/ex_ext.py +0 -0
- {pytdxdata-0.6.2 → pytdxdata-0.6.4}/src/pytdxdata/protocol/commands/ex_proto.py +0 -0
- {pytdxdata-0.6.2 → pytdxdata-0.6.4}/src/pytdxdata/protocol/commands/finance.py +0 -0
- {pytdxdata-0.6.2 → pytdxdata-0.6.4}/src/pytdxdata/protocol/commands/kline.py +0 -0
- {pytdxdata-0.6.2 → pytdxdata-0.6.4}/src/pytdxdata/protocol/commands/mac.py +0 -0
- {pytdxdata-0.6.2 → pytdxdata-0.6.4}/src/pytdxdata/protocol/commands/mac_ext.py +0 -0
- {pytdxdata-0.6.2 → pytdxdata-0.6.4}/src/pytdxdata/protocol/commands/mac_tick.py +0 -0
- {pytdxdata-0.6.2 → pytdxdata-0.6.4}/src/pytdxdata/protocol/commands/minute.py +0 -0
- {pytdxdata-0.6.2 → pytdxdata-0.6.4}/src/pytdxdata/protocol/commands/security_list.py +0 -0
- {pytdxdata-0.6.2 → pytdxdata-0.6.4}/src/pytdxdata/protocol/commands/setup.py +0 -0
- {pytdxdata-0.6.2 → pytdxdata-0.6.4}/src/pytdxdata/protocol/commands/std_ext.py +0 -0
- {pytdxdata-0.6.2 → pytdxdata-0.6.4}/src/pytdxdata/protocol/commands/xdxr.py +0 -0
- {pytdxdata-0.6.2 → pytdxdata-0.6.4}/src/pytdxdata/protocol/datetime_.py +0 -0
- {pytdxdata-0.6.2 → pytdxdata-0.6.4}/src/pytdxdata/protocol/frame.py +0 -0
- {pytdxdata-0.6.2 → pytdxdata-0.6.4}/src/pytdxdata/protocol/mac_frame.py +0 -0
- {pytdxdata-0.6.2 → pytdxdata-0.6.4}/src/pytdxdata/protocol/price.py +0 -0
- {pytdxdata-0.6.2 → pytdxdata-0.6.4}/src/pytdxdata/protocol/volume.py +0 -0
- {pytdxdata-0.6.2 → pytdxdata-0.6.4}/src/pytdxdata/router.py +0 -0
- {pytdxdata-0.6.2 → pytdxdata-0.6.4}/src/pytdxdata/scheduler/__init__.py +0 -0
- {pytdxdata-0.6.2 → pytdxdata-0.6.4}/src/pytdxdata/server_probe.py +0 -0
- {pytdxdata-0.6.2 → pytdxdata-0.6.4}/src/pytdxdata/symbols.py +0 -0
|
@@ -146,6 +146,8 @@ _EX_PAGE = 1000 # EX 商品列表单页
|
|
|
146
146
|
_TICK_PAGE = 1000 # MAC 逐笔单页
|
|
147
147
|
_EX_TICK_PAGE = 1800 # 港股逐笔单页
|
|
148
148
|
_ALL_PAGES_CAP = 50 # count=None(全量)时的翻页上限
|
|
149
|
+
# 集合竞价**委托**记录标记(0x122F 第 5 字段)。不是成交,见 _ticks_one 注释。
|
|
150
|
+
_BS_AUCTION_ORDER = 8
|
|
149
151
|
|
|
150
152
|
# 港股系市场:逐笔走 EX 专用 16B 协议(0x23FC/0x2406),其余扩展市场走 MAC 0x122F
|
|
151
153
|
_HK_MARKETS = frozenset({27, 31, 48, 49, 71, 98})
|
|
@@ -233,11 +235,13 @@ class TdxData:
|
|
|
233
235
|
pool_max: int = 12,
|
|
234
236
|
mac_pool_cap: int = 4,
|
|
235
237
|
std_pool_cap: int = 4,
|
|
238
|
+
ex_pool_cap: int = 2,
|
|
236
239
|
) -> None:
|
|
237
240
|
self.port = port
|
|
238
241
|
self.timeout = timeout
|
|
239
242
|
self.default_adjust = default_adjust
|
|
240
243
|
self.mac_pool_cap = mac_pool_cap
|
|
244
|
+
self.ex_pool_cap = ex_pool_cap
|
|
241
245
|
self._std_servers = list(standard_servers or get_standard_hosts())
|
|
242
246
|
self._mac_servers = list(mac_servers or get_mac_hosts())
|
|
243
247
|
self._ex_servers = list(ex_servers or get_ex_hosts())
|
|
@@ -262,8 +266,11 @@ class TdxData:
|
|
|
262
266
|
probe_factory=lambda: MacKlineCmd(1, "600000", KlinePeriod.DAY, Adjust.NONE, 0, 100),
|
|
263
267
|
)
|
|
264
268
|
# EX扩展市场池(港股/期货/美股,端口7727;MAC EX login + pytdx EX setup 混合)
|
|
269
|
+
# 单服务器场景(测速缓存收缩后仅 1 台)下,有效并发 = 服务器数 × ex_pool_cap,
|
|
270
|
+
# 默认 cap=2 保证至少 2 并发;acquire 有 Condition 背压等待,不再快速失败。
|
|
265
271
|
self._ex_pool = ExPool(self._ex_servers, timeout=timeout,
|
|
266
272
|
min_size=min(pool_min, 2), max_size=min(pool_max, 6),
|
|
273
|
+
per_server_cap=ex_pool_cap,
|
|
267
274
|
handshake_map=EX_HANDSHAKES)
|
|
268
275
|
disk = None
|
|
269
276
|
if self._cache_dir is not None:
|
|
@@ -790,12 +797,26 @@ class TdxData:
|
|
|
790
797
|
|
|
791
798
|
参数:
|
|
792
799
|
date: ``None``=当日,``YYYYMMDD``=历史某日。
|
|
793
|
-
start:
|
|
800
|
+
start: 起始偏移,**从最新一笔往回数**(``0``=当天最后一条)。
|
|
801
|
+
``start=1000`` 表示跳过最近 1000 条、从更早的位置开始。
|
|
794
802
|
count: ``None``=尽量取全量(自动翻页,上限 50 页);给了就取这么多条。
|
|
795
803
|
|
|
796
804
|
返回:
|
|
797
|
-
``list[TransactionRecord]
|
|
798
|
-
|
|
805
|
+
``list[TransactionRecord]``,按入参标的顺序拼接,**每条标的内部按时间升序**。
|
|
806
|
+
注意服务端是按约 3 秒聚合的切片,``vol``/``trade_count`` 是切片增量
|
|
807
|
+
而非当日累计。
|
|
808
|
+
A股含 ``trade_count``,港股为 HH:MM 时间 + ``fields["zengcang"]`` 增仓。
|
|
809
|
+
|
|
810
|
+
**集合竞价委托(``bs_flag=8``)不会出现在结果里**:它们不是成交,``vol``
|
|
811
|
+
是累计撮合量(会被后续记录覆盖),计入会让 Σvol 比真值虚高 20%~160%,
|
|
812
|
+
且不同主机收录的条数不同 → 同一查询两次调用结果不一致。
|
|
813
|
+
|
|
814
|
+
**指数(``sh000016`` 等)的两个字段语义与个股不同**:
|
|
815
|
+
|
|
816
|
+
- ``vol`` 单位是**百元**(成交额/100),不是手。
|
|
817
|
+
- ``trade_count`` 是**当时均价 × 1000**,不是笔数。
|
|
818
|
+
|
|
819
|
+
详见 :class:`~pytdxdata.models.TransactionRecord` 的类注释。
|
|
799
820
|
"""
|
|
800
821
|
syms = parse_symbols(symbols)
|
|
801
822
|
sem = asyncio.Semaphore(max(1, concurrency))
|
|
@@ -816,18 +837,19 @@ class TdxData:
|
|
|
816
837
|
if sym.is_ex:
|
|
817
838
|
rows = await self._ticks_ex(sym, date=date, start=start, count=count)
|
|
818
839
|
else:
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
840
|
+
rows = await self._ticks_cn_serial(sym, date=date, start=start,
|
|
841
|
+
count=count)
|
|
842
|
+
# ★ 过滤集合竞价**委托**记录(bs_flag=8)。必须在逐页拉取**全部结束之后**做:
|
|
843
|
+
# 分页靠 `len(rows) < page_size` 判终止,若在 parse_response 里过滤,
|
|
844
|
+
# 满页会被剥短成"短页" → 提前终止 → 丢数据。
|
|
845
|
+
# 实测(2026-10-21 sh600000):b8 是 09:15~09:25 / 14:57~15:00 竞价段的
|
|
846
|
+
# 撮合快照,vol 是**累计值**(可被后续记录覆盖),不是成交增量;
|
|
847
|
+
# 计入后 Σvol 比真值虚高 20%~160%,且**不同主机的 b8 集合不同**
|
|
848
|
+
# (干净主机 0 条、脏主机 135 条)→ 同一查询两次调用结果不一致。
|
|
849
|
+
# 剔除后:Σvol 与快照 vol 精确相等(比值 1.0000),且跨主机逐条一致。
|
|
850
|
+
rows = [r for r in rows if r.bs_flag != _BS_AUCTION_ORDER]
|
|
851
|
+
# 排序放在 pack 之前,让缓存直接存入正确顺序,避免每次命中都重排。
|
|
852
|
+
rows.sort(key=lambda r: r.time)
|
|
831
853
|
return pack_payload(rows)
|
|
832
854
|
|
|
833
855
|
records = unpack_payload(await self._cache.get_or_fetch(key, fetch))
|
|
@@ -835,6 +857,54 @@ class TdxData:
|
|
|
835
857
|
r.symbol = sym.text
|
|
836
858
|
return records
|
|
837
859
|
|
|
860
|
+
async def _ticks_cn_serial(self, sym: Symbol, *, date: int | None, start: int,
|
|
861
|
+
count: int | None) -> list[TransactionRecord]:
|
|
862
|
+
"""A股逐笔(0x122F)**单连接串行游标**翻页。
|
|
863
|
+
|
|
864
|
+
为什么不用并发分页器:``0x122F`` 的 ``start`` 是「从**最新一笔**往回数的偏移」,
|
|
865
|
+
是个**相对锚点**,不是稳定的绝对序号。而池里各主机对集合竞价委托(``bs_flag=8``)
|
|
866
|
+
的收录**不一致**(实测干净主机 0 条、脏主机 135 条),同一 ``start`` 在不同主机上
|
|
867
|
+
落到**不同的真实成交**上。并发分页 = 各页来自不同主机 → 页边界既**重叠**
|
|
868
|
+
(sh600000 冗余 116 条)又**漏条**(13:03 附近丢 59 条),Σvol 偏移 −1.2%。
|
|
869
|
+
|
|
870
|
+
逐笔单日仅 5~6 页(1000 条/页),串行开销可忽略、换来精确一致,
|
|
871
|
+
故这里固定**单连接**、按 ``start`` 递增(= 向更早方向)推进。
|
|
872
|
+
|
|
873
|
+
返回:按页序累加后再**整体翻转**,得到时间升序的完整列表。
|
|
874
|
+
"""
|
|
875
|
+
chunks: list[list[TransactionRecord]] = []
|
|
876
|
+
pos = start
|
|
877
|
+
remaining = count
|
|
878
|
+
pc = await self._mac_pool.acquire()
|
|
879
|
+
try:
|
|
880
|
+
for _ in range(_ALL_PAGES_CAP):
|
|
881
|
+
n = _TICK_PAGE if remaining is None else min(_TICK_PAGE, remaining)
|
|
882
|
+
if n <= 0:
|
|
883
|
+
break
|
|
884
|
+
rows = await pc.execute(
|
|
885
|
+
MacTransactionCmd(sym.market, sym.code, date or 0, pos, n))
|
|
886
|
+
if not rows:
|
|
887
|
+
break
|
|
888
|
+
chunks.append(list(rows))
|
|
889
|
+
pos += len(rows)
|
|
890
|
+
if remaining is not None:
|
|
891
|
+
remaining -= len(rows)
|
|
892
|
+
if remaining <= 0:
|
|
893
|
+
break
|
|
894
|
+
# 短页 = 已到最早一笔
|
|
895
|
+
if len(rows) < n:
|
|
896
|
+
break
|
|
897
|
+
except Exception:
|
|
898
|
+
await self._mac_pool.release(pc, broken=True)
|
|
899
|
+
raise
|
|
900
|
+
await self._mac_pool.release(pc)
|
|
901
|
+
out: list[TransactionRecord] = []
|
|
902
|
+
for chunk in reversed(chunks):
|
|
903
|
+
out.extend(chunk)
|
|
904
|
+
for r in out:
|
|
905
|
+
r.symbol = sym.text
|
|
906
|
+
return out
|
|
907
|
+
|
|
838
908
|
async def _ticks_ex(self, sym: Symbol, *, date: int | None, start: int,
|
|
839
909
|
count: int | None) -> list[TransactionRecord]:
|
|
840
910
|
from .protocol.commands.ex_ext import (
|
|
@@ -843,7 +913,7 @@ class TdxData:
|
|
|
843
913
|
)
|
|
844
914
|
hk = sym.market in _HK_MARKETS
|
|
845
915
|
page = _EX_TICK_PAGE if hk else _TICK_PAGE
|
|
846
|
-
|
|
916
|
+
chunks: list[list[TransactionRecord]] = []
|
|
847
917
|
pos = start
|
|
848
918
|
remaining = count
|
|
849
919
|
for _ in range(_ALL_PAGES_CAP):
|
|
@@ -855,22 +925,27 @@ class TdxData:
|
|
|
855
925
|
if date else
|
|
856
926
|
GetExTransactionDataCmd(sym.market, sym.code, pos, n))
|
|
857
927
|
rows = await self._execute_ex(cmd)
|
|
858
|
-
|
|
928
|
+
chunk = [self._ex_tick(sym, r) for r in rows]
|
|
859
929
|
else:
|
|
860
930
|
cmd = MacTransactionCmd(sym.market, sym.code, date or 0, pos, n)
|
|
861
931
|
rows = await self._execute_ex(cmd)
|
|
862
932
|
for r in rows:
|
|
863
933
|
r.symbol = sym.text
|
|
864
|
-
|
|
865
|
-
if not
|
|
934
|
+
chunk = list(rows)
|
|
935
|
+
if not chunk:
|
|
866
936
|
break
|
|
867
|
-
pos
|
|
937
|
+
# EX 通道的 pos 同样是"从最新往回数",逐页倒序累加 → 最后整体翻转。
|
|
938
|
+
chunks.append(chunk)
|
|
939
|
+
pos += len(chunk)
|
|
868
940
|
if remaining is not None:
|
|
869
|
-
remaining -= len(
|
|
941
|
+
remaining -= len(chunk)
|
|
870
942
|
if remaining <= 0:
|
|
871
943
|
break
|
|
872
|
-
if len(
|
|
944
|
+
if len(chunk) < n:
|
|
873
945
|
break
|
|
946
|
+
out: list[TransactionRecord] = []
|
|
947
|
+
for chunk in reversed(chunks):
|
|
948
|
+
out.extend(chunk)
|
|
874
949
|
return out
|
|
875
950
|
|
|
876
951
|
@staticmethod
|
|
@@ -228,14 +228,34 @@ class SecurityInfo:
|
|
|
228
228
|
|
|
229
229
|
@dataclass(slots=True)
|
|
230
230
|
class TransactionRecord:
|
|
231
|
-
"""逐笔成交(跨市场统一模型;A股 MAC 通道含 trade_count
|
|
231
|
+
"""逐笔成交(跨市场统一模型;A股 MAC 通道含 trade_count=成交笔数)。
|
|
232
|
+
|
|
233
|
+
注意(实测 2026-10-21):
|
|
234
|
+
|
|
235
|
+
- 服务端是按**约 3 秒聚合**返回的切片,不是交易所原始逐笔成交。
|
|
236
|
+
- ``vol`` / ``trade_count`` 都是**该切片自身的增量**,不是当日累计值。
|
|
237
|
+
- ``trade_count`` 为**有符号**值:集合竞价段(``bs_flag=8``)会是负数
|
|
238
|
+
(实测 sh600000 09:15 段为 -874),不要对全表直接求 max/mean。
|
|
239
|
+
- 返回列表已按时间升序,但同秒多条时顺序不保证。
|
|
240
|
+
- ``bs_flag=8`` 的**竞价委托记录已被 ``get_ticks()`` 过滤掉**,不会出现在结果里。
|
|
241
|
+
|
|
242
|
+
**指数语义完全不同**(``is_cn_index`` 为真时,如 ``sh000016``):
|
|
243
|
+
|
|
244
|
+
- ``vol`` 单位是**百元**(= 成交额 / 100),不是「手」。实测
|
|
245
|
+
``快照amount / Σtick.vol = 100.0002``,且 ``Σtick.vol`` 与分时 Σvol **逐位相等**。
|
|
246
|
+
想和成分股成交量对比必须先换算,直接比会得到 ~26 倍的假比例。
|
|
247
|
+
- ``trade_count`` **不是笔数**,而是**当时均价 × 1000**(实测 tc/1000 与分时
|
|
248
|
+
``avg_price`` 的差 < 1.1)。指数没有「成交笔数」概念。
|
|
249
|
+
- ``bs_flag`` 语义不成立(实测返回 2,而模型只定义 0=卖 / 1=买)。
|
|
250
|
+
"""
|
|
251
|
+
|
|
232
252
|
market: int
|
|
233
253
|
code: str
|
|
234
254
|
time: str # HH:MM:SS(扩展市场为 HH:MM)
|
|
235
255
|
price: float
|
|
236
|
-
vol: float #
|
|
237
|
-
trade_count: int #
|
|
238
|
-
bs_flag: int # 1=主动买 0=主动卖
|
|
256
|
+
vol: float # 股票=手;指数=百元(成交额/100),见类注释
|
|
257
|
+
trade_count: int # 股票=笔数增量;指数=均价×1000,见类注释
|
|
258
|
+
bs_flag: int # 1=主动买 0=主动卖 2=中性 5=盘后固定价(指数语义不成立)
|
|
239
259
|
symbol: str = ""
|
|
240
260
|
fields: dict[str, float] = field(default_factory=dict) # 扩展市场额外字段(增仓等)
|
|
241
261
|
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
"""EX扩展市场连接池(固定连接数,借还+坏连接重建+login自动)。
|
|
2
|
+
|
|
3
|
+
与标准池 pool.py 的背压语义对齐:acquire 在无空闲连接且无法扩容时,
|
|
4
|
+
基于 asyncio.Condition 排队等待 release 唤醒(默认 acquire_timeout=30s),
|
|
5
|
+
而不是快速失败。per_server_cap 限制单台服务器连接数;单服务器场景下
|
|
6
|
+
有效并发 = servers × per_server_cap(默认 1),通过 TdxData(ex_pool_cap=N)
|
|
7
|
+
可对同一 EX 主机开多连接。
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import asyncio
|
|
12
|
+
import logging
|
|
13
|
+
import time
|
|
14
|
+
|
|
15
|
+
from .ex_connection import ExTdxConnection
|
|
16
|
+
|
|
17
|
+
log = logging.getLogger(__name__)
|
|
18
|
+
|
|
19
|
+
DEFAULT_ACQUIRE_TIMEOUT = 30.0
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class ExPoolTimeoutError(ConnectionError):
|
|
23
|
+
"""acquire 等待超时(携带池状态快照,便于排障)。"""
|
|
24
|
+
|
|
25
|
+
def __init__(self, pool: "ExPool", timeout: float) -> None:
|
|
26
|
+
idle = len(pool._idle)
|
|
27
|
+
total = pool._total
|
|
28
|
+
servers = len(pool.servers)
|
|
29
|
+
cap = pool.per_server_cap
|
|
30
|
+
super().__init__(
|
|
31
|
+
f"EX连接池获取超时(等了 {timeout:.1f}s):"
|
|
32
|
+
f"idle={idle} total={total} servers={servers} per_server_cap={cap} "
|
|
33
|
+
f"有效并发={servers * cap}"
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class ExPool:
|
|
38
|
+
"""EX通道连接池(港股/期货,端口7727,连接时自动login)。"""
|
|
39
|
+
|
|
40
|
+
def __init__(self, servers: list[str], *, timeout: float = 10.0,
|
|
41
|
+
min_size: int = 2, max_size: int = 6,
|
|
42
|
+
per_server_cap: int = 1,
|
|
43
|
+
acquire_timeout: float | None = None,
|
|
44
|
+
handshake: str = "login",
|
|
45
|
+
handshake_map: dict | None = None) -> None:
|
|
46
|
+
self.servers = servers
|
|
47
|
+
self.timeout = timeout
|
|
48
|
+
self.handshake = handshake
|
|
49
|
+
self.handshake_map = handshake_map or {}
|
|
50
|
+
self.min_size = min_size
|
|
51
|
+
self.max_size = max_size
|
|
52
|
+
self.per_server_cap = max(1, per_server_cap) # 一台服务器最多几个连接(默认1=单连接)
|
|
53
|
+
self.acquire_timeout = (
|
|
54
|
+
DEFAULT_ACQUIRE_TIMEOUT if acquire_timeout is None else acquire_timeout
|
|
55
|
+
)
|
|
56
|
+
self._idle: list[tuple[str, ExTdxConnection]] = []
|
|
57
|
+
self._server_count: dict[str, int] = {}
|
|
58
|
+
self._total = 0
|
|
59
|
+
self._closed = False
|
|
60
|
+
self._cond = asyncio.Condition()
|
|
61
|
+
|
|
62
|
+
async def start(self) -> None:
|
|
63
|
+
async with self._cond:
|
|
64
|
+
for host in self.servers[: self.min_size]:
|
|
65
|
+
if self._server_count.get(host, 0) >= self.per_server_cap:
|
|
66
|
+
continue
|
|
67
|
+
try:
|
|
68
|
+
conn = ExTdxConnection(host, 7727, self.timeout, self.handshake_map.get(host, self.handshake))
|
|
69
|
+
await conn.connect()
|
|
70
|
+
self._idle.append((host, conn))
|
|
71
|
+
self._total += 1
|
|
72
|
+
self._server_count[host] = self._server_count.get(host, 0) + 1
|
|
73
|
+
except Exception as e:
|
|
74
|
+
log.warning("EX连接失败 %s: %s", host, str(e)[:60])
|
|
75
|
+
|
|
76
|
+
async def close(self) -> None:
|
|
77
|
+
self._closed = True
|
|
78
|
+
async with self._cond:
|
|
79
|
+
for _, conn in self._idle:
|
|
80
|
+
try:
|
|
81
|
+
await conn.close()
|
|
82
|
+
except Exception:
|
|
83
|
+
pass
|
|
84
|
+
self._idle.clear()
|
|
85
|
+
self._total = 0
|
|
86
|
+
self._server_count.clear()
|
|
87
|
+
self._cond.notify_all()
|
|
88
|
+
|
|
89
|
+
async def acquire(self, timeout: float | None = None) -> ExTdxConnection:
|
|
90
|
+
"""借出一条连接;无空闲且无法扩容时排队等待 release 唤醒。
|
|
91
|
+
|
|
92
|
+
timeout 默认取 self.acquire_timeout(30s);传 None 表示无限等待。
|
|
93
|
+
"""
|
|
94
|
+
if timeout is None:
|
|
95
|
+
timeout = self.acquire_timeout
|
|
96
|
+
deadline = None if timeout is None else time.monotonic() + timeout
|
|
97
|
+
async with self._cond:
|
|
98
|
+
while True:
|
|
99
|
+
# 1. 优先借用空闲连接(过期则丢弃,槽位在锁内回收)
|
|
100
|
+
if self._idle:
|
|
101
|
+
_, conn = self._idle.pop()
|
|
102
|
+
fresh = time.monotonic() - conn.last_used < 30.0
|
|
103
|
+
if conn.alive and fresh:
|
|
104
|
+
return conn
|
|
105
|
+
# 连接空闲过久(login会话可能失效)→ 丢弃,槽位让给扩容
|
|
106
|
+
self._total = max(0, self._total - 1)
|
|
107
|
+
self._server_count[conn.host] = max(0, self._server_count.get(conn.host, 0) - 1)
|
|
108
|
+
self._schedule_close(conn)
|
|
109
|
+
|
|
110
|
+
# 2. 可扩容 → 锁内预留槽位,锁外建连
|
|
111
|
+
new_conn = None
|
|
112
|
+
new_host = None
|
|
113
|
+
if self._total < self.max_size and self.servers:
|
|
114
|
+
host = self._next_available_server()
|
|
115
|
+
if host is not None:
|
|
116
|
+
self._total += 1
|
|
117
|
+
self._server_count[host] = self._server_count.get(host, 0) + 1
|
|
118
|
+
new_conn = ExTdxConnection(host, 7727, self.timeout, self.handshake_map.get(host, self.handshake))
|
|
119
|
+
new_host = host
|
|
120
|
+
if new_conn is not None:
|
|
121
|
+
# 锁外网络 IO:连接失败回滚槽位后继续等待
|
|
122
|
+
try:
|
|
123
|
+
await new_conn.connect()
|
|
124
|
+
return new_conn
|
|
125
|
+
except Exception as e:
|
|
126
|
+
log.warning("EX扩容失败 %s: %s", new_host, str(e)[:60])
|
|
127
|
+
async with self._cond:
|
|
128
|
+
self._total = max(0, self._total - 1)
|
|
129
|
+
self._server_count[new_host] = max(0, self._server_count.get(new_host, 0) - 1)
|
|
130
|
+
|
|
131
|
+
# 3. 池满:排队等待 release 唤醒(或超时)
|
|
132
|
+
now = time.monotonic()
|
|
133
|
+
if deadline is not None and now >= deadline:
|
|
134
|
+
raise ExPoolTimeoutError(self, timeout)
|
|
135
|
+
try:
|
|
136
|
+
if deadline is None:
|
|
137
|
+
await self._cond.wait()
|
|
138
|
+
else:
|
|
139
|
+
await asyncio.wait_for(self._cond.wait(), timeout=deadline - now)
|
|
140
|
+
except asyncio.TimeoutError:
|
|
141
|
+
raise ExPoolTimeoutError(self, timeout)
|
|
142
|
+
|
|
143
|
+
def _next_available_server(self) -> str | None:
|
|
144
|
+
for h in self.servers:
|
|
145
|
+
if self._server_count.get(h, 0) < self.per_server_cap:
|
|
146
|
+
return h
|
|
147
|
+
return None
|
|
148
|
+
|
|
149
|
+
def _schedule_close(self, conn: ExTdxConnection) -> None:
|
|
150
|
+
async def _close():
|
|
151
|
+
try:
|
|
152
|
+
await conn.close()
|
|
153
|
+
except Exception:
|
|
154
|
+
pass
|
|
155
|
+
try:
|
|
156
|
+
asyncio.get_running_loop().create_task(_close())
|
|
157
|
+
except RuntimeError:
|
|
158
|
+
pass
|
|
159
|
+
|
|
160
|
+
async def release(self, conn: ExTdxConnection, *, broken: bool = False) -> None:
|
|
161
|
+
async with self._cond:
|
|
162
|
+
if broken or not conn.alive:
|
|
163
|
+
self._total = max(0, self._total - 1)
|
|
164
|
+
self._server_count[conn.host] = max(0, self._server_count.get(conn.host, 0) - 1)
|
|
165
|
+
self._schedule_close(conn)
|
|
166
|
+
else:
|
|
167
|
+
self._idle.append((conn.host, conn))
|
|
168
|
+
self._cond.notify_all()
|
|
@@ -13,16 +13,23 @@ MAX_QUOTES = 80
|
|
|
13
13
|
|
|
14
14
|
|
|
15
15
|
def price_decimal_digits(market: int, code: str) -> int:
|
|
16
|
-
"""推断报价有效小数位:股票2位(/100)
|
|
16
|
+
"""推断报价有效小数位:股票 2 位(/100)、ETF/基金 3 位(/1000)。
|
|
17
|
+
|
|
18
|
+
**沪市指数必须是 2 位**,此前把 ``000``/``8`` 一并判成 3 位,导致上证50、
|
|
19
|
+
上证指数、科创50 等**价格整体少 10 倍**。实证(2026-10-21):协议原始整数
|
|
20
|
+
与分时/逐笔价格比对,6 只沪市指数 + 2 只板块指数(880001/880305)全部是
|
|
21
|
+
``×10`` 错误,而 4 只沪市 ETF(510300/510500/588000/511010)、4 只沪市
|
|
22
|
+
股票、3 只科创板、3 只深市指数、深市股票/创业板/ETF 全部 ``×1`` 正确。
|
|
23
|
+
"""
|
|
17
24
|
code = (code or "").strip().rstrip("\x00")
|
|
18
25
|
if market == 1: # SH
|
|
19
|
-
if code.startswith(
|
|
20
|
-
return 3
|
|
21
|
-
return 2
|
|
26
|
+
if code.startswith("5"):
|
|
27
|
+
return 3 # ETF/基金
|
|
28
|
+
return 2 # 指数(000xxx/880xxx)、股票(60xxxx/688xxx)
|
|
22
29
|
if market == 0: # SZ
|
|
23
30
|
if code.startswith("1"):
|
|
24
|
-
return 3
|
|
25
|
-
return 2
|
|
31
|
+
return 3 # 基金/债券
|
|
32
|
+
return 2 # 指数(399xxx)、股票(00xxxx/30xxxx)
|
|
26
33
|
return 2
|
|
27
34
|
|
|
28
35
|
|
|
@@ -111,8 +111,11 @@ class MacTransactionCmd(BaseCommand[list[TransactionRecord]]):
|
|
|
111
111
|
for i in range(count):
|
|
112
112
|
offset = 39 + i * 18
|
|
113
113
|
try:
|
|
114
|
+
# trade_count 必须按**有符号** int32 解析:集合竞价段(bs_flag=8)
|
|
115
|
+
# 该字段实为负值,按 uint32 会读出 42 亿量级的脏数据。
|
|
116
|
+
# 实测(2026-10-21 sh600000):09:15:03 原始 96fcffff = -874。
|
|
114
117
|
time_sec, price, volume, trade_count, bs_flag = unpack_from(
|
|
115
|
-
"<
|
|
118
|
+
"<IfIiH", body, offset, "mac transaction item"
|
|
116
119
|
)
|
|
117
120
|
except ValueError:
|
|
118
121
|
break
|
|
@@ -27,6 +27,7 @@ class PageSpec:
|
|
|
27
27
|
ordered: bool = True # 按 start 升序拼接
|
|
28
28
|
min_page: int = 100 # 规避标准K线 count<100 空响应坑
|
|
29
29
|
start_offset: int = 0 # 起始偏移(从该偏移开始分页,避免拉取历史全量)
|
|
30
|
+
newest_first: bool = False # 服务端 start 从最新往回数(0x122F 逐笔即如此)
|
|
30
31
|
|
|
31
32
|
|
|
32
33
|
@dataclass(slots=True)
|
|
@@ -94,7 +95,7 @@ class Paginator:
|
|
|
94
95
|
if s.pc is not None:
|
|
95
96
|
pc, s.pc = s.pc, None
|
|
96
97
|
await self.pool.release(pc)
|
|
97
|
-
return self._assemble(out, spec.ordered)
|
|
98
|
+
return self._assemble(out, spec.ordered, spec.newest_first)
|
|
98
99
|
|
|
99
100
|
def _plan_starts(self, spec: PageSpec) -> list[tuple[int, int]]:
|
|
100
101
|
"""切页:返回 [(start, count), ...]。"""
|
|
@@ -158,9 +159,12 @@ class Paginator:
|
|
|
158
159
|
return None, False
|
|
159
160
|
return None, False
|
|
160
161
|
|
|
161
|
-
def _assemble(self, results: list[PageResult], ordered: bool
|
|
162
|
+
def _assemble(self, results: list[PageResult], ordered: bool,
|
|
163
|
+
newest_first: bool = False) -> list[Any]:
|
|
164
|
+
# newest_first=True:start=0 是最新一页,start 越大越旧 → 反向拼才对得上时间序。
|
|
165
|
+
# 单页内部服务端已按时间升序,所以只翻页序,不翻页内元素。
|
|
162
166
|
if ordered:
|
|
163
|
-
results.sort(key=lambda r: r.start)
|
|
167
|
+
results.sort(key=lambda r: r.start, reverse=newest_first)
|
|
164
168
|
out: list[Any] = []
|
|
165
169
|
for r in results:
|
|
166
170
|
out.extend(r.items)
|