fix模拟盘盈亏:按权利金净额×平仓指数,不再把买币预算差额当盈利。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
dekun
2026-10-08 23:49:02 +08:00
parent a16dd4f9cc
commit a0ee1fa8a0
5 changed files with 115 additions and 95 deletions
+17 -4
View File
@@ -142,15 +142,25 @@ def display_pnl_usdt_from_option_row(row: dict[str, Any]) -> float | None:
def premium_paid_usdt_from_option_row(row: dict[str, Any]) -> float | None:
"""开仓权利金折 USDT.
优先用开仓时兑换/预算占用的 budget_usdt(不随币价浮动);
否则 USDC 原样;币本位无预算记录时才回退 × 当前指数.
用权利金币数量 × 开仓/标记指数;绝不用 budget_usdt(那是买币缓冲预算,不是权利金).
"""
entry = _safe_float(row.get("premium_entry_usdt") or row.get("budget_usdt"))
entry = _safe_float(row.get("premium_entry_usdt"))
if entry is not None:
return round(float(entry), 4)
paid = _safe_float(row.get("premium_paid"))
if paid is None:
return None
ccy = str(row.get("premium_ccy") or "USDC").strip().upper() or "USDC"
if ccy in ("ETH", "BTC"):
idx = _safe_float(
row.get("open_index_px")
or row.get("idx_px")
or row.get("idxPx")
or row.get("index_px")
)
if idx is None or idx <= 0:
return None
return round(float(paid) * float(idx), 4)
return _coin_amount_to_usdt(paid, row)
@@ -254,7 +264,10 @@ def build_display_option_positions(
)
if budget_usdt is not None:
row["budget_usdt"] = round(float(budget_usdt), 4)
row["premium_entry_usdt"] = round(float(budget_usdt), 4)
# 权利金入口 U:币数量×指数,不用买币预算
prem_u = premium_paid_usdt_from_option_row(row)
if prem_u is not None:
row["premium_entry_usdt"] = round(float(prem_u), 4)
if include_close_preview:
attach_close_preview(cfg, ex, row, premium_paid=_safe_float(row.get("premium_paid")))
rows.append(row)
+4 -1
View File
@@ -184,7 +184,10 @@ def add_bridge_usdt_recovered(
def cash_pnl_usdt_from_bridge(conn: sqlite3.Connection, bridge_id: int | None) -> float | None:
"""现金盈亏 = 卖回 USDT 合计 − 开仓买币花费(budget_usdt)."""
"""桥上现货净 USDT(卖回−买币预算).仅供对账,不得当作期权已实现盈亏.
买币预算含权利金本金与缓冲;用此值当盈利会把权利金本金算进去.
"""
if bridge_id is None:
return None
ensure_bridge_table(conn)
+68 -49
View File
@@ -512,22 +512,20 @@ def _sim_net_usdt_converts_for_trade(
def sync_sim_cash_realized_pnl_usdt(conn, ex: Any = None) -> int:
"""模拟盘:用现货买币/卖回的真实 USDT 净额覆盖冻结盈亏(对齐钱包)."""
del ex # 现金口径不依赖实时指数
init_options_tables(conn)
try:
from lib.options.options_spot_bridge_lib import (
cash_pnl_usdt_from_bridge,
ensure_bridge_table,
)
"""模拟盘:按权利金净盈亏冻结 U(收回−已付−费)×平仓指数.
禁止再用「卖回 USDT − 买币预算」:买币预算含权利金本金与缓冲,卖回差额会把
权利金本金也算进盈利,导致合计盈亏虚高(约翻倍).
函数名保留兼容旧调用.
"""
init_options_tables(conn)
from lib.options.options_pnl_settle_lib import resolve_close_index_px, settle_closed_pnl
ensure_bridge_table(conn)
except Exception:
return 0
rows = conn.execute(
"""
SELECT id, bridge_id, underlying, budget_usdt, premium_ccy,
created_at, closed_at, realized_pnl_usdt
SELECT id, inst_id, underlying, premium_ccy, premium_paid, premium_received,
open_fee, close_fee, realized_pnl, realized_pnl_usdt,
close_index_px, open_index_px, close_quote, eth_amount
FROM options_trades
WHERE status = 'closed'
ORDER BY id DESC
@@ -541,45 +539,71 @@ def sync_sim_cash_realized_pnl_usdt(conn, ex: Any = None) -> int:
if ccy not in ("ETH", "BTC") and underly not in ("ETH", "BTC"):
continue
underly = underly or ccy
cash = None
bid = _row_get(row, "bridge_id")
try:
if bid is not None:
cash = cash_pnl_usdt_from_bridge(conn, int(bid))
except Exception:
cash = None
if cash is None:
# 旧桥未记 usdt_recovered:用流水回补(开仓前1分钟~平仓后30分钟)
start = str(_row_get(row, "created_at") or "")
end = str(_row_get(row, "closed_at") or "")
if start and end:
from datetime import datetime, timedelta
paid = _safe_float(_row_get(row, "premium_paid"))
recv = _safe_float(_row_get(row, "premium_received"))
if recv is None:
cq = _safe_float(_row_get(row, "close_quote"))
eth = _safe_float(_row_get(row, "eth_amount"))
if cq is not None and eth is not None and eth > 0:
try:
from lib.options.options_pricing_lib import total_premium
def _shift(ts: str, minutes: int) -> str:
try:
dt = datetime.fromisoformat(str(ts).strip().replace(" ", "T", 1))
return (dt + timedelta(minutes=minutes)).strftime("%Y-%m-%d %H:%M:%S")
except Exception:
return ts
cash = _sim_net_usdt_converts_for_trade(
conn,
recv = float(total_premium(cq, eth))
except Exception:
recv = None
if paid is None or recv is None:
# 无毛权利金时回退:已有币数量净盈亏 × 冻结指数
net = _safe_float(_row_get(row, "realized_pnl"))
if net is None:
continue
idx = _safe_float(_row_get(row, "close_index_px")) or _safe_float(
_row_get(row, "open_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=underly,
start_ts=_shift(start, -2),
end_ts=_shift(end, 30),
)
if cash is None:
continue
if idx is None or idx <= 0:
continue
usdt = round(float(net) * float(idx), 4)
close_idx = float(idx)
new_pnl = float(net)
else:
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=underly,
hint=_row_get(row, "open_index_px"),
)
settled = settle_closed_pnl(
premium_paid=paid,
premium_received=recv,
open_fee=_row_get(row, "open_fee"),
close_fee=_row_get(row, "close_fee"),
premium_ccy=ccy or underly or "ETH",
index_px=idx,
)
usdt = settled.get("realized_pnl_usdt")
close_idx = settled.get("close_index_px")
new_pnl = settled.get("realized_pnl")
if usdt is None:
continue
old = _safe_float(_row_get(row, "realized_pnl_usdt"))
if old is not None and abs(float(old) - float(cash)) < 1e-6:
if old is not None and abs(float(old) - float(usdt)) < 1e-6:
continue
conn.execute(
"""
UPDATE options_trades
SET realized_pnl_usdt = ?
SET realized_pnl_usdt = ?,
close_index_px = COALESCE(close_index_px, ?),
realized_pnl = COALESCE(?, realized_pnl)
WHERE id = ?
""",
(float(cash), int(row["id"])),
(float(usdt), close_idx, new_pnl, int(row["id"])),
)
updated += 1
return updated
@@ -589,15 +613,10 @@ def load_local_options_stats_history(conn, ex: Any = None) -> list[dict[str, Any
"""本地已平(模拟盘口径) + 当前 open."""
init_options_tables(conn)
try:
from lib.sim.mode_lib import is_sim_mode
# get_db 不可用时仍尝试现金同步(conn 已打开)
# 权利金净盈亏冻结 U(纠正旧版把买币预算差额当盈利的数据)
sync_sim_cash_realized_pnl_usdt(conn, ex)
except Exception:
try:
sync_sim_cash_realized_pnl_usdt(conn, ex)
except Exception:
pass
pass
try:
freeze_missing_realized_pnl_usdt(conn, ex)
except Exception: