Files
pytdxdata/src/pytdxdata/protocol/commands/transaction.py
T
openbotandopenbot-coder 8344ed6e6b fix: 修复沪市指数价格少10倍 + 逐笔竞价委托污染(Σvol 虚高/跨主机不稳定) (#3)
核对 sh000016 上证50 与 50 只成分股的 tick 汇总时,发现三个口径
(快照/分时/逐笔)互不一致,追查到 5 个缺陷。

1. 沪市指数价格整体少 10 倍
   price_decimal_digits 把沪市 000xxx(上证/上证50/沪深300/科创50)与
   8xxxxx(板块指数)判为 3 位小数,实际协议是 2 位。
   上证指数 3713 -> 371、上证50 2747 -> 274。
   实证 6 只指数 + 2 只板块指数全部 ×10,而 ETF/股票/科创板/深市全类 ×1 正确。
   改法:沪市仅 ETF(5开头) 保留 3 位,其余 2 位。

2. get_ticks 把 bs_flag=8 竞价委托当成成交
   该记录是 09:15~09:25 / 14:57~15:00 竞价段的撮合委托快照,
   vol 是累计值(可被后续覆盖),不是成交增量。
   - Σvol 虚高:sh600000 含 b8 = 668,693 vs 快照 462,562(1.4456);
     剔 b8 = 462,634(1.000156,精确一致)
   - 跨主机不稳定:干净主机 0 条、脏主机 135 条 -> 同一 start 落到不同真实成交
   改法:分页后统一剔除 b8。

3. A股逐笔改单连接串行游标(_ticks_cn_serial)
   并发分页各页来自不同主机,而 0x122F 的 start 是「从最新往回数」的相对锚点,
   主机间 b8 收录差异导致页边界既重叠(冗余 116 条)又漏条(13:03 附近丢 59 条)。
   逐笔单日仅 5~6 页,串行开销可忽略。

4. trade_count 有符号解析(前序)、返回列表时间序(前序)保留。

- sh000016 三口径闭合:快照 vol/amount 比值 1.00000061/0.99999997;
  指数逐笔 Σvol = 分时 Σvol = 1,045,584,467(完全相等)
- 6 只标的 Σvol/快照 vol 全部回到 1.0001~1.0007
- 跨主机公共时间窗逐条一致(5/5 标的,条数差 0)
- 测试 194 -> 217 passed(+20 小数位、+3 逐笔回归)

- TransactionRecord 类注释 + get_ticks docstring 明示指数语义:
  vol 单位「百元」(成交额/100)、trade_count 为「均价×1000」而非笔数
- API_REFERENCE / llms.txt 同步

Co-authored-by: openbot-coder <openbot-coder@users.noreply.github.com>
2026-10-22 09:06:40 +08:00

130 lines
5.2 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""逐笔成交命令:标准通道(当日0x170801含笔数 / 历史0x013001)+ MAC通道(0x122F含trade_count)"""
from __future__ import annotations
import struct
from ..._binary import unpack_from
from ...models import TransactionRecord
from ..datetime_ import get_time
from ..mac_frame import build_mac_request
from ..price import get_price
from .base import BaseCommand
STD_PAGE_SIZE = 800
MAC_PAGE_SIZE = 1000
class GetTransactionDataCmd(BaseCommand[list[TransactionRecord]]):
"""标准通道当日逐笔(0x170801)。协议含成交笔数(_num_orders),此处显式解析暴露。"""
def __init__(self, market: int, code: str, start: int, count: int = 800) -> None:
self.market = market
self.code = code.encode("utf-8")
self.start = start
self.count = count
def build_request(self) -> bytes:
header = bytes.fromhex("0c17080101010e000e00c50f".replace(" ", ""))
return header + struct.pack("<H6sHH", self.market, self.code, self.start, self.count)
def parse_response(self, body: bytes) -> list[TransactionRecord]:
(num,) = unpack_from("<H", body, 0, "std transaction header")
pos = 2
last_price = 0
records: list[TransactionRecord] = []
for _ in range(num):
hour, minute, pos = get_time(body, pos)
price_diff, pos = get_price(body, pos)
vol, pos = get_price(body, pos)
num_orders, pos = get_price(body, pos) # 成交笔数(当日独有)
bs_flag, pos = get_price(body, pos)
_unknown, pos = get_price(body, pos)
last_price += price_diff
records.append(TransactionRecord(
market=self.market, code=self.code.decode("utf-8"),
time=f"{hour:02d}:{minute:02d}:00",
price=last_price / 100.0, vol=float(vol),
trade_count=int(num_orders), bs_flag=bs_flag,
))
return records
class GetHistoryTransactionDataCmd(BaseCommand[list[TransactionRecord]]):
"""标准通道历史逐笔(0x013001,无笔数字段)。"""
def __init__(self, market: int, code: str, date: int, start: int, count: int = 800) -> None:
self.market = market
self.code = code.encode("utf-8")
self.date = date
self.start = start
self.count = count
def build_request(self) -> bytes:
header = bytes.fromhex("0c013001000112001200b50f".replace(" ", ""))
return header + struct.pack("<IH6sHH", self.date, self.market, self.code, self.start, self.count)
def parse_response(self, body: bytes) -> list[TransactionRecord]:
(num,) = unpack_from("<H", body, 0, "hist transaction header")
pos = 6 # 2(num) + 4(skip)
last_price = 0
records: list[TransactionRecord] = []
for _ in range(num):
hour, minute, pos = get_time(body, pos)
price_diff, pos = get_price(body, pos)
vol, pos = get_price(body, pos)
bs_flag, pos = get_price(body, pos)
_unknown, pos = get_price(body, pos)
last_price += price_diff
records.append(TransactionRecord(
market=self.market, code=self.code.decode("utf-8"),
time=f"{hour:02d}:{minute:02d}:00",
price=last_price / 100.0, vol=float(vol),
trade_count=0, bs_flag=bs_flag, # 历史无笔数
))
return records
class MacTransactionCmd(BaseCommand[list[TransactionRecord]]):
"""MAC通道逐笔(0x122F,每条18B固定:time+price+vol+trade_count+bs_flag,含成交笔数)。"""
def __init__(self, market: int, code: str, ymd: int, start: int, count: int = 1000) -> None:
self.market = market
self.code = code
self.ymd = ymd
self.start = start
self.count = count
def build_request(self) -> bytes:
body = struct.pack(
"<H22sIIH10x",
self.market,
self.code.encode("gbk"),
self.ymd,
self.start,
self.count,
)
return build_mac_request(0x122F, body)
def parse_response(self, body: bytes) -> list[TransactionRecord]:
(count,) = unpack_from("<H", body, 29, "mac transaction count")
records: list[TransactionRecord] = []
for i in range(count):
offset = 39 + i * 18
try:
# trade_count 必须按**有符号** int32 解析:集合竞价段(bs_flag=8)
# 该字段实为负值,按 uint32 会读出 42 亿量级的脏数据。
# 实测(2026-10-21 sh600000):09:15:03 原始 96fcffff = -874。
time_sec, price, volume, trade_count, bs_flag = unpack_from(
"<IfIiH", body, offset, "mac transaction item"
)
except ValueError:
break
h, m, s = time_sec // 3600, time_sec % 3600 // 60, time_sec % 60
records.append(TransactionRecord(
market=self.market, code=self.code,
time=f"{h:02d}:{m:02d}:{s:02d}",
price=price, vol=float(volume),
trade_count=int(trade_count), bs_flag=bs_flag,
))
return records