Skip to content

K 线对接 v2 ​

概述 ​

K 线 v2 使用 HTTP 历史查询 + WebSocket 实时快照/增量修正 的模式。

相较旧版接入,v2 的关键变化是:

  1. HTTP 查询已接入 realtime CAGG + raw overlay,当前 candle 会随新成交持续更新。
  2. WS 订阅成功后,如果存在最新 K 线,服务端会先推送一帧 type=kline 快照。
  3. WS 不只会推送当前桶,也可能推送历史 bucket 的权威修正。
  4. WS 新增 type=kline_removed 删除帧,前端需要按 bucket 删除本地 candle。
  5. isFinal 表示时间桶闭合,但后续仍可能收到同 bucket 的修正包。

本文只整理 K 线部分;深度图与池子逐笔成交的 realtime 规则请放在各自接口文档中维护。

通用约定 ​

项目说明
接口前缀DEX 接口实际挂载前缀通常为 /api/v1
network_id必须使用 canonical 格式,如 topo--164、aptos--2
pool_address后端会标准化为小写 0x...,前端本地 key 也建议统一小写
HTTP wrapper timestamp毫秒,表示服务端响应时间
WS envelope timestamp毫秒,表示服务端发包时间
K 线 data.timestamp秒,表示 candle bucket start

HTTP 响应统一包装:

json
{
  "code": 0,
  "message": "Success",
  "data": {},
  "timestamp": 1781777827000
}

部分 nullable 字段在 JSON 中可能被省略,而不是显式返回 null。前端类型应按 undefined | null 处理:

  • volume_usd:缺 USD 估值时可能不存在。
  • lastTradeTime:没有成交时间时可能不存在。

历史 K 线查询 ​

http
POST /api/v1/dex/klines/query

请求体:

json
{
  "network_id": "topo--164",
  "pool_address": "0x...",
  "interval": "1m",
  "start_time": 1781777400,
  "end_time": 1781778000,
  "limit": 500,
  "force_refresh": false
}

请求字段 ​

字段类型必填说明
network_idstring是canonical network id,不要传旧 chain_id 或 bare chain 名称
pool_addressstring是池子地址
intervalstring是支持 1m、5m、15m、30m、1h、4h、1d、1W、1M
start_timenumber是起始秒级 Unix 时间戳
end_timenumber是结束秒级 Unix 时间戳
limitnumber否返回条数上限,建议 <= 500
force_refreshboolean否true 跳过 Redis 读缓存,直接查 Fresh DB;普通页面刷新不需要常开

1M 表示月,1m 表示分钟,大小写不能混用。

响应示例 ​

json
{
  "code": 0,
  "message": "Success",
  "data": {
    "klines": [
      {
        "timestamp": 1781777820,
        "open": "63100.1",
        "high": "63200.2",
        "low": "63010.3",
        "close": "63180.4",
        "volume_x": "12300000000",
        "volume_y": "456000000",
        "volume_usd": "789.12",
        "volumeUsdMissingCount": 0,
        "trade_count": 12,
        "isFinal": false,
        "lastTradeTime": 1781777826389
      }
    ],
    "pool_address": "0x...",
    "network_id": "topo--164",
    "interval": "1m",
    "count": 1
  },
  "timestamp": 1781777827000
}

K 线字段 ​

字段类型说明
timestampnumbercandle bucket start,秒级时间戳
open/high/low/closestring标准单位价格,统一为 token_b / token_a
volume_xstringX 侧 token raw amount
volume_ystringY 侧 token raw amount
volume_usdstringUSD 成交额;缺失表示未知,不等于 "0"
volumeUsdMissingCountnumber该 candle 中缺少 USD 估值的成交数量
trade_countnumber桶内成交笔数
isFinalbooleancandle 时间桶是否闭合
lastTradeTimenumber最近一笔成交时间,毫秒

前端展示注意点:

  • open/high/low/close 与深度图 mid_price、池子成交 price 同量级,都是 token_b / token_a。
  • volume_x / volume_y 是 raw amount,展示时按 token decimals 格式化。
  • 图表库若只接受 number,可在适配层转换;业务类型仍建议保留 string,避免精度损耗扩散。
  • volume_usd 缺失时展示为未知或隐藏,不要显示为 0。

最新 K 线查询 ​

http
POST /api/v1/dex/klines/latest

请求体:

json
{
  "network_id": "topo--164",
  "pool_address": "0x...",
  "interval": "1m",
  "force_refresh": false
}

响应 data 为单根 K 线或 null。

该接口优先返回 realtime latest;低频池子如果当前窗口无成交,会返回最后一根已存在 K 线。

WebSocket 订阅 ​

默认 WS 端点:

text
/api/v1/ws/dex

生产启用认证时,连接后第一帧必须发送认证消息。支持 token 或 api_key:

json
{
  "action": "auth",
  "api_key": "<api-key>",
  "request_id": "auth-1"
}

认证成功:

json
{
  "type": "authenticated",
  "user_id": "xxx",
  "request_id": "auth-1"
}

订阅 K 线:

json
{
  "action": "subscribe",
  "topic": "kline",
  "network_id": "topo--164",
  "pool_address": "0x...",
  "interval": "1m",
  "request_id": "kline-1"
}

