Files
crypto_monitor/tests/test_hedge_exchange_pnl.py
T
2026-07-21 10:09:44 +08:00

106 lines
3.3 KiB
Python

"""对冲计划期权腿盈亏与交易所对齐."""
from __future__ import annotations
import sqlite3
import unittest
from lib.hedge_plan.hedge_plan_db import get_plan, init_hedge_plan_tables, insert_leg, insert_plan
from lib.hedge_plan.hedge_plan_settle_lib import (
backfill_hedge_option_legs_realized_pnl,
resolve_option_leg_realized_pnl,
)
class HedgeExchangePnlTest(unittest.TestCase):
def test_resolve_prefers_exchange(self):
leg = {
"inst_id": "ETH-USD_UM-260719-1850-P",
"opened_at": "2026-07-17 06:59:18",
"premium": 5.0,
}
hist = [
{
"instId": "ETH-USD_UM-260719-1850-P",
"uTime": "1784400000000",
"realizedPnl": "12.00",
"closeAvgPx": "30",
}
]
pnl, src = resolve_option_leg_realized_pnl(
leg=leg, hist_rows=hist, fallback=-5.0
)
self.assertEqual(src, "exchange")
self.assertEqual(pnl, 12.0)
def test_backfill_updates_plan_total(self):
conn = sqlite3.connect(":memory:")
conn.row_factory = sqlite3.Row
init_hedge_plan_tables(conn)
pid = insert_plan(
conn,
{
"plan_type": "options_options",
"status": "closed",
"underlying": "ETH",
"premium_total": 10,
"realized_pnl_options": 6.08,
"realized_pnl_total": 6.08,
"opened_at": "2026-07-17 06:59:18",
"closed_at": "2026-07-19 16:00:13",
},
)
insert_leg(
conn,
{
"plan_id": pid,
"leg_role": "option_a",
"inst_id": "ETH-USD_UM-260719-1890-C",
"opt_type": "C",
"strike": 1890,
"size": 10,
"premium": 5.92,
"status": "closed",
"realized_pnl": -5.92,
"opened_at": "2026-07-17 06:59:18",
"closed_at": "2026-07-19 16:00:13",
},
)
insert_leg(
conn,
{
"plan_id": pid,
"leg_role": "option_b",
"inst_id": "ETH-USD_UM-260719-1850-P",
"opt_type": "P",
"strike": 1850,
"size": 10,
"premium": 4.0,
"status": "closed",
"realized_pnl": 12.0,
"opened_at": "2026-07-17 06:59:18",
"closed_at": "2026-07-19 08:00:00",
},
)
hist = [
{
"instId": "ETH-USD_UM-260719-1890-C",
"uTime": "1784476813000",
"realizedPnl": "-5.50",
},
{
"instId": "ETH-USD_UM-260719-1850-P",
"uTime": "1784448000000",
"realizedPnl": "11.80",
},
]
out = backfill_hedge_option_legs_realized_pnl(conn, hist)
self.assertEqual(out["legs"], 2)
self.assertEqual(out["plans"], 1)
plan = get_plan(conn, pid)
self.assertAlmostEqual(float(plan["realized_pnl_options"]), 6.3, places=4)
self.assertAlmostEqual(float(plan["realized_pnl_total"]), 6.3, places=4)
if __name__ == "__main__":
unittest.main()