统计已实现盈亏扣手续费,并按平仓时指数冻结为 U。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
dekun
2026-10-08 22:50:21 +08:00
parent e8f8a76753
commit 5e8b578f75
12 changed files with 726 additions and 54 deletions
+130 -23
View File
@@ -61,7 +61,8 @@ def _underlying_index_usdt(ex: Any, underly: str) -> float | None:
def history_pnl_to_usdt(history: list[dict[str, Any]], ex: Any = None) -> list[dict[str, Any]]:
"""
统计用:币本位 realized_pnl(ETH/BTC) 按指数折成 U;USDC 原样.
统计用:优先已冻结的 realized_pnl_usdt(平仓当时口径,含手续费后净额);
否则币本位用 close_index_px(再否则实时指数)折 U;USDC 原样.
折算失败的币仓剔除盈亏字段,避免把「币数量」当成 U.
"""
from lib.options.options_margin_mode_lib import margin_mode_from_inst_id, premium_ccy_for_mode
@@ -73,6 +74,11 @@ def history_pnl_to_usdt(history: list[dict[str, Any]], ex: Any = None) -> list[d
if r.get("status") == "open":
out.append(r)
continue
frozen = _safe_float(r.get("realized_pnl_usdt"))
if frozen is not None:
r["realized_pnl"] = round(float(frozen), 4)
out.append(r)
continue
pnl = _safe_float(r.get("realized_pnl"))
if pnl is None:
out.append(r)
@@ -83,9 +89,11 @@ def history_pnl_to_usdt(history: list[dict[str, Any]], ex: Any = None) -> list[d
if not ccy:
ccy = premium_ccy_for_mode(margin_mode_from_inst_id(inst), underly)
if ccy in ("ETH", "BTC"):
if underly not in idx_cache:
idx_cache[underly] = _underlying_index_usdt(ex, underly)
idx = idx_cache.get(underly)
idx = _safe_float(r.get("close_index_px"))
if idx is None or idx <= 0:
if underly not in idx_cache:
idx_cache[underly] = _underlying_index_usdt(ex, underly)
idx = idx_cache.get(underly)
if idx is None or idx <= 0:
r["realized_pnl"] = None
else:
@@ -278,6 +286,8 @@ def _closed_trade_dicts(closed_rows) -> list[dict[str, Any]]:
{
"status": "closed",
"realized_pnl": _row_get(row, "realized_pnl"),
"realized_pnl_usdt": _row_get(row, "realized_pnl_usdt"),
"close_index_px": _row_get(row, "close_index_px"),
"created_at": _row_get(row, "created_at"),
"closed_at": _row_get(row, "closed_at"),
"inst_id": _row_get(row, "inst_id") or "",
@@ -288,26 +298,118 @@ def _closed_trade_dicts(closed_rows) -> list[dict[str, Any]]:
return out
_CLOSED_STATS_SELECT = """
SELECT realized_pnl, realized_pnl_usdt, close_index_px,
created_at, closed_at, inst_id, underlying, premium_ccy
FROM options_trades
WHERE status = 'closed'
AND (realized_pnl IS NOT NULL OR realized_pnl_usdt IS NOT NULL)
"""
def freeze_missing_realized_pnl_usdt(conn, ex: Any = None) -> int:
"""旧已平仓缺冻结 U 时按 close_index/当前指数写一次,之后不再跟盘变."""
init_options_tables(conn)
rows = conn.execute(
"""
SELECT id, realized_pnl, realized_pnl_usdt, close_index_px,
inst_id, underlying, premium_ccy, premium_paid, premium_received,
open_fee, close_fee
FROM options_trades
WHERE status = 'closed'
AND realized_pnl_usdt IS NULL
AND realized_pnl IS NOT NULL
ORDER BY id DESC
LIMIT 300
"""
).fetchall()
if not rows:
return 0
from lib.options.options_pnl_settle_lib import settle_closed_pnl, resolve_close_index_px
updated = 0
for row in rows:
ccy = str(_row_get(row, "premium_ccy") or "").strip().upper()
idx = _safe_float(_row_get(row, "close_index_px"))
if idx is None or idx <= 0:
idx = resolve_close_index_px(
ex,
inst_id=str(_row_get(row, "inst_id") or ""),
underlying=str(_row_get(row, "underlying") or ""),
)
# 有手续费列时按净额重算;否则用已有 realized_pnl 冻结
ofee = _safe_float(_row_get(row, "open_fee")) or 0.0
cfee = _safe_float(_row_get(row, "close_fee")) or 0.0
paid = _row_get(row, "premium_paid")
recv = _row_get(row, "premium_received")
if paid is not None and recv is not None and (ofee > 0 or cfee > 0):
settled = settle_closed_pnl(
premium_paid=paid,
premium_received=recv,
open_fee=ofee,
close_fee=cfee,
premium_ccy=ccy or "USDC",
index_px=idx,
)
pnl = settled.get("realized_pnl")
usdt = settled.get("realized_pnl_usdt")
close_idx = settled.get("close_index_px")
else:
pnl = _safe_float(_row_get(row, "realized_pnl"))
if pnl is None:
continue
settled = settle_closed_pnl(
premium_paid=0,
premium_received=pnl,
open_fee=0,
close_fee=0,
premium_ccy=ccy or "USDC",
index_px=idx,
)
usdt = settled.get("realized_pnl_usdt")
close_idx = settled.get("close_index_px")
if usdt is None:
continue
conn.execute(
"""
UPDATE options_trades
SET realized_pnl_usdt = ?,
close_index_px = COALESCE(close_index_px, ?),
realized_pnl = COALESCE(?, realized_pnl)
WHERE id = ? AND realized_pnl_usdt IS NULL
""",
(float(usdt), close_idx, pnl, int(row["id"])),
)
updated += 1
return updated
def load_local_options_stats_history(conn, ex: Any = None) -> list[dict[str, Any]]:
"""本地已平(含冻结 U/手续费净额) + 当前 open,供统计/中控窗口复用."""
init_options_tables(conn)
try:
freeze_missing_realized_pnl_usdt(conn, ex)
except Exception:
pass
closed_rows = conn.execute(_CLOSED_STATS_SELECT).fetchall()
open_rows = conn.execute(
"SELECT created_at FROM options_trades WHERE status = 'open'"
).fetchall()
history = _closed_trade_dicts(closed_rows)
for row in open_rows:
history.append({"status": "open", "created_at": _row_get(row, "created_at")})
return history
def compute_options_stats(get_db, ex: Any = None) -> dict[str, Any]:
conn = get_db()
try:
init_options_tables(conn)
closed_rows = conn.execute(
"""
SELECT realized_pnl, created_at, closed_at, inst_id, underlying, premium_ccy
FROM options_trades
WHERE status = 'closed' AND realized_pnl IS NOT NULL
"""
).fetchall()
open_rows = conn.execute(
"""
SELECT created_at FROM options_trades WHERE status = 'open'
"""
).fetchall()
history = _closed_trade_dicts(closed_rows)
for row in open_rows:
history.append({"status": "open", "created_at": _row_get(row, "created_at")})
# 币本位盈亏按指数折 U,再算胜率/盈亏比(与 /api/options/stats 一致)
history = load_local_options_stats_history(conn, ex)
try:
conn.commit()
except Exception:
pass
# 优先冻结 U;缺省再按指数折(与 /api/options/stats 一致)
return compute_options_stats_from_history(history_pnl_to_usdt(history, ex))
finally:
conn.close()
@@ -337,12 +439,17 @@ def header_options_stats_for_window(
start_bj, end_bj = utc_window_to_bj_sql_strings(
list_window["start_utc"], list_window["end_utc"], app_tz
)
try:
freeze_missing_realized_pnl_usdt(conn, ex)
except Exception:
pass
closed_rows = conn.execute(
"""
SELECT realized_pnl, created_at, closed_at, inst_id, underlying, premium_ccy
SELECT realized_pnl, realized_pnl_usdt, close_index_px,
created_at, closed_at, inst_id, underlying, premium_ccy
FROM options_trades
WHERE status = 'closed'
AND realized_pnl IS NOT NULL
AND (realized_pnl IS NOT NULL OR realized_pnl_usdt IS NOT NULL)
AND COALESCE(closed_at, created_at) >= ?
AND COALESCE(closed_at, created_at) <= ?
""",