API 参考 / 实时数据

实时数据(WebSocket)

按 topic 订阅的 WebSocket 流。公开 topic 无需鉴权;私有 topic 在订阅帧里带会话 token。流只推增量,权威状态从 REST 获取。

连接

地址ws://127.0.0.1:8090/api/v1/stream
鉴权公开 topic 无需鉴权;私有 topic 在 subscribe 帧的 token 字段带会话 Bearer token(只读校验,不消费会话)。
握手令牌交易线 WS 另有短时握手令牌:POST /api/v1/ws/handshake-token
浏览器同源代理只转发 REST,WebSocket 需直连流地址或由部署层反代升级。

协议帧

入站(客户端 → 服务端)
{ "op": "subscribe",   "topic": "px.crypto.BTC" }
{ "op": "subscribe",   "topic": "private.0x3f1a…9c2e.px", "token": "<session bearer token>" }
{ "op": "unsubscribe", "topic": "px.crypto.BTC" }
出站(服务端 → 客户端)
{ "op": "subscribed", "topic": "px.crypto.BTC", "needsSnapshot": true, "currentSequence": 184 }
{ "op": "message",    "topic": "px.crypto.BTC", "sequence": 185, "serverTime": 1758240000000,
  "type": "tick", "data": { "symbol": "BTC", "priceText": "118425.50", "tsMs": 1758240000000 } }
{ "op": "error",      "topic": "private.0x…px", "message": "token address does not match topic" }

Topic 字典

topic鉴权data说明
px.crypto.{coin}公开{ "symbol": "BTC", "priceText": "118425.50", "tsMs": 1758240000000 }现货价(Pyth 行情)。全字符串,priceText 口径与 REST 历史端点一致。
px.updown.{series}公开{ "series": "btc-5m", "marketId": "px-btc-5m-…", "roundStartMs": …, "roundEndMs": …, "resolution": null }轮次边界事件,type = rotate | resolved。收到即重新拉 GET /px/updown;payload 不含行情。
private.{address}.px订阅帧带 Bearer 会话 token{ "kind": "orders" | "positions" | "fills" }账户变更通知。token 归属地址必须与 topic 一致,不一致只拒这条订阅、不断连接;明细一律走 REST 重取。

消费纪律

  1. 流只推增量,不补发历史。重连后先通过 REST 拉取挂单、成交与账户状态,再消费新事件。
  2. sequence 在单个连接内单调连续,跨连接可能归零。用它检测同一连接内的丢帧,不用于跨连接对账。
  3. 订阅可在不断连的情况下增减。每条 subscribe / unsubscribe 独立应答,一条被拒不影响其他 topic。
  4. subscribed 帧带 needsSnapshot: true 与 currentSequence。收到后通过 REST 拉取快照,之后从 currentSequence + 1 开始消费增量。
  5. 挂单保护由 REST 心跳(cancel-on-disconnect)负责,与流的连接状态无关。见 Market Maker API。

示例:订阅并处理丢帧

const ws = new WebSocket("ws://127.0.0.1:8090/api/v1/stream");
let expected: number | undefined;

ws.onopen = () => {
  ws.send(JSON.stringify({ op: "subscribe", topic: "px.crypto.BTC" }));
};

ws.onmessage = async (event) => {
  const frame = JSON.parse(event.data);
  if (frame.op === "subscribed") {
    expected = frame.currentSequence + 1;
    await loadSnapshotOverRest(); // 先拉快照,再消费增量
    return;
  }
  if (frame.op === "message") {
    if (expected !== undefined && frame.sequence !== expected) {
      // 丢帧:单连接内 sequence 必须连续。重建快照,不要试图补洞。
      await loadSnapshotOverRest();
    }
    expected = frame.sequence + 1;
    apply(frame.type, frame.data);
  }
};