跳到主要内容

K线时间格式规范

本文档描述系统中 K线 (蜡烛图) 数据的时间格式处理规范。


时间格式标准

外部 API 接口

导入/修复端点

  • POST /api/v1/internal/klines/import
  • GET /api/v1/internal/klines/repair

格式: Unix 时间戳 (毫秒)

{
"klines": [
{
"symbol": "BTCUSDT",
"period": "1m",
"open_time": 1704067200000, // 毫秒
"open": "42000.50",
"high": "42100.00",
"low": "41900.00",
"close": "42050.00",
"volume": "123.45"
}
]
}

原因:

  • 匹配 Binance API 格式 (毫秒)
  • JavaScript/前端应用标准
  • 更高精度支持亚秒级数据

查询端点

  • GET /api/v1/markets/{symbol}/candles

输入参数 (from, to): Unix 时间戳 (秒) 响应 (time 字段): Unix 时间戳 (毫秒)

# 请求示例
curl "https://api.axblade.io/api/v1/markets/BTCUSDT/candles?period=5m&from=1704067200&to=1704070800"
{
"symbol": "BTCUSDT",
"period": "5m",
"candles": [
{
"time": 1704067200000, // 响应使用毫秒
"open": "42000.50",
"high": "42100.00",
"low": "41900.00",
"close": "42050.00",
"volume": "123.45"
}
]
}

内部数据结构

HistoricalKline (导入/存储)

pub struct HistoricalKline {
pub open_time: i64, // Unix 时间戳 (毫秒)
// ... 其他字段
}

用于:

  • 从外部源批量导入
  • 修复操作
  • 数据库写入

Candle (内存)

pub struct Candle {
pub time: i64, // Unix 时间戳 (秒)
// ... 其他字段
}

用于:

  • 内存缓存
  • 实时更新
  • 内部计算

注意: 遗留设计使用秒作为内存表示,API 响应时转换为毫秒。


数据库存储

: klines_historical : open_time TIMESTAMPTZ

数据库使用 PostgreSQL TIMESTAMPTZ 类型,自动处理转换:

  • 输入: 通过 chrono::DateTime::from_timestamp_millis() 从毫秒转换
  • 输出: 通过 .timestamp() 返回秒,然后转换为毫秒

转换流程

导入/修复流程

Binance API (ms)
→ HistoricalKline.open_time (ms)
→ from_timestamp_millis() → TIMESTAMPTZ
→ Database
→ Candle.time (s) for in-memory cache
→ API Response (ms)

查询流程

Database TIMESTAMPTZ
→ .timestamp() → Candle.time (s)
→ * 1000 → API Response (ms)

重要注意事项

  1. 导入/修复端点始终使用毫秒
  2. 数据库比较: 直接查询 klines_historical 时使用 TIMESTAMPTZ 比较
  3. Binance API: 始终返回毫秒,修复端点无需转换
  4. 前端/JavaScript: 使用毫秒 (Date 对象标准)

代码引用

文件功能
backend/src/api/handlers/kline.rs - ImportKlineDto导入 DTO
backend/src/api/handlers/kline.rs - repair_klines()修复处理器
backend/src/services/kline/mod.rs - HistoricalKline历史类型
backend/src/services/kline/mod.rs - Candle内存类型
backend/src/services/kline/mod.rs - save_klines_batch()保存函数

迁移说明

日期: 2025-12-27

从存储秒改为存储毫秒用于导入的 K线数据:

  • 匹配 Binance API 格式
  • 保持与外部数据源的一致性
  • 需要时提供亚秒级精度

破坏性变更: 如果有现有的脚本或工具调用导入/修复端点,请确保它们提供毫秒时间戳,而不是秒。