6e423eebfb
新增 vnpy CTP 桥接、以损定仓/固定张数、趋势回调与滚仓策略、按资金推荐品种及交易风控;模拟盘走 SimNow,实盘预留期货公司配置。 Co-authored-by: Cursor <cursoragent@cursor.com>
71 lines
1.9 KiB
Python
71 lines
1.9 KiB
Python
"""策略结束快照。"""
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
from datetime import datetime
|
|
from typing import Any
|
|
|
|
STRATEGY_TREND = "trend_pullback"
|
|
STRATEGY_ROLL = "roll"
|
|
MAX_ROWS = 100
|
|
|
|
|
|
def save_snapshot(
|
|
conn,
|
|
*,
|
|
strategy_type: str,
|
|
source_id: int,
|
|
symbol: str,
|
|
direction: str,
|
|
result_label: str,
|
|
payload: dict,
|
|
pnl: float | None = None,
|
|
opened_at: str = "",
|
|
) -> None:
|
|
now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
|
conn.execute(
|
|
"""INSERT INTO strategy_trade_snapshots (
|
|
strategy_type, source_id, symbol, direction, result_label,
|
|
opened_at, closed_at, pnl_amount, snapshot_json, created_at
|
|
) VALUES (?,?,?,?,?,?,?,?,?,?)""",
|
|
(
|
|
strategy_type,
|
|
source_id,
|
|
symbol,
|
|
direction,
|
|
result_label,
|
|
opened_at,
|
|
now,
|
|
pnl,
|
|
json.dumps(payload, ensure_ascii=False),
|
|
now,
|
|
),
|
|
)
|
|
conn.execute(
|
|
"""DELETE FROM strategy_trade_snapshots WHERE id NOT IN (
|
|
SELECT id FROM strategy_trade_snapshots ORDER BY id DESC LIMIT ?
|
|
)""",
|
|
(MAX_ROWS,),
|
|
)
|
|
|
|
|
|
def list_snapshots(conn, limit: int = 100) -> tuple[list[dict], list[dict]]:
|
|
rows = conn.execute(
|
|
"SELECT * FROM strategy_trade_snapshots ORDER BY id DESC LIMIT ?",
|
|
(max(1, min(limit, 200)),),
|
|
).fetchall()
|
|
trend, roll = [], []
|
|
for r in rows:
|
|
d = dict(r)
|
|
try:
|
|
d["snapshot"] = json.loads(d.get("snapshot_json") or "{}")
|
|
except Exception:
|
|
d["snapshot"] = {}
|
|
st = d.get("strategy_type")
|
|
d["strategy_label"] = "趋势回调" if st == STRATEGY_TREND else "顺势加仓"
|
|
if st == STRATEGY_TREND:
|
|
trend.append(d)
|
|
else:
|
|
roll.append(d)
|
|
return trend, roll
|