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: def premium_paid_usdt_from_option_row(row: dict[str, Any]) -> float | None:
"""开仓权利金折 USDT. """开仓权利金折 USDT.
优先用开仓时兑换/预算占用的 budget_usdt(不随币价浮动); 用权利金币数量 × 开仓/标记指数;绝不用 budget_usdt(那是买币缓冲预算,不是权利金).
否则 USDC 原样;币本位无预算记录时才回退 × 当前指数.
""" """
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: if entry is not None:
return round(float(entry), 4) return round(float(entry), 4)
paid = _safe_float(row.get("premium_paid")) paid = _safe_float(row.get("premium_paid"))
if paid is None: if paid is None:
return 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) return _coin_amount_to_usdt(paid, row)
@@ -254,7 +264,10 @@ def build_display_option_positions(
) )
if budget_usdt is not None: if budget_usdt is not None:
row["budget_usdt"] = round(float(budget_usdt), 4) 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: if include_close_preview:
attach_close_preview(cfg, ex, row, premium_paid=_safe_float(row.get("premium_paid"))) attach_close_preview(cfg, ex, row, premium_paid=_safe_float(row.get("premium_paid")))
rows.append(row) 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: def cash_pnl_usdt_from_bridge(conn: sqlite3.Connection, bridge_id: int | None) -> float | None:
"""现金盈亏 = 卖回 USDT 合计 − 开仓买币花费(budget_usdt).""" """桥上现货净 USDT(卖回−买币预算).仅供对账,不得当作期权已实现盈亏.
买币预算含权利金本金与缓冲;用此值当盈利会把权利金本金算进去.
"""
if bridge_id is None: if bridge_id is None:
return None return None
ensure_bridge_table(conn) ensure_bridge_table(conn)
+65 -46
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: def sync_sim_cash_realized_pnl_usdt(conn, ex: Any = None) -> int:
"""模拟盘:用现货买币/卖回的真实 USDT 净额覆盖冻结盈亏(对齐钱包).""" """模拟盘:按权利金净盈亏冻结 U(收回−已付−费)×平仓指数.
del ex # 现金口径不依赖实时指数
init_options_tables(conn) 禁止再用「卖回 USDT − 买币预算」:买币预算含权利金本金与缓冲,卖回差额会把
try: 权利金本金也算进盈利,导致合计盈亏虚高(约翻倍).
from lib.options.options_spot_bridge_lib import ( 函数名保留兼容旧调用.
cash_pnl_usdt_from_bridge, """
ensure_bridge_table, 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( rows = conn.execute(
""" """
SELECT id, bridge_id, underlying, budget_usdt, premium_ccy, SELECT id, inst_id, underlying, premium_ccy, premium_paid, premium_received,
created_at, closed_at, realized_pnl_usdt open_fee, close_fee, realized_pnl, realized_pnl_usdt,
close_index_px, open_index_px, close_quote, eth_amount
FROM options_trades FROM options_trades
WHERE status = 'closed' WHERE status = 'closed'
ORDER BY id DESC 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"): if ccy not in ("ETH", "BTC") and underly not in ("ETH", "BTC"):
continue continue
underly = underly or ccy underly = underly or ccy
cash = None paid = _safe_float(_row_get(row, "premium_paid"))
bid = _row_get(row, "bridge_id") 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: try:
if bid is not None: from lib.options.options_pricing_lib import total_premium
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
def _shift(ts: str, minutes: int) -> str: recv = float(total_premium(cq, eth))
try:
dt = datetime.fromisoformat(str(ts).strip().replace(" ", "T", 1))
return (dt + timedelta(minutes=minutes)).strftime("%Y-%m-%d %H:%M:%S")
except Exception: except Exception:
return ts recv = None
if paid is None or recv is None:
cash = _sim_net_usdt_converts_for_trade( # 无毛权利金时回退:已有币数量净盈亏 × 冻结指数
conn, net = _safe_float(_row_get(row, "realized_pnl"))
underlying=underly, if net is None:
start_ts=_shift(start, -2), continue
end_ts=_shift(end, 30), idx = _safe_float(_row_get(row, "close_index_px")) or _safe_float(
_row_get(row, "open_index_px")
) )
if cash is None: if idx is None or idx <= 0:
idx = resolve_close_index_px(
ex,
inst_id=str(_row_get(row, "inst_id") or ""),
underlying=underly,
)
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 continue
old = _safe_float(_row_get(row, "realized_pnl_usdt")) 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 continue
conn.execute( conn.execute(
""" """
UPDATE options_trades 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 = ? WHERE id = ?
""", """,
(float(cash), int(row["id"])), (float(usdt), close_idx, new_pnl, int(row["id"])),
) )
updated += 1 updated += 1
return updated return updated
@@ -589,12 +613,7 @@ def load_local_options_stats_history(conn, ex: Any = None) -> list[dict[str, Any
"""本地已平(模拟盘口径) + 当前 open.""" """本地已平(模拟盘口径) + 当前 open."""
init_options_tables(conn) init_options_tables(conn)
try: try:
from lib.sim.mode_lib import is_sim_mode # 权利金净盈亏冻结 U(纠正旧版把买币预算差额当盈利的数据)
# get_db 不可用时仍尝试现金同步(conn 已打开)
sync_sim_cash_realized_pnl_usdt(conn, ex)
except Exception:
try:
sync_sim_cash_realized_pnl_usdt(conn, ex) sync_sim_cash_realized_pnl_usdt(conn, ex)
except Exception: except Exception:
pass pass
+19 -35
View File
@@ -73,8 +73,9 @@ class SettleClosedPnlTests(unittest.TestCase):
self.assertAlmostEqual(float(s["realized_pnl_usdt"]), 27.0, places=4) self.assertAlmostEqual(float(s["realized_pnl_usdt"]), 27.0, places=4)
class SimCashPnlStatsTests(unittest.TestCase): class SimPremiumPnlStatsTests(unittest.TestCase):
def test_sim_cash_from_bridge_overrides_index_pnl(self): def test_sim_uses_premium_net_not_bridge_cash(self):
"""卖回−预算会把权利金本金算进盈利;必须用(收回−已付)×平仓指数."""
import sqlite3 import sqlite3
from lib.options.options_db import init_options_tables from lib.options.options_db import init_options_tables
@@ -85,6 +86,7 @@ class SimCashPnlStatsTests(unittest.TestCase):
conn.row_factory = sqlite3.Row conn.row_factory = sqlite3.Row
init_options_tables(conn) init_options_tables(conn)
ensure_bridge_table(conn) ensure_bridge_table(conn)
# 桥上现金差额 952.96,但权利金净盈亏仅 0.01 ETH × 2500 = 25U
conn.execute( conn.execute(
""" """
INSERT INTO options_spot_bridge( INSERT INTO options_spot_bridge(
@@ -97,12 +99,12 @@ class SimCashPnlStatsTests(unittest.TestCase):
INSERT INTO options_trades( INSERT INTO options_trades(
inst_id, underlying, opt_type, sheets, eth_amount, inst_id, underlying, opt_type, sheets, eth_amount,
premium_paid, premium_received, realized_pnl, premium_ccy, premium_paid, premium_received, realized_pnl, premium_ccy,
status, bridge_id, budget_usdt, realized_pnl_usdt, status, bridge_id, budget_usdt, realized_pnl_usdt, close_index_px,
created_at, closed_at created_at, closed_at
) VALUES ( ) VALUES (
'ETH-USD-261009-2500-P', 'ETH', 'P', 1, 0.01, 'ETH-USD-261009-2500-P', 'ETH', 'P', 1, 0.01,
0.01, 0.02, 0.01, 'ETH', 0.01, 0.02, 0.01, 'ETH',
'closed', 1, 1000.0, 884.54, 'closed', 1, 1000.0, 1947.05, 2500.0,
'2026-10-06 10:00:00', '2026-10-08 14:00:00' '2026-10-06 10:00:00', '2026-10-08 14:00:00'
) )
""" """
@@ -111,62 +113,44 @@ class SimCashPnlStatsTests(unittest.TestCase):
n = sync_sim_cash_realized_pnl_usdt(conn, None) n = sync_sim_cash_realized_pnl_usdt(conn, None)
self.assertEqual(n, 1) self.assertEqual(n, 1)
row = conn.execute( row = conn.execute(
"SELECT realized_pnl_usdt FROM options_trades WHERE id=1" "SELECT realized_pnl_usdt, realized_pnl FROM options_trades WHERE id=1"
).fetchone() ).fetchone()
self.assertAlmostEqual(float(row["realized_pnl_usdt"]), 952.96, places=2) # (0.02-0.01)*2500 = 25, 绝不是 1952.96-1000
self.assertAlmostEqual(float(row["realized_pnl_usdt"]), 25.0, places=2)
self.assertAlmostEqual(float(row["realized_pnl"]), 0.01, places=8)
conn.close() conn.close()
def test_sim_cash_from_ledger_when_bridge_missing_recovered(self): def test_sim_deducts_fees_from_premium_pnl(self):
import sqlite3 import sqlite3
from lib.options.options_db import init_options_tables from lib.options.options_db import init_options_tables
from lib.options.options_spot_bridge_lib import ensure_bridge_table
from lib.options.options_stats_lib import sync_sim_cash_realized_pnl_usdt from lib.options.options_stats_lib import sync_sim_cash_realized_pnl_usdt
from lib.sim.db_lib import init_sim_tables
conn = sqlite3.connect(":memory:") conn = sqlite3.connect(":memory:")
conn.row_factory = sqlite3.Row conn.row_factory = sqlite3.Row
init_options_tables(conn) init_options_tables(conn)
ensure_bridge_table(conn)
init_sim_tables(conn)
conn.execute(
"""
INSERT INTO options_spot_bridge(
id, underlying, status, budget_usdt, usdt_recovered
) VALUES (1, 'ETH', 'closed', 1000.0, NULL)
"""
)
conn.execute( conn.execute(
""" """
INSERT INTO options_trades( INSERT INTO options_trades(
inst_id, underlying, opt_type, sheets, eth_amount, inst_id, underlying, opt_type, sheets, eth_amount,
premium_paid, premium_received, realized_pnl, premium_ccy, premium_paid, premium_received, realized_pnl, premium_ccy,
status, bridge_id, budget_usdt, realized_pnl_usdt, open_fee, close_fee, status, realized_pnl_usdt, close_index_px,
created_at, closed_at created_at, closed_at
) VALUES ( ) VALUES (
'ETH-USD-261009-2500-P', 'ETH', 'P', 1, 0.01, 'BTC-USD-261008-86500-P', 'BTC', 'P', 1, 0.01,
0.01, 0.02, 0.01, 'ETH', 0.01, 0.02, 0.01, 'BTC',
'closed', 1, 1000.0, 884.54, 0.0001, 0.0001, 'closed', 1947.05, 80000.0,
'2026-10-06 10:00:00', '2026-10-08 14:00:00' '2026-10-05 05:11:30', '2026-10-07 10:03:53'
) )
""" """
) )
# 买币 -1000U, 卖回 +1952.96U
conn.execute(
"""
INSERT INTO sim_ledger_entries(kind, amount, ccy, account, note, ts)
VALUES
('convert', -1000.0, 'USDT', 'trading', 'ETH/USDT mkt 2500', '2026-10-06 10:00:05'),
('convert', 1952.96, 'USDT', 'trading', 'from eth', '2026-10-08 14:00:10')
"""
)
conn.commit() conn.commit()
n = sync_sim_cash_realized_pnl_usdt(conn, None) sync_sim_cash_realized_pnl_usdt(conn, None)
self.assertEqual(n, 1)
row = conn.execute( row = conn.execute(
"SELECT realized_pnl_usdt FROM options_trades WHERE id=1" "SELECT realized_pnl_usdt FROM options_trades WHERE id=1"
).fetchone() ).fetchone()
self.assertAlmostEqual(float(row["realized_pnl_usdt"]), 952.96, places=2) # (0.02-0.01-0.0002)*80000 = 784
self.assertAlmostEqual(float(row["realized_pnl_usdt"]), 784.0, places=2)
conn.close() conn.close()
+7 -6
View File
@@ -26,8 +26,8 @@ class ReviewLocalSyncFreezeTests(unittest.TestCase):
created_at, closed_at created_at, closed_at
) VALUES ( ) VALUES (
'BTC-USD-261008-86500-P', 'BTC', 'P', 1, 0.01, 'BTC-USD-261008-86500-P', 'BTC', 'P', 1, 0.01,
0.01, 0.02, 0.01172, 'BTC', 0.01, 0.02, 0.01, 'BTC',
'closed', 1947.05, 85000.0, 'closed', 850.0, 85000.0,
'2026-10-05 05:11:30', '2026-10-07 10:03:53' '2026-10-05 05:11:30', '2026-10-07 10:03:53'
) )
""" """
@@ -45,8 +45,8 @@ class ReviewLocalSyncFreezeTests(unittest.TestCase):
("local_opt:1",), ("local_opt:1",),
).fetchone() ).fetchone()
self.assertIsNotNone(row) self.assertIsNotNone(row)
# 必须是冻结现金 1947.05,不是 0.01172*999999 # (0.02-0.01)*85000=850,不是 0.01*999999
self.assertAlmostEqual(float(row["realized_pnl_total"]), 1947.05, places=2) self.assertAlmostEqual(float(row["realized_pnl_total"]), 850.0, places=2)
conn.close() conn.close()
def test_second_sync_stable_when_index_moves(self): def test_second_sync_stable_when_index_moves(self):
@@ -70,7 +70,7 @@ class ReviewLocalSyncFreezeTests(unittest.TestCase):
) VALUES ( ) VALUES (
'BTC-USD-261008-86500-P', 'BTC', 'P', 1, 0.01, 'BTC-USD-261008-86500-P', 'BTC', 'P', 1, 0.01,
0.01, 0.02, 0.01, 'BTC', 0.01, 0.02, 0.01, 'BTC',
'closed', 952.96, 80000.0, 'closed', 800.0, 80000.0,
'2026-10-05 05:11:30', '2026-10-07 10:03:53' '2026-10-05 05:11:30', '2026-10-07 10:03:53'
) )
""" """
@@ -99,7 +99,8 @@ class ReviewLocalSyncFreezeTests(unittest.TestCase):
("local_opt:1",), ("local_opt:1",),
).fetchone()["realized_pnl_total"] ).fetchone()["realized_pnl_total"]
) )
self.assertAlmostEqual(v1, 952.96, places=2) # (0.02-0.01)*80000=800; 实时指数变也不改
self.assertAlmostEqual(v1, 800.0, places=2)
self.assertAlmostEqual(v2, v1, places=6) self.assertAlmostEqual(v2, v1, places=6)
conn.close() conn.close()