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_px;否则用「实值腿」成交反推;再否则公开指数近似。""" 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 candidates: list[float] = [] for raw in fills: f = dict(raw) if not isinstance(raw, dict) else raw if str(f.get("action") or "") != "close": continue leg = str(f.get("leg") or "") if leg not in ("option", "option2"): continue if abs(float(f.get("slip") or 0)) > 1e-12: continue try: px = float(f.get("fill_px") or 0) except (TypeError, ValueError): continue # 虚值到期 fill=0:k+0 / k-0 会得到行权价,不是真实结算指数 if px <= 1e-9: continue if leg == "option": strike = g.get("strike") side = str(g.get("option_side") or "").lower() else: strike = g.get("strike2") side = str(g.get("option2_side") or "put").lower() if strike is None: continue try: k = float(strike) except (TypeError, ValueError): continue if side in ("call", "c"): candidates.append(k + px) elif side in ("put", "p"): candidates.append(k - px) if candidates: return round(sum(candidates) / len(candidates), 4) try: from .public_index import maybe_public_settle_index pub = maybe_public_settle_index(g) if pub is not None and pub > 0: return round(float(pub), 4) except Exception: pass return None def _overlay_expiry_intrinsic_fills( g: dict, fills: list, settle_index: float | None ) -> list: """到期且已有结算指数:close 成交按内在价值覆盖展示/盈亏(响应层)。 交易所账单偶发落成近 0 价(如 0.2),与内在价值(如 42.2)严重不符时 若只覆盖 fill≈0,Put 仍会按错误价算成巨亏。 """ if settle_index is None or settle_index <= 0: return fills if str(g.get("close_reason") or "") != "expiry": return fills out: list = [] changed = False for raw in fills: f = dict(raw) if not isinstance(raw, dict) else dict(raw) if str(f.get("action") or "") == "close" and str(f.get("leg") or "") in ( "option", "option2", ): try: px = float(f.get("fill_px") or 0) except (TypeError, ValueError): px = 0.0 leg = str(f.get("leg") or "") if leg == "option": strike = g.get("strike") side = str(g.get("option_side") or "").lower() else: strike = g.get("strike2") side = str(g.get("option2_side") or "put").lower() if strike is not None: try: intrinsic = float( _intrinsic(side, float(settle_index), float(strike)) ) # 与内在价值偏差超过 0.5 USDT(或相对 5%)则覆盖 tol = max(0.5, abs(intrinsic) * 0.05) if abs(px - intrinsic) > tol: qty = float(f.get("qty_eth") or 0) f["fill_px"] = intrinsic f["base_px"] = intrinsic f["notional"] = intrinsic * qty f["slip"] = 0.0 f["_overlay_intrinsic"] = True changed = True except (TypeError, ValueError): pass out.append(f) return out if changed else fills # 兼容旧测试名 _overlay_expiry_zero_fills = _overlay_expiry_intrinsic_fills 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;到期才用实值腿反推;否则永续平仓价。""" raw = g.get("settle_index_px") if raw is not None: try: v = float(raw) if v > 0: return v except (TypeError, ValueError): pass # 仅到期:期权平仓价=内在价值,可反推指数;中途卖出的权利金不能当指数 if str(g.get("close_reason") or "") == "expiry": inferred = _infer_settle_index(g, fills) if inferred is not None and inferred > 0: return inferred 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 settle = _infer_settle_index(g, fills) view_fills = _overlay_expiry_intrinsic_fills(g, fills, settle) overlaid = any( isinstance(f, dict) and f.get("_overlay_intrinsic") for f in view_fills ) summary = summarize_fills_pnl(view_fills) # LIVE 且未做内在价值覆盖:优先 groups.realized_pnl(含资金费) if ( not overlaid and 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" elif overlaid: summary = dict(summary) summary["pnl_source"] = "expiry_intrinsic_overlay" 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)) if settle is not None and g.get("settle_index_px") is None: g["settle_index_px"] = float(settle) info = _expiry_settle_info(g, view_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, view_fills) g["move_points"] = mp g["close_index_px"] = _close_index_px(g, view_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") g["_view_fills"] = view_fills g["_overlay_settle"] = float(settle) if settle is not None else None g["_overlaid"] = overlaid return g def persist_expiry_overlay_if_needed(db: Any, g: dict, raw_fills: list) -> None: """把内在价值覆盖写回库:fills / realized_pnl / settle_index,并补本地账本差额。""" if not g.get("_overlaid"): return view_fills = g.get("_view_fills") or [] net = g.get("net_pnl") if net is None: return settle = g.get("_overlay_settle") group_id = str(g.get("group_id") or "") if not group_id: return old_net = float(g.get("realized_pnl") or 0) # 已对齐则跳过(避免每次列表刷库) if abs(old_net - float(net)) < 0.02: stored = g.get("settle_index_px") try: if settle is None or ( stored is not None and abs(float(stored) - float(settle)) < 0.05 ): # 仍可能 fills 未写回;检查是否还有 overlay 标记需要落库 pass else: pass except (TypeError, ValueError): pass raw_close = { str(dict(f).get("leg")): dict(f) for f in raw_fills if str(dict(f).get("action") or "") == "close" and str(dict(f).get("leg") or "") in ("option", "option2") } cash_delta = 0.0 updates: list[tuple] = [] for vf in view_fills: if not isinstance(vf, dict) or not vf.get("_overlay_intrinsic"): continue leg = str(vf.get("leg") or "") old = raw_close.get(leg) if not old or old.get("id") is None: continue try: old_px = float(old.get("fill_px") or 0) new_px = float(vf.get("fill_px") or 0) qty = float(vf.get("qty_eth") or old.get("qty_eth") or 0) except (TypeError, ValueError): continue if abs(old_px - new_px) <= 1e-9: continue cash_delta += (new_px - old_px) * qty updates.append( ( new_px, new_px, new_px * qty, int(old["id"]), ) ) if not updates and abs(old_net - float(net)) < 0.02: # 只缺 settle if settle is None: return try: if g.get("settle_index_px") is not None and abs( float(g["settle_index_px"]) - float(settle) ) < 0.05: return except (TypeError, ValueError): pass with db._lock: for base, fill, notional, fid in updates: db._conn.execute( "UPDATE fills SET base_px=?, fill_px=?, notional=?, slip=0 WHERE id=?", (base, fill, notional, fid), ) db._conn.execute( """UPDATE groups SET realized_pnl=?, settle_index_px=COALESCE(?, settle_index_px), note=CASE WHEN instr(COALESCE(note,''), 'expiry_intrinsic_repair')>0 THEN note ELSE trim(COALESCE(note,'') || ' | expiry_intrinsic_repair') END WHERE group_id=? AND status='closed'""", ( float(net), float(settle) if settle is not None else None, group_id, ), ) db._conn.commit() if abs(cash_delta) > 1e-9: try: from ..sim.ledger import Ledger Ledger(db).apply_cash( cash_delta, kind="repair_option_intrinsic", group_id=group_id, note=f"expiry intrinsic overlay cash_delta={cash_delta:.4f}", allow_negative=True, ) except Exception: pass # 刷新内存中的 realized,供同请求后续使用 g["realized_pnl"] = float(net) @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"],), ) gr = _enrich_group(g, fills) try: persist_expiry_overlay_if_needed(db, gr, list(fills)) except Exception: pass gr.pop("_view_fills", None) gr.pop("_overlay_settle", None) gr.pop("_overlaid", None) groups.append(gr) 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) try: persist_expiry_overlay_if_needed(db, gr, list(fills)) except Exception: pass view_fills = gr.pop("_view_fills", None) or fills gr.pop("_overlay_settle", None) gr.pop("_overlaid", None) return { "group": gr, "fills": [ { k: v for k, v in (dict(x) if not isinstance(x, dict) else x).items() if k != "_overlay_intrinsic" } for x in view_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}