auto_trade_sys/docs/DB与币安订单对账说明.md
薇薇安 fc6c31dd5d feat(user_data_stream): 增强订单和算法更新事件的日志记录
在 `user_data_stream.py` 中为 `ORDER_TRADE_UPDATE` 和 `ALGO_UPDATE` 事件添加了日志记录功能,确保在接收到相关推送时能够记录事件信息。这一改进提升了系统的可追踪性和调试能力。
2026-02-21 17:09:41 +08:00

104 lines
3.0 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# DB 与币安订单对账说明
## 一、查询系统今日落入 DB 的单子
### 1. 命令行脚本(推荐)
```bash
# 今日、默认账号、按创建时间(落库时间)
python scripts/query_trades_today.py
# 指定账号
python scripts/query_trades_today.py --account 2
# 指定日期
python scripts/query_trades_today.py --date 2026-02-21
# 按入场时间筛选
python scripts/query_trades_today.py --time-filter entry
# 仅可对账记录(有开仓/平仓订单号)
python scripts/query_trades_today.py --reconciled-only
# 导出到 JSON 文件
python scripts/query_trades_today.py -o today_trades.json
```
### 2. API 接口
```
GET /api/trades?period=today&time_filter=created&reconciled_only=false
```
- `period=today`:今天
- `time_filter=created`:按创建时间(落库时间),便于对照「何时写入 DB」
- `time_filter=entry`:按入场时间
- `time_filter=exit`:按平仓时间
- `reconciled_only=false`:包含所有记录(含取消、无订单号)
### 3. 前端导出
交易记录页面 → 选择「今天」→ 导出 JSON / Excel。
---
## 二、币安订单推送日志
系统会将收到的 **ORDER_TRADE_UPDATE**、**ALGO_UPDATE** 写入日志,便于与 DB 对照。
### 日志路径
```
{项目根}/logs/binance_order_events.log
```
### 格式
每行一条 JSON例如
```json
{"ts":1737500000000,"event_type":"ORDER_TRADE_UPDATE","account_id":1,"E":1737500000123,"symbol":"BTCUSDT","orderId":123456,"clientOrderId":"SYS_1737500000_abcd","event":"TRADE","status":"FILLED","reduceOnly":false,"avgPrice":"95000","executedQty":"0.01","realizedPnl":"0"}
```
### 字段说明
| 字段 | 说明 |
|------|------|
| ts | 本机接收时间戳 |
| event_type | ORDER_TRADE_UPDATE / ALGO_UPDATE |
| account_id | 账号 ID |
| E | 币安事件时间(毫秒) |
| symbol | 交易对 |
| orderId | 币安订单号 |
| clientOrderId | 自定义订单号(系统前缀) |
| event | NEW/TRADE/CANCELED |
| status | NEW/FILLED/CANCELED 等 |
| reduceOnly | 是否只减仓(平仓单) |
| avgPrice/executedQty | 成交价/成交量FILLED 时) |
| realizedPnl | 实现盈亏(平仓时) |
| algoId/triggeredOrderId | ALGO_UPDATE 专用 |
### 对账用法
```bash
# 查看今天收到的所有订单推送
grep "ORDER_TRADE_UPDATE" logs/binance_order_events.log
# 查看 FILLED 成交
grep '"status":"FILLED"' logs/binance_order_events.log
# 按 clientOrderId 对照
grep "SYS_1737500000_abcd" logs/binance_order_events.log
```
---
## 三、对账流程建议
1. **查 DB 今日记录**`python scripts/query_trades_today.py -o db_today.json`
2. **查币安推送日志**`tail -f logs/binance_order_events.log` 或 `grep "ORDER_TRADE_UPDATE" logs/binance_order_events.log`
3. **对照**:用 `clientOrderId``orderId` 关联 DB 记录与推送日志,确认:
- DB 有 pending 且收到 FILLED 推送 → 应更新为 open
- DB 有 open 且收到 reduceOnly FILLED → 应更新 exit_order_id
- 收到推送但 DB 无对应记录 → 可能漏建或为手动单