4a5d19e30f
Co-authored-by: Cursor <cursoragent@cursor.com>
307 lines
10 KiB
Python
307 lines
10 KiB
Python
from __future__ import annotations
|
|
|
|
from typing import Annotated, Any
|
|
|
|
from fastapi import APIRouter, Depends, HTTPException
|
|
|
|
from ..models.db import get_db
|
|
from ..sim.pnl import summarize_fills_pnl
|
|
from .auth import require_user
|
|
from .hold_timing import hold_timing
|
|
|
|
router = APIRouter(prefix="/api/trades", tags=["trades"])
|
|
|
|
|
|
def _row(r: Any) -> dict:
|
|
return dict(r)
|
|
|
|
|
|
def _is_oo_group(g: dict) -> bool:
|
|
return (
|
|
str(g.get("hedge_mode") or "") == "option_option"
|
|
or bool(g.get("option2_inst_id"))
|
|
or str(g.get("bias") or "") == "option_option"
|
|
)
|
|
|
|
|
|
def _infer_settle_index(g: dict, fills: list) -> float | None:
|
|
settle_index = g.get("settle_index_px")
|
|
if settle_index is not None:
|
|
try:
|
|
v = float(settle_index)
|
|
if v > 0:
|
|
return v
|
|
except (TypeError, ValueError):
|
|
pass
|
|
strike = g.get("strike")
|
|
side = str(g.get("option_side") or "").lower()
|
|
if strike is None:
|
|
return None
|
|
for raw in fills:
|
|
f = dict(raw) if not isinstance(raw, dict) else raw
|
|
if str(f.get("leg")) != "option" or str(f.get("action")) != "close":
|
|
continue
|
|
if abs(float(f.get("slip") or 0)) > 1e-12:
|
|
continue
|
|
px = float(f.get("fill_px") or 0)
|
|
k = float(strike)
|
|
if side in ("call", "c"):
|
|
return k + px
|
|
if side in ("put", "p"):
|
|
return k - px
|
|
break
|
|
return None
|
|
|
|
|
|
def _intrinsic(side: str, settle_index: float, strike: float) -> float:
|
|
s = str(side or "").lower()
|
|
if s in ("call", "c"):
|
|
return max(settle_index - strike, 0.0)
|
|
if s in ("put", "p"):
|
|
return max(strike - settle_index, 0.0)
|
|
return 0.0
|
|
|
|
|
|
def _expiry_settle_info(g: dict, fills: list) -> dict | None:
|
|
"""到期结算口径:期权价 = 内在价值(指数 vs 行权价),非盘口。"""
|
|
if str(g.get("close_reason") or "") != "expiry":
|
|
return None
|
|
settle_index = _infer_settle_index(g, fills)
|
|
strike = g.get("strike")
|
|
side = str(g.get("option_side") or "").lower()
|
|
intrinsic = None
|
|
if settle_index is not None and strike is not None:
|
|
intrinsic = _intrinsic(side, float(settle_index), float(strike))
|
|
formula = (
|
|
"Call: max(指数−行权价, 0)"
|
|
if side in ("call", "c")
|
|
else "Put: max(行权价−指数, 0)"
|
|
if side in ("put", "p")
|
|
else ""
|
|
)
|
|
is_oo = _is_oo_group(g)
|
|
out: dict[str, Any] = {
|
|
"settle_index_px": float(settle_index) if settle_index is not None else None,
|
|
"strike": float(strike) if strike is not None else None,
|
|
"intrinsic": intrinsic,
|
|
"formula": formula,
|
|
"perp_note": (
|
|
"期期无永续腿;两腿均按内在价值结算"
|
|
if is_oo
|
|
else "永续仍按市价平仓(非指数交割)"
|
|
),
|
|
"is_oo": is_oo,
|
|
}
|
|
if is_oo:
|
|
strike2 = g.get("strike2")
|
|
side2 = str(g.get("option2_side") or "put").lower()
|
|
intrinsic2 = None
|
|
if settle_index is not None and strike2 is not None:
|
|
intrinsic2 = _intrinsic(side2, float(settle_index), float(strike2))
|
|
out["strike2"] = float(strike2) if strike2 is not None else None
|
|
out["intrinsic2"] = intrinsic2
|
|
out["formula2"] = (
|
|
"Put: max(行权价−指数, 0)"
|
|
if side2 in ("put", "p")
|
|
else "Call: max(指数−行权价, 0)"
|
|
if side2 in ("call", "c")
|
|
else ""
|
|
)
|
|
out["option2_side"] = side2
|
|
return out
|
|
|
|
|
|
def _close_index_px(g: dict, fills: list) -> float | None:
|
|
"""平仓时标的指数:优先 settle_index_px,否则用永续平仓价近似。"""
|
|
raw = g.get("settle_index_px")
|
|
if raw is not None:
|
|
try:
|
|
v = float(raw)
|
|
if v > 0:
|
|
return v
|
|
except (TypeError, ValueError):
|
|
pass
|
|
for row in fills:
|
|
f = dict(row) if not isinstance(row, dict) else row
|
|
if str(f.get("leg") or "") == "perp" and str(f.get("action") or "") == "close":
|
|
try:
|
|
v = float(f.get("fill_px") or 0)
|
|
if v > 0:
|
|
return v
|
|
except (TypeError, ValueError):
|
|
pass
|
|
break
|
|
return None
|
|
|
|
|
|
def _move_points(g: dict, fills: list) -> float | None:
|
|
"""开仓指数 → 平仓指数的点数(带符号:上涨为正)。持仓中无平仓价则空。"""
|
|
entry = g.get("entry_index_px")
|
|
if entry is None:
|
|
return None
|
|
try:
|
|
e = float(entry)
|
|
except (TypeError, ValueError):
|
|
return None
|
|
if e <= 0:
|
|
return None
|
|
close_px = _close_index_px(g, fills)
|
|
if close_px is None:
|
|
return None
|
|
return round(float(close_px) - e, 2)
|
|
|
|
|
|
def _option_entry_px(fills: list, *, leg: str = "option") -> float | None:
|
|
for row in fills:
|
|
f = dict(row) if not isinstance(row, dict) else row
|
|
if str(f.get("leg") or "") != leg or str(f.get("action") or "") != "open":
|
|
continue
|
|
try:
|
|
v = float(f.get("fill_px") or 0)
|
|
if v > 0:
|
|
return v
|
|
except (TypeError, ValueError):
|
|
pass
|
|
break
|
|
return None
|
|
|
|
|
|
def _option_leverage_for_leg(
|
|
g: dict, fills: list, *, leg: str = "option"
|
|
) -> float | None:
|
|
"""开仓期权杠杆 = 开仓指数 ÷ 期权开仓均价(与选约门限口径一致)。"""
|
|
from ..strategy.selection import option_leverage
|
|
|
|
try:
|
|
entry = float(g.get("entry_index_px") or 0)
|
|
except (TypeError, ValueError):
|
|
return None
|
|
opt_px = _option_entry_px(fills, leg=leg)
|
|
if entry <= 0 or opt_px is None:
|
|
return None
|
|
lev = option_leverage(entry, opt_px)
|
|
return round(float(lev), 1) if lev is not None else None
|
|
|
|
|
|
def _enrich_group(g: dict, fills: list) -> dict:
|
|
is_oo = _is_oo_group(g)
|
|
g["is_oo"] = is_oo
|
|
summary = summarize_fills_pnl(fills)
|
|
# LIVE:优先 groups.realized_pnl(已按交易所回写,含资金费)
|
|
if str(g.get("exec_mode") or "").upper() == "LIVE" and g.get("realized_pnl") is not None:
|
|
summary = dict(summary)
|
|
summary["net_pnl"] = float(g["realized_pnl"])
|
|
if g.get("funding_usdt") is not None:
|
|
summary["funding_usdt"] = float(g["funding_usdt"])
|
|
summary["pnl_source"] = "live_exchange"
|
|
# 期期 SIM:若成交汇总缺腿但组上已有 realized_pnl,用组值兜底
|
|
elif (
|
|
is_oo
|
|
and g.get("realized_pnl") is not None
|
|
and (
|
|
summary.get("option_pnl") is None
|
|
or summary.get("option2_pnl") is None
|
|
)
|
|
):
|
|
summary = dict(summary)
|
|
summary["net_pnl"] = float(g["realized_pnl"])
|
|
summary["pnl_source"] = "group_realized"
|
|
g["pnl_summary"] = summary
|
|
if summary.get("net_pnl") is not None:
|
|
g["net_pnl"] = summary["net_pnl"]
|
|
elif g.get("realized_pnl") is not None:
|
|
g["net_pnl"] = float(g["realized_pnl"])
|
|
prem1 = float(g.get("initial_premium") or 0)
|
|
prem2 = float(g.get("initial_premium2") or 0) if is_oo else 0.0
|
|
g["total_initial_premium"] = prem1 + prem2 if is_oo else prem1
|
|
g.update(hold_timing(g, fills))
|
|
info = _expiry_settle_info(g, fills)
|
|
if info:
|
|
g["expiry_settle"] = info
|
|
if g.get("settle_index_px") is None and info.get("settle_index_px") is not None:
|
|
g["settle_index_px"] = info["settle_index_px"]
|
|
mp = _move_points(g, fills)
|
|
g["move_points"] = mp
|
|
g["close_index_px"] = _close_index_px(g, fills)
|
|
g["option_leverage"] = _option_leverage_for_leg(g, fills, leg="option")
|
|
if is_oo:
|
|
g["option2_leverage"] = _option_leverage_for_leg(g, fills, leg="option2")
|
|
return g
|
|
|
|
|
|
@router.get("/groups")
|
|
async def list_groups(_user: Annotated[str, Depends(require_user)]) -> dict:
|
|
db = get_db()
|
|
rows = db.fetchall("SELECT * FROM groups ORDER BY open_at_ms DESC LIMIT 200")
|
|
groups = []
|
|
for r in rows:
|
|
g = _row(r)
|
|
fills = db.fetchall(
|
|
"SELECT * FROM fills WHERE group_id=? ORDER BY id ASC",
|
|
(g["group_id"],),
|
|
)
|
|
groups.append(_enrich_group(g, fills))
|
|
return {"groups": groups}
|
|
|
|
|
|
@router.get("/groups/{group_id}")
|
|
async def group_detail(
|
|
group_id: str, _user: Annotated[str, Depends(require_user)]
|
|
) -> dict:
|
|
db = get_db()
|
|
g = db.fetchone("SELECT * FROM groups WHERE group_id=?", (group_id,))
|
|
if g is None:
|
|
raise HTTPException(status_code=404, detail="group not found")
|
|
fills = db.fetchall(
|
|
"SELECT * FROM fills WHERE group_id=? ORDER BY id ASC", (group_id,)
|
|
)
|
|
gr = _enrich_group(_row(g), fills)
|
|
return {
|
|
"group": gr,
|
|
"fills": [_row(x) for x in fills],
|
|
"pnl_summary": gr.get("pnl_summary"),
|
|
}
|
|
|
|
|
|
@router.delete("/groups/{group_id}")
|
|
async def delete_group(
|
|
group_id: str, _user: Annotated[str, Depends(require_user)]
|
|
) -> dict:
|
|
"""删除一条已平仓交易记录(组/成交/残留/相关账本流水)。不回滚权益。"""
|
|
db = get_db()
|
|
g = db.fetchone("SELECT * FROM groups WHERE group_id=?", (group_id,))
|
|
if g is None:
|
|
raise HTTPException(status_code=404, detail="group not found")
|
|
status = str(g["status"] or "").lower()
|
|
if status != "closed":
|
|
raise HTTPException(
|
|
status_code=409,
|
|
detail="只能删除已平仓记录;持仓中或开仓中的组不可删",
|
|
)
|
|
pos = db.fetchone("SELECT group_id FROM positions WHERE id=1")
|
|
if pos and str(pos["group_id"] or "") == group_id:
|
|
raise HTTPException(
|
|
status_code=409,
|
|
detail="当前持仓仍引用该组,不可删除",
|
|
)
|
|
with db._lock:
|
|
db._conn.execute("DELETE FROM fills WHERE group_id=?", (group_id,))
|
|
db._conn.execute(
|
|
"DELETE FROM residual_options WHERE group_id=?", (group_id,)
|
|
)
|
|
db._conn.execute(
|
|
"DELETE FROM ledger_entries WHERE group_id=?", (group_id,)
|
|
)
|
|
cur = db._conn.execute(
|
|
"DELETE FROM groups WHERE group_id=? AND status='closed'",
|
|
(group_id,),
|
|
)
|
|
if cur.rowcount <= 0:
|
|
db._conn.rollback()
|
|
raise HTTPException(
|
|
status_code=409,
|
|
detail="删除失败:组状态已变更",
|
|
)
|
|
db._conn.commit()
|
|
return {"ok": True, "group_id": group_id}
|