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
+110
View File
@@ -0,0 +1,110 @@
"""查 Bitget candle1m 每条推送里到底带几根 K 线、最新的在哪一端。
归因结果显示 ccxt.pro 比原始 WS 快约 1.4 秒,而两者订阅的是同一条频道。
Hummingbot 的解析取 data["data"][0],我的探针也取 [0],两者一致地慢——
若 Bitget 一条消息里带多根、最新在末尾,取 [0] 就会系统性落后一个滑动窗口。
对每条消息记录:元素个数、首末元素的时间戳、以及首末之差。
若普遍 len>1 且末元素更新,则 [0] 就是那 1.4 秒的来源,且可用一行覆盖修好。
.venv/bin/python research/live/probe_ws_payload.py --minutes 4
"""
from __future__ import annotations
import argparse
import asyncio
import json
import time
from collections import Counter, defaultdict
WSS = "wss://ws.bitget.com/v2/ws/public"
SYMS = ("BTCUSDT", "ETHUSDT", "SOLUSDT")
async def run(minutes: int) -> None:
import aiohttp
payload = {"op": "subscribe",
"args": [{"instType": "USDT-FUTURES", "channel": "candle1m",
"instId": s} for s in SYMS]}
n_elems = Counter()
action_elems = Counter()
# 取 [0] 相对取 [-1] 的落后量:同一根 K 线,两种读法各自首次见到的时刻
first_seen_head: dict = {}
first_seen_tail: dict = {}
n_msg = 0
print(f"[载荷探针] {SYMS} · 跑 {minutes} 分钟", flush=True)
deadline = time.time() + minutes * 60
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
if msg.data == "pong":
continue
d = json.loads(msg.data)
if "data" not in d or "arg" not in d:
continue
arr = d["data"]
if not arr:
continue
n_msg += 1
sym = d["arg"]["instId"].replace("USDT", "")
act = d.get("action")
n_elems[len(arr)] += 1
action_elems[(act, len(arr))] += 1
now_ms = int(time.time() * 1000)
head_ts, tail_ts = int(arr[0][0]), int(arr[-1][0])
first_seen_head.setdefault((sym, head_ts), now_ms)
first_seen_tail.setdefault((sym, tail_ts), now_ms)
if n_msg <= 6 or len(arr) > 1:
print(f" {sym} action={act} 元素数={len(arr)} "
f"首ts={head_ts} 末ts={tail_ts} "
f"跨度={(tail_ts - head_ts) // 1000}s", 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)
print(f"\n########## 每条消息的元素个数分布(共 {n_msg} 条)##########")
for k in sorted(n_elems):
print(f" {k} 根: {n_elems[k]}")
print("\n按 action 拆分:")
for k in sorted(action_elems, key=lambda x: (str(x[0]), x[1])):
print(f" action={k[0]} 元素数={k[1]}: {action_elems[k]}")
# 同一根 K 线,用 [-1] 读比用 [0] 读早多少
lead = defaultdict(list)
for (sym, ts), t_tail in first_seen_tail.items():
t_head = first_seen_head.get((sym, ts))
if t_head is not None:
lead[sym].append(t_head - t_tail)
print("\n########## 取 [-1] 比取 [0] 提前多少(ms##########")
for s in SYMS:
v = sorted(lead[s.replace("USDT", "")])
if not v:
print(f" {s}: 无配对")
continue
print(f" {s}: n={len(v)} 中位 {v[len(v) // 2]}ms 最大 {v[-1]}ms")
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--minutes", type=int, default=4)
asyncio.run(run(ap.parse_args().minutes))
if __name__ == "__main__":
main()