fix(quotes): 修正 server_time 解码口径(十进制位拼接 HHMMSS + 价格小数位) (#15)
Co-authored-by: openbot-coder <openbot-coder@users.noreply.github.com>
This commit is contained in:
1 parent
c9722943e2
commit
dea39db441
5 files changed
+203
-11
No files matched your search
@@ -2,6 +2,38 @@
|
||||
|
||||
本项目遵循 [语义化版本](https://semver.org/lang/zh-CN/)。
|
||||
|
||||
## [未发布]
|
||||
|
||||
### 修复
|
||||
|
||||
- **修复 `get_quotes` 的 `server_time`(行情快照时间)解码错误**。
|
||||
|
||||
原实现按「小时 + 百万分之一小时」(`divmod(raw, 1_000_000)`)解码,但协议实际是
|
||||
**十进制位拼接**:
|
||||
|
||||
```
|
||||
整数 = HH*10**(4+d) + MM*10**(2+d) + SS*10**d + 小数
|
||||
d = 该品种价格小数位(股票 2 / ETF·LOF·B股 3 / 国债·回购 4)
|
||||
```
|
||||
|
||||
后果:股票 13:29:59 显示成 `11:17:57`(基准错、速率也只有实际的 53%),ETF/债券
|
||||
直接给出小时 > 23 的非法值。
|
||||
|
||||
| 标的 | raw | 0.7.1 显示 | 现在 |
|
||||
|---|---|---|---|
|
||||
| `sh600000`(dp=2) | `13224002` | `13:13:26.407` | **`13:22:40.02`** |
|
||||
| `sh510300`(dp=3) | `132245903` | `132:14:45.250` | **`13:22:45.903`** |
|
||||
| `sh204001`(dp=4) | `1310228050` | `1310:13:40.980` | **`13:10:22.8050`** |
|
||||
|
||||
- 小数位数跟着品种价格精度走,输出 `HH:MM:SS.ff`(2~4 位,兼容旧文档的 `HH:MM:SS.mmm`)。
|
||||
- 服务端怪癖:**SS 落在 50~59 秒时写成 90~99**(编码值 +40 秒)。未修正时该区间的滞后
|
||||
会从稳定的 10.6 秒突变成 -29.4 秒;现在 `SS >= 60` 一律减 40 秒还原。
|
||||
- **指数(`sh000001` / `sz399001` / `sh000300` …)该字段返回空串**:协议里它对指数不是
|
||||
时钟(同一时刻 `000001` 解出 `12:89`、`399001` 解出 `12:15`,互相矛盾)。此前会给出一个
|
||||
看着合理、其实是垃圾的时间。要指数时间请用 `get_minutes` / K 线。
|
||||
- 实测验收(2026-10-30 盘中,同服务器连续采样 3 分钟):`server_time` 与本地时钟的滞后
|
||||
稳定在 10.5~10.9 秒;股票 / ETF / B股 / 国债 / 回购全覆盖,见 `tests/test_quote_time.py`。
|
||||
|
||||
## [0.7.1] - 2026-10-29
|
||||
|
||||
### 性能
|
||||
|
||||
@@ -228,6 +228,18 @@ from pytdxdata import (
|
||||
|
||||
> 注:`__init__` 仅导出 `Market/ExMarket/KlinePeriod/Adjust` 与 6 个核心模型;`BoardInfo/MemberQuote/AuctionItem` 等需 `from pytdxdata.models import ...`。
|
||||
|
||||
**`SecurityQuote.server_time`(行情快照时间,0.7.2 修正)**
|
||||
|
||||
- 格式 `HH:MM:SS.ff`,小数位数 = 该品种**价格小数位**:股票 2、ETF/LOF/B股 3、国债·回购 4。
|
||||
例 `13:22:40.02` / `13:22:45.903` / `13:10:22.8050`。
|
||||
- 它比本地时钟**慢 5~15 秒**(服务器快照滞后),超低流动性品种(货币 ETF、国债)可能差几分钟。
|
||||
判断「行情有没有更新」请看这个值有没有变,别看调用时刻 —— 盘口本身约 3 秒刷新一次。
|
||||
- **指数(`sh000001` / `sz399001` / `sh000300` …)恒为空串**:该字段对指数不是时钟
|
||||
(同一时刻 `000001` 解出 `12:89`、`399001` 解出 `12:15`,协议内没有可用信息)。
|
||||
要指数时间请用 `get_minutes` / K 线。
|
||||
- ⚠️ 0.7.1 及之前按「小时 + 百万分之一小时」解码是**错的**:股票 `11:29:59` 会显示成
|
||||
`11:17:57`,ETF/债券会显示成 `113:00:21` 这种非法小时。
|
||||
|
||||
**量纲对照(跨品种,2026-10-22 实测)**
|
||||
|
||||
同名字段在不同品种上单位不同。最典型的坑是用 `amount / vol` 算均价——它在可转债上会**错 10 倍**:
|
||||
|
||||
@@ -216,6 +216,10 @@ class SecurityQuote:
|
||||
A股(标准通道):五档 ``bid``/``ask`` + 买卖量 + 涨跌停价齐全,``name`` 为空。
|
||||
A股(``fields=[...]`` 走 MAC 0x122B):``name`` 与 ``fields`` 齐全,五档为空。
|
||||
扩展市场(港股/美股/期货):``name`` + 基础价量在属性上,其余字段位在 ``fields``。
|
||||
|
||||
``server_time`` 是**行情快照时间**:``HH:MM:SS.ff``,小数位数等于该品种价格小数位
|
||||
(股票 2 / ETF·LOF·B股 3 / 国债·回购 4),通常比本地时钟慢 5~15 秒。**指数恒为空串**
|
||||
(协议里这个字段对指数不是时钟);判断行情是否更新看它有没有变,别看调用时刻。
|
||||
"""
|
||||
market: int
|
||||
code: str
|
||||
|
||||
@@ -5,6 +5,7 @@ import struct
|
||||
|
||||
from ..._binary import unpack_from
|
||||
from ...models import SecurityQuote
|
||||
from ...symbols import is_cn_index
|
||||
from ..price import get_price
|
||||
from ..volume import get_volume
|
||||
from .base import BaseCommand
|
||||
@@ -161,13 +162,49 @@ def price_decimal_digits(market: int, code: str) -> int:
|
||||
return _decimal_digits_static(m, code)
|
||||
|
||||
|
||||
def format_server_time(raw: int) -> str:
|
||||
"""服务器时间编码:小时 + 百万分之一小时。14999212 -> 14:59:57.163"""
|
||||
hours, fractional_hour = divmod(raw, 1_000_000)
|
||||
total_millis = fractional_hour * 3600 // 1000
|
||||
minutes, remainder = divmod(total_millis, 60_000)
|
||||
seconds, millis = divmod(remainder, 1000)
|
||||
return f"{hours:02d}:{minutes:02d}:{seconds:02d}.{millis:03d}"
|
||||
_SERVER_TIME_SKEW = 40
|
||||
"""服务端在「50~59 秒」段会写成「90~99」秒,整数值固定多 40×10**d。"""
|
||||
|
||||
|
||||
def format_server_time(raw: int, digits: int = 2) -> str:
|
||||
"""报价快照时间解码:十进制数字拼接 ``HH MM SS`` + ``digits`` 位小数。
|
||||
|
||||
编码(2026-10-30 盘中实测确定)::
|
||||
|
||||
整数 = HH*10**(4+d) + MM*10**(2+d) + SS*10**d + 小数
|
||||
d = 该品种**价格小数位**(股票 2 / ETF·LOF·B股 3 / 国债·回购 4)
|
||||
|
||||
实测样例:``13224002``(d=2)→ ``13:22:40.02``;``132245903``(d=3)→
|
||||
``13:22:45.903``;``1310228050``(d=4)→ ``13:10:22.8050``。
|
||||
|
||||
历史错误(0.8.0 修正):此前按「小时 + 百万分之一小时」解码 —— 用
|
||||
``divmod(raw, 1_000_000)`` 取小时、余数按每秒 3600/1e6 折算。股票会把
|
||||
11:29:59 解成 **11:17:57**(基准错了、速率也只有真实时钟的 53%),
|
||||
ETF / 债券更会解出 ``113:00:21.222`` 这种小时 > 23 的非法值。
|
||||
|
||||
⚠️ 服务端怪癖:**SS 落在 50~59 秒时写成 90~99**(编码值 +40 秒)。实测
|
||||
3 分钟连续采样,未修正时该区间的滞后会从稳定的 10.6 秒突然变成 -29.4 秒
|
||||
(正好差 40)。因此这里对 ``SS >= 60`` 一律减 40 秒还原。
|
||||
|
||||
⚠️ 指数(``sh000001`` / ``sz399001`` …)该字段**不是**这只时钟:解出来
|
||||
MM 常 > 59、且不同指数互相矛盾(同一时刻 000001 是 12:89、399001 是 12:15),
|
||||
协议里没有给出可用信息。这类返回值一律为空串,不要编造时间;要指数时间
|
||||
请用 :meth:`~pytdxdata.api.TdxData.get_minutes` 或 K 线。
|
||||
"""
|
||||
if raw <= 0:
|
||||
return ""
|
||||
d = digits if 0 <= digits <= 6 else 2
|
||||
scale = 10 ** d
|
||||
frac = raw % scale
|
||||
rest = raw // scale
|
||||
seconds = rest % 100
|
||||
minutes = (rest // 100) % 100
|
||||
hours = rest // 10000
|
||||
if seconds >= 60:
|
||||
seconds -= _SERVER_TIME_SKEW
|
||||
if hours > 23 or minutes > 59 or not 0 <= seconds <= 59:
|
||||
return ""
|
||||
return f"{hours:02d}:{minutes:02d}:{seconds:02d}.{frac:0{d}d}"
|
||||
|
||||
|
||||
class GetSecurityQuotesCmd(BaseCommand[list[SecurityQuote]]):
|
||||
@@ -235,13 +272,14 @@ class GetSecurityQuotesCmd(BaseCommand[list[SecurityQuote]]):
|
||||
pos += 4
|
||||
|
||||
code = code_b.decode("utf-8").rstrip("\x00")
|
||||
divisor = 10 ** price_decimal_digits(market_b, code)
|
||||
dp = price_decimal_digits(market_b, code)
|
||||
divisor = 10 ** dp
|
||||
p = price_raw / divisor
|
||||
results.append(SecurityQuote(
|
||||
market=market_b, code=code, price=p,
|
||||
cur_vol=float(cur_vol),
|
||||
rise_speed=_rise_speed / 100.0,
|
||||
decimal_point=price_decimal_digits(market_b, code),
|
||||
decimal_point=dp,
|
||||
open_amount=float(_unknown_3),
|
||||
pre_close=(price_raw + last_close_diff) / divisor,
|
||||
open=(price_raw + open_diff) / divisor,
|
||||
@@ -250,8 +288,8 @@ class GetSecurityQuotesCmd(BaseCommand[list[SecurityQuote]]):
|
||||
vol=float(vol), amount=amount, s_vol=float(s_vol), b_vol=float(b_vol),
|
||||
bid=[((price_raw + d) / divisor, v) for d, v in bid],
|
||||
ask=[((price_raw + d) / divisor, v) for d, v in ask],
|
||||
server_time=format_server_time(unknown_0),
|
||||
server_time="" if is_cn_index(market_b, code)
|
||||
else format_server_time(unknown_0, dp),
|
||||
trading_status=trading_status,
|
||||
))
|
||||
return results
|
||||
return results
|
||||
@@ -0,0 +1,106 @@
|
||||
"""报价快照时间字段(0x053E 第 6 个变长字段)解码口径。
|
||||
|
||||
2026-10-30 修正前按「小时 + 百万分之一小时」解码,股票 11:29:59 会解成
|
||||
11:17:57、ETF 会解出 `113:00:21` 这种非法小时。这里把实测口径锁死:
|
||||
十进制位拼接 `HH MM SS` + 价格小数位,SS 的 50~59 段服务端写成 90~99。
|
||||
"""
|
||||
import struct
|
||||
|
||||
from pytdxdata.protocol.commands.quotes import (
|
||||
GetSecurityQuotesCmd,
|
||||
format_server_time,
|
||||
price_decimal_digits,
|
||||
)
|
||||
from pytdxdata.protocol.price import put_price
|
||||
|
||||
# ---------- 纯解码 ----------
|
||||
|
||||
def test_stock_two_digits():
|
||||
# 13:22:40.02(股票价格 2 位小数 → 时间带 2 位小数)
|
||||
assert format_server_time(13224002, 2) == "13:22:40.02"
|
||||
|
||||
|
||||
def test_etf_three_digits():
|
||||
# 13:22:45.903(ETF 3 位小数)
|
||||
assert format_server_time(132245903, 3) == "13:22:45.903"
|
||||
|
||||
|
||||
def test_bond_four_digits():
|
||||
# 13:10:22.8050(国债 / 回购 4 位小数)
|
||||
assert format_server_time(1310228050, 4) == "13:10:22.8050"
|
||||
|
||||
|
||||
def test_seconds_50_59_written_as_90_99():
|
||||
# 服务端把 52 秒写成 92 → 必须还原成 13:17:52.01
|
||||
assert format_server_time(13179201, 2) == "13:17:52.01"
|
||||
assert format_server_time(13179501, 2) == "13:17:55.01"
|
||||
assert format_server_time(13179801, 2) == "13:17:58.01"
|
||||
# 90 以下原样(不要误伤 51、59 这类合法秒)
|
||||
assert format_server_time(13175101, 2) == "13:17:51.01"
|
||||
assert format_server_time(13175901, 2) == "13:17:59.01"
|
||||
|
||||
|
||||
def test_index_and_garbage_return_empty():
|
||||
# 指数该字段不是时钟(同一时刻 000001 解出 12:89 → MM 越界)
|
||||
assert format_server_time(12867393, 2) == ""
|
||||
assert format_server_time(0, 2) == ""
|
||||
# 小时越界
|
||||
assert format_server_time(113005895, 2) == ""
|
||||
|
||||
|
||||
def test_digits_follow_decimal_point():
|
||||
assert price_decimal_digits(1, "600000") == 2
|
||||
assert price_decimal_digits(1, "510300") == 3
|
||||
assert price_decimal_digits(1, "019547") == 4
|
||||
|
||||
|
||||
# ---------- 整条报文 ----------
|
||||
|
||||
def _quote_record(market: int, code: str, price_raw: int, time_raw: int,
|
||||
vol: int = 1000, rise: int = 0) -> bytes:
|
||||
"""按 0x053E 记录布局拼一条报价(金额字段填 0,不参与本节断言)。"""
|
||||
out = bytearray(struct.pack("<B6sH", market, code.encode(), 0))
|
||||
for v in (price_raw, 0, 0, 0, 0): # price / lastclose / open / high / low
|
||||
out += put_price(v)
|
||||
out += put_price(time_raw) # ← 快照时间
|
||||
out += put_price(-price_raw) # unknown1(多数标的 = -price)
|
||||
out += put_price(vol) # vol
|
||||
out += put_price(1) # cur_vol
|
||||
out += struct.pack("<I", 0) # amount(4 字节自定义浮点)
|
||||
for v in (vol // 2, vol // 2, 0, 0): # s_vol / b_vol / unknown2 / unknown3
|
||||
out += put_price(v)
|
||||
for _ in range(5): # 五档:价差 0,量 1
|
||||
for v in (0, 0, 1, 1):
|
||||
out += put_price(v)
|
||||
out += struct.pack("<H", 0) # trading_status
|
||||
for _ in range(4):
|
||||
out += put_price(0)
|
||||
out += struct.pack("<hH", rise, 0) # rise_speed / active2
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def _body(records: list[bytes]) -> bytes:
|
||||
# 前 2 字节是服务端魔数(解析时跳过),随后是 2 字节条数
|
||||
return b"\x00\x00" + struct.pack("<H", len(records)) + b"".join(records)
|
||||
|
||||
|
||||
def test_parse_response_sets_server_time():
|
||||
body = _body([
|
||||
_quote_record(1, "600000", 996, 13224002),
|
||||
_quote_record(1, "510300", 4105, 132245903),
|
||||
])
|
||||
quotes = GetSecurityQuotesCmd([(1, "600000"), (1, "510300")]).parse_response(body)
|
||||
assert [q.server_time for q in quotes] == ["13:22:40.02", "13:22:45.903"]
|
||||
# 价格口径未受影响
|
||||
assert [round(q.price, 3) for q in quotes] == [9.96, 4.105]
|
||||
assert [q.decimal_point for q in quotes] == [2, 3]
|
||||
|
||||
|
||||
def test_parse_response_blank_time_for_index():
|
||||
body = _body([
|
||||
_quote_record(1, "000001", 363808, 12867393),
|
||||
_quote_record(1, "600000", 996, 13179201),
|
||||
])
|
||||
quotes = GetSecurityQuotesCmd([(1, "000001"), (1, "600000")]).parse_response(body)
|
||||
assert quotes[0].server_time == ""
|
||||
assert quotes[1].server_time == "13:17:52.01"
|
||||
Reference in new issue
Block a user