服务端顺序:

  1. 返回 type=subscribed ACK。
  2. 如果存在最新 K 线,发送一帧 type=kline 快照。
  3. 后续按 affected bucket 推送增量或修正。

ACK 示例:

json
{
  "type": "subscribed",
  "topic": "kline",
  "network_id": "topo--164",
  "pool_address": "0x...",
  "interval": "1m",
  "request_id": "kline-1"
}

数据帧:

json
{
  "type": "kline",
  "network_id": "topo--164",
  "pool_address": "0x...",
  "interval": "1m",
  "data": {
    "timestamp": 1781777820,
    "open": "63100.1",
    "high": "63200.2",
    "low": "63010.3",
    "close": "63180.4",
    "volume_x": "12300000000",
    "volume_y": "456000000",
    "volume_usd": "789.12",
    "volumeUsdMissingCount": 0,
    "trade_count": 12,
    "isFinal": false,
    "lastTradeTime": 1781777826389
  },
  "timestamp": 1781777827000
}

删除帧:

json
{
  "type": "kline_removed",
  "network_id": "topo--164",
  "pool_address": "0x...",
  "interval": "1m",
  "bucket_timestamp": 1781777820,
  "timestamp": 1781777827000
}

前端状态规则 ​

建议本地按 (network_id, pool_address, interval, candle.timestamp) 作为 candle 幂等 key。

消息处理规则
type=kline 且本地已有相同 data.timestampreplace 该 candle
type=kline 且 data.timestamp 更大append 新 candle
type=kline 且 data.timestamp 更小仍可能是历史 bucket 权威修正,应按 timestamp replace,不要直接丢弃
type=kline_removed删除 bucket_timestamp 对应 candle;本地不存在则忽略
isFinal=false当前 candle 后续仍会被同 timestamp 消息覆盖
isFinal=true时间桶已闭合;后续若收到同 timestamp 且 envelope timestamp 更新的修正包,仍应接受

为了避免旧包覆盖新包,前端可以为每个 candle 记录最后处理过的 WS envelope timestamp:

ts
const candleKey = `${networkId}:${poolAddress.toLowerCase()}:${interval}:${candle.timestamp}`

if ((lastEnvelopeTimestampByKey[candleKey] ?? 0) <= message.timestamp) {
  upsertCandle(candle)
  lastEnvelopeTimestampByKey[candleKey] = message.timestamp
}

图表适配建议 ​

如果图表库使用毫秒时间戳,适配层统一做秒/毫秒转换:

ts
const toChartTimestamp = (timestamp: number) => {
  return timestamp < 1e12 ? timestamp * 1000 : timestamp
}

const toApiTimestamp = (timestamp: number) => {
  return Math.floor(timestamp / 1000)
}

示例转换:

ts
const toChartKLineData = (item: KlineData) => ({
  timestamp: toChartTimestamp(item.timestamp),
  open: Number(item.open),
  high: Number(item.high),
  low: Number(item.low),
  close: Number(item.close),
  volume: item.volume_usd == null ? undefined : Number(item.volume_usd),
})

错误处理 ​

WS 错误帧:

json
{
  "type": "error",
  "code": "INVALID_REQUEST",
  "message": "network_id must be canonical",
  "request_id": "..."
}

常见 code:

code说明
AUTH_FAILED / AUTH_TIMEOUT / RATE_LIMITED认证失败、认证超时或限流
INVALID_REQUEST请求结构或参数错误
INVALID_INTERVALK 线 interval 不支持
INVALID_POOL池子不存在
MAX_SUBSCRIPTIONS单连接订阅数超过上限
BACKPRESSURE_RECONNECT发送队列满,建议重连并重新订阅
INTERNAL_ERROR临时服务端错误,可重试或重连

HTTP 中 token metadata 缺失通常表现为 400,message 包含 pool token metadata missing。前端应展示“数据准备中/暂不可用”,不要当作空 K 线。

推荐类型 ​

ts
type ApiResponse<T> = {
  code: number
  message: string
  data?: T | null
  timestamp: number
}

type KlineData = {
  timestamp: number // bucket start, seconds
  open: string
  high: string
  low: string
  close: string
  volume_x: string
  volume_y: string
  volume_usd?: string | null
  volumeUsdMissingCount: number
  trade_count: number
  isFinal: boolean
  lastTradeTime?: number | null // ms
}

type KlineMessage =
  | {
      type: 'kline'
      network_id: string
      pool_address: string
      interval: string
      data: KlineData
      timestamp: number // envelope ms
    }
  | {
      type: 'kline_removed'
      network_id: string
      pool_address: string
      interval: string
      bucket_timestamp: number // bucket start, seconds
      timestamp: number // envelope ms
    }

前端适配清单 ​

  1. 所有 K 线请求统一传 canonical network_id,不要再传 chain_id。
  2. K 线类型新增 isFinal、lastTradeTime、volumeUsdMissingCount。
  3. volume_usd 改成 optional;缺失时展示为未知或隐藏,不显示为 0。
  4. HTTP 与 WS 的 data.timestamp 都按秒级 bucket start 处理。
  5. 图表库需要毫秒时,只在 datafeed / adapter 层转换。
  6. WS 支持同 timestamp replace、旧 bucket replace 和 kline_removed。
  7. isFinal=true 之后仍接受服务端后续修正包。
  8. 断线重连后重新认证、重新订阅,并用服务端快照重建本地状态。