fix模拟盘盈亏:按权利金净额×平仓指数,不再把买币预算差额当盈利。
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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")
|
||||
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:
|
||||
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
|
||||
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")
|
||||
recv = float(total_premium(cq, eth))
|
||||
except Exception:
|
||||
return ts
|
||||
|
||||
cash = _sim_net_usdt_converts_for_trade(
|
||||
conn,
|
||||
underlying=underly,
|
||||
start_ts=_shift(start, -2),
|
||||
end_ts=_shift(end, 30),
|
||||
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 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
|
||||
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,12 +613,7 @@ 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 已打开)
|
||||
sync_sim_cash_realized_pnl_usdt(conn, ex)
|
||||
except Exception:
|
||||
try:
|
||||
# 权利金净盈亏冻结 U(纠正旧版把买币预算差额当盈利的数据)
|
||||
sync_sim_cash_realized_pnl_usdt(conn, ex)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@@ -73,8 +73,9 @@ class SettleClosedPnlTests(unittest.TestCase):
|
||||
self.assertAlmostEqual(float(s["realized_pnl_usdt"]), 27.0, places=4)
|
||||
|
||||
|
||||
class SimCashPnlStatsTests(unittest.TestCase):
|
||||
def test_sim_cash_from_bridge_overrides_index_pnl(self):
|
||||
class SimPremiumPnlStatsTests(unittest.TestCase):
|
||||
def test_sim_uses_premium_net_not_bridge_cash(self):
|
||||
"""卖回−预算会把权利金本金算进盈利;必须用(收回−已付)×平仓指数."""
|
||||
import sqlite3
|
||||
|
||||
from lib.options.options_db import init_options_tables
|
||||
@@ -85,6 +86,7 @@ class SimCashPnlStatsTests(unittest.TestCase):
|
||||
conn.row_factory = sqlite3.Row
|
||||
init_options_tables(conn)
|
||||
ensure_bridge_table(conn)
|
||||
# 桥上现金差额 952.96,但权利金净盈亏仅 0.01 ETH × 2500 = 25U
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO options_spot_bridge(
|
||||
@@ -97,12 +99,12 @@ class SimCashPnlStatsTests(unittest.TestCase):
|
||||
INSERT INTO options_trades(
|
||||
inst_id, underlying, opt_type, sheets, eth_amount,
|
||||
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
|
||||
) VALUES (
|
||||
'ETH-USD-261009-2500-P', 'ETH', 'P', 1, 0.01,
|
||||
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'
|
||||
)
|
||||
"""
|
||||
@@ -111,62 +113,44 @@ class SimCashPnlStatsTests(unittest.TestCase):
|
||||
n = sync_sim_cash_realized_pnl_usdt(conn, None)
|
||||
self.assertEqual(n, 1)
|
||||
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()
|
||||
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()
|
||||
|
||||
def test_sim_cash_from_ledger_when_bridge_missing_recovered(self):
|
||||
def test_sim_deducts_fees_from_premium_pnl(self):
|
||||
import sqlite3
|
||||
|
||||
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.sim.db_lib import init_sim_tables
|
||||
|
||||
conn = sqlite3.connect(":memory:")
|
||||
conn.row_factory = sqlite3.Row
|
||||
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(
|
||||
"""
|
||||
INSERT INTO options_trades(
|
||||
inst_id, underlying, opt_type, sheets, eth_amount,
|
||||
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
|
||||
) VALUES (
|
||||
'ETH-USD-261009-2500-P', 'ETH', 'P', 1, 0.01,
|
||||
0.01, 0.02, 0.01, 'ETH',
|
||||
'closed', 1, 1000.0, 884.54,
|
||||
'2026-10-06 10:00:00', '2026-10-08 14:00:00'
|
||||
'BTC-USD-261008-86500-P', 'BTC', 'P', 1, 0.01,
|
||||
0.01, 0.02, 0.01, 'BTC',
|
||||
0.0001, 0.0001, 'closed', 1947.05, 80000.0,
|
||||
'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()
|
||||
n = sync_sim_cash_realized_pnl_usdt(conn, None)
|
||||
self.assertEqual(n, 1)
|
||||
sync_sim_cash_realized_pnl_usdt(conn, None)
|
||||
row = conn.execute(
|
||||
"SELECT realized_pnl_usdt FROM options_trades WHERE id=1"
|
||||
).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()
|
||||
|
||||
|
||||
|
||||
@@ -26,8 +26,8 @@ class ReviewLocalSyncFreezeTests(unittest.TestCase):
|
||||
created_at, closed_at
|
||||
) VALUES (
|
||||
'BTC-USD-261008-86500-P', 'BTC', 'P', 1, 0.01,
|
||||
0.01, 0.02, 0.01172, 'BTC',
|
||||
'closed', 1947.05, 85000.0,
|
||||
0.01, 0.02, 0.01, 'BTC',
|
||||
'closed', 850.0, 85000.0,
|
||||
'2026-10-05 05:11:30', '2026-10-07 10:03:53'
|
||||
)
|
||||
"""
|
||||
@@ -45,8 +45,8 @@ class ReviewLocalSyncFreezeTests(unittest.TestCase):
|
||||
("local_opt:1",),
|
||||
).fetchone()
|
||||
self.assertIsNotNone(row)
|
||||
# 必须是冻结现金 1947.05,不是 0.01172*999999
|
||||
self.assertAlmostEqual(float(row["realized_pnl_total"]), 1947.05, places=2)
|
||||
# (0.02-0.01)*85000=850,不是 0.01*999999
|
||||
self.assertAlmostEqual(float(row["realized_pnl_total"]), 850.0, places=2)
|
||||
conn.close()
|
||||
|
||||
def test_second_sync_stable_when_index_moves(self):
|
||||
@@ -70,7 +70,7 @@ class ReviewLocalSyncFreezeTests(unittest.TestCase):
|
||||
) VALUES (
|
||||
'BTC-USD-261008-86500-P', 'BTC', 'P', 1, 0.01,
|
||||
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'
|
||||
)
|
||||
"""
|
||||
@@ -99,7 +99,8 @@ class ReviewLocalSyncFreezeTests(unittest.TestCase):
|
||||
("local_opt:1",),
|
||||
).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)
|
||||
conn.close()
|
||||
|
||||
|
||||
Reference in New Issue
Block a user