research: 影子交易器落在 Hummingbot 上,并修掉 Bitget 连接器的换根延迟

1m 腿的滑点余量只有几个 bp,所以要测的必须是生产路径的滑点——换个运行时
测出来的数就不作数。框架因此从「滑点已知后再定」提前到测量阶段就定为
Hummingbot(Spot/Perp 连接器均 v2.0,Bitget 是 Foundation Partner)。

新增 research/live/。前置测量:

- bench_compute.py 本机算力,1m 单币 0.318s、三币串行 1.38s
- venue_parity.py Binance 与 Bitget 同根信号重合仅 14.6~42.6%
- signal_sensitivity.py 0.25bp 扰动就换掉一半信号
- aggregate_robustness.py 但总体期望不降——脆的是信号身份,不是 alpha
- bitget_baseline.py 因此改用 Bitget 原生基线定预算:余量 BTC -0.13bp、
  ETH +4.02bp、SOL +2.92bp。BTC 本就为负,只作延迟测量的参照物

运行时选型:

- parity_env.py 容器与本机信号逐一相同(下标、中枢数、checksum 全等),
  容器内 0.26s/币反而更快。故 chanlun 直接挂载进容器,不必另起信号服务。
  装进现有 .venv 那条路走不通:Hummingbot 要 numba>=0.61.2 与
  aiohttp<3.14,与本机 Python 3.14 冲突
- latency_ccxt.py / latency_hummingbot.py / latency_compare.py 初测显示
  Hummingbot 比 ccxt.pro 慢约 1030ms,90 根逐根配对里 80~97% 更慢
- probe_ws_action.py 否掉「丢弃 snapshot」的猜测:换根首条就是 update
- probe_hb_vs_raw.py 与 latency_attribute.py 四路归因——容器网络 2~18ms、
  Hummingbot 处理 -10~-30ms,1350~1480ms 全落在解析方式上
- probe_ws_payload.py 定位根因:Bitget 换根会推一条带两根的消息
  [上一根, 新一根],而上游取 data["data"][0] 拿到的是上一根,新一根要等
  下一条单元素消息

修复:

- patched_candles.py 处理消息里的全部元素。不能简单改成 [-1]——那样上一根
  的收盘价会永远停在换根前约 1 秒的那次推送上,而信号对 0.25bp 都敏感
- verify_patch.py 60 根配对验证:拿回 1060~1090ms,与原始 WS 只差 5~14ms
  已贴理论下限,19 根已收盘 K 线 OHLCV 逐根未变。折算 ETH 省 0.54bp、
  SOL 省 0.42bp。此 bug 值得向上游反馈

影子交易器:

- shadow_hb.py 不下单,读连接器真实盘口按仓位吃单深度算成交价,与次根开盘价
  (回测 entry_delay=1 的口径)相减,分解成延迟漂移、盘口价差、深度冲击。
  盘口 10Hz 滚动缓冲 30 秒,把延迟变成自变量:每个信号记 0.5/1/2/5s 与实际
  算完时刻各一个滑点值,本机算得慢也不影响能读出的曲线
- shadow_signal.py 信号计算隔离到子进程。0.26s 是纯 CPU 且 chanlun 受 GIL
  限制,放进 asyncio 循环会把行情处理一起卡住
- shadow_report.py 首日延迟门槛与滑点曲线报表

