4ef33a367f
Resolve CZCE/DCE symbols to the correct exchange for orders, dedupe stop-loss closes and trade logs, and rely on CTP sync for authoritative records. Co-authored-by: Cursor <cursoragent@cursor.com>
120 lines
4.0 KiB
Python
120 lines
4.0 KiB
Python
# Copyright (c) 2025-2026 马建军. All rights reserved.
|
|
# 专有软件 — 未经授权禁止复制、传播、转售。
|
|
# 严禁用于:带单/代客理财、向他人推荐期货品种或买卖建议、融资配资等业务。
|
|
# 详见 LICENSE.zh-CN.txt 与 docs/软件购买与使用协议.md
|
|
|
|
"""交易记录:字段补全、资金曲线数据。"""
|
|
from __future__ import annotations
|
|
|
|
from typing import Any
|
|
|
|
|
|
TRADE_LOG_EXTRA_COLUMNS = (
|
|
"ALTER TABLE trade_logs ADD COLUMN margin_pct REAL",
|
|
"ALTER TABLE trade_logs ADD COLUMN equity_after REAL",
|
|
"ALTER TABLE trade_logs ADD COLUMN source TEXT DEFAULT 'local'",
|
|
"ALTER TABLE trade_logs ADD COLUMN ctp_trade_key TEXT",
|
|
)
|
|
|
|
|
|
def ensure_trade_log_columns(conn) -> None:
|
|
for sql in TRADE_LOG_EXTRA_COLUMNS:
|
|
try:
|
|
conn.execute(sql)
|
|
except Exception:
|
|
pass
|
|
|
|
|
|
def calc_equity_after(capital: float, pnl_net: float) -> float | None:
|
|
cap = float(capital or 0)
|
|
if cap <= 0:
|
|
return None
|
|
return round(cap + float(pnl_net or 0), 2)
|
|
|
|
|
|
def _norm_symbol(symbol: str) -> str:
|
|
return (symbol or "").split(".")[0].strip().lower()
|
|
|
|
|
|
def _norm_close_minute(ts: str) -> str:
|
|
"""统一 close_time 到分钟粒度,兼容 ISO `T` 与空格分隔。"""
|
|
return (ts or "").strip().replace("T", " ")[:16]
|
|
|
|
|
|
def purge_duplicate_local_trade_logs(conn) -> int:
|
|
"""删除已被 CTP 柜台记录覆盖的本地重复成交。"""
|
|
removed = 0
|
|
ctp_rows = [
|
|
dict(r)
|
|
for r in conn.execute("SELECT * FROM trade_logs WHERE source='ctp'").fetchall()
|
|
]
|
|
local_rows = [
|
|
dict(r)
|
|
for r in conn.execute(
|
|
"""SELECT * FROM trade_logs
|
|
WHERE COALESCE(source, 'local') != 'ctp'
|
|
AND (ctp_trade_key IS NULL OR ctp_trade_key = '')"""
|
|
).fetchall()
|
|
]
|
|
for ctp in ctp_rows:
|
|
ct16 = _norm_close_minute(ctp.get("close_time") or "")
|
|
sym_n = _norm_symbol(ctp.get("symbol") or "")
|
|
lots = float(ctp.get("lots") or 0)
|
|
direction = (ctp.get("direction") or "long").strip().lower()
|
|
for loc in local_rows:
|
|
if loc.get("id") == ctp.get("id"):
|
|
continue
|
|
if _norm_symbol(loc.get("symbol") or "") != sym_n:
|
|
continue
|
|
if (loc.get("direction") or "long").strip().lower() != direction:
|
|
continue
|
|
if _norm_close_minute(loc.get("close_time") or "") != ct16:
|
|
continue
|
|
if abs(float(loc.get("lots") or 0) - lots) > 0.01:
|
|
continue
|
|
conn.execute("DELETE FROM trade_logs WHERE id=?", (loc["id"],))
|
|
removed += 1
|
|
return removed
|
|
|
|
|
|
def enrich_trades_for_records(
|
|
trades: list[dict[str, Any]],
|
|
*,
|
|
initial_capital: float = 0.0,
|
|
) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
|
|
"""表格仍按 id 降序;资金曲线按平仓时间升序用最新资金绘制。"""
|
|
rows = [dict(t) for t in trades]
|
|
chrono = sorted(
|
|
rows,
|
|
key=lambda t: ((t.get("close_time") or ""), int(t.get("id") or 0)),
|
|
)
|
|
running = float(initial_capital or 0)
|
|
curve: list[dict[str, Any]] = []
|
|
|
|
for t in chrono:
|
|
pnl_net = float(t.get("pnl_net") or 0)
|
|
eq = t.get("equity_after")
|
|
if eq is None:
|
|
if running > 0:
|
|
eq = round(running + pnl_net, 2)
|
|
else:
|
|
eq = None
|
|
t["equity_after"] = eq
|
|
if eq is not None:
|
|
running = float(eq)
|
|
|
|
if t.get("margin_pct") is None:
|
|
margin = float(t.get("margin") or 0)
|
|
cap_before = float(eq or 0) - pnl_net if eq is not None else 0.0
|
|
if margin > 0 and cap_before > 0:
|
|
t["margin_pct"] = round(margin / cap_before * 100, 2)
|
|
|
|
if eq is not None:
|
|
curve.append({
|
|
"time": (t.get("close_time") or "")[:19],
|
|
"value": float(eq),
|
|
"id": int(t.get("id") or 0),
|
|
})
|
|
|
|
return rows, curve
|