不用 paper trade 测滑点:它的成交由 Hummingbot 自己的撮合模型模拟,
测出来是模型行为而非市场行为。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Ubuntu
2026-08-27 23:51:57 +08:00
co-authored by Cursor
parent 66061f79a1
commit 7e339d2a54
44 changed files with 11946 additions and 0 deletions
+156
View File
@@ -0,0 +1,156 @@
"""验证 Hummingbot 那 1030ms 的来源:Bitget candle1m 的 snapshot / update 序列。
Hummingbot 的 bitget_perpetual candles feed 里有这么一句:
if data and data.get("data") and data["action"] == "update":
action == "snapshot" 的消息被整条丢弃。若新 K 线的首条推送恰是 snapshot,
Hummingbot 就必须等到下一条 update 才知道换根了,代价约等于一个推送间隔。
本脚本直接连原始 WS,对每条消息记录 action、K 线时间戳、到达时刻,
然后针对每次换根回答两件事:
1. 首条带新时间戳的消息,action 是什么
2. 若是 snapshot,到首条 update 之间隔了多久(= Hummingbot 白等的时间)
.venv/bin/python research/live/probe_ws_action.py --minutes 6
"""
from __future__ import annotations
import argparse
import asyncio
import json
import time
from collections import defaultdict
from pathlib import Path
WSS = "wss://ws.bitget.com/v2/ws/public"
SYMS = ("BTCUSDT", "ETHUSDT", "SOLUSDT")
OUT = Path(__file__).resolve().parents[1] / "out" / "probe_ws_action.csv"
async def run(minutes: int) -> None:
import csv
import aiohttp
payload = {"op": "subscribe",
"args": [{"instType": "USDT-FUTURES", "channel": "candle1m",
"instId": s} for s in SYMS]}
n_rows = 0
# 每个币记录:当前时间戳、该时间戳下已见过的 action 序列
cur: dict[str, int] = {}
seen: dict[str, list] = defaultdict(list)
rollovers: list[dict] = []
cnt: dict = defaultdict(lambda: defaultdict(int))
# 边收边写:进程若被杀,已采到的样本仍在盘上
OUT.parent.mkdir(parents=True, exist_ok=True)
fh = OUT.open("w", newline="")
w = csv.DictWriter(fh, fieldnames=["t_ms", "sym", "action", "kline_ts"])
w.writeheader()
print(f"[原始 WS 探针] {SYMS} · candle1m · 跑 {minutes} 分钟", flush=True)
deadline = time.time() + minutes * 60
try:
while time.time() < deadline:
try:
async with aiohttp.ClientSession() as sess, \
sess.ws_connect(WSS, heartbeat=20) as ws:
await ws.send_str(json.dumps(payload))
while time.time() < deadline:
msg = await ws.receive(timeout=30)
# 断开后 receive() 会立刻返回 CLOSED;这里若只 continue
# 就成了无等待空转,必须跳出去重连
if msg.type is not aiohttp.WSMsgType.TEXT:
print(f" 非文本消息 {msg.type},重连", flush=True)
break
raw = msg.data
if raw == "pong":
continue
try:
d = json.loads(raw)
except Exception:
continue
if "data" not in d or "arg" not in d:
if d.get("event"):
print(f" 事件: {d}", flush=True)
continue
now_ms = int(time.time() * 1000)
sym = d["arg"]["instId"]
action = d.get("action")
kts = int(d["data"][0][0])
w.writerow({"t_ms": now_ms, "sym": sym,
"action": action, "kline_ts": kts})
n_rows += 1
cnt[sym][action] += 1
if n_rows % 50 == 0:
fh.flush()
prev = cur.get(sym)
if prev is None:
cur[sym] = kts
seen[sym] = [(action, now_ms)]
continue
if kts > prev:
cur[sym] = kts
seen[sym] = [(action, now_ms)]
rollovers.append({"sym": sym, "kline_ts": kts,
"first_action": action,
"first_ms": now_ms})
print(f" {sym} 换根 -> 首条 action={action}",
flush=True)
else:
seen[sym].append((action, now_ms))
# 若首条是 snapshot,找该时间戳下首条 update 的延后量
for r in rollovers:
if (r["sym"] == sym and r["kline_ts"] == kts
and r["first_action"] == "snapshot"
and "gap_to_update_ms" not in r
and action == "update"):
r["gap_to_update_ms"] = now_ms - r["first_ms"]
print(f" {sym} snapshot->update 间隔 "
f"{r['gap_to_update_ms']}ms", flush=True)
except asyncio.CancelledError:
raise
except Exception as e:
print(f" 连接异常 {type(e).__name__}: {e}1s 后重连", flush=True)
# 重连前固定歇一下,避免服务端持续拒绝时打成重连风暴
if time.time() < deadline:
await asyncio.sleep(1)
finally:
fh.close()
print(f"\n########## 消息构成(共 {n_rows} 条)##########")
for s in SYMS:
print(f" {s}: {dict(cnt[s])}")
print(f"\n########## 换根时首条消息的 action{len(rollovers)} 次)##########")
by = defaultdict(lambda: defaultdict(int))
gaps = defaultdict(list)
for r in rollovers:
by[r["sym"]][r["first_action"]] += 1
if "gap_to_update_ms" in r:
gaps[r["sym"]].append(r["gap_to_update_ms"])
for s in SYMS:
g = sorted(gaps[s])
med = g[len(g) // 2] if g else None
print(f" {s}: 首条 action 分布 {dict(by[s])}"
+ (f" · snapshot->update 中位 {med}msn={len(g)}" if g else ""))
all_g = sorted(x for v in gaps.values() for x in v)
if all_g:
print(f"\n合计 snapshot->update 中位 {all_g[len(all_g) // 2]}ms "
f"n={len(all_g)})——这就是 Hummingbot 因丢弃 snapshot 白等的时间")
print(f"\n产物写入 {OUT}")
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--minutes", type=int, default=6)
asyncio.run(run(ap.parse_args().minutes))
if __name__ == "__main__":
main()