币本位期权数据统计按指数折算为U,不再误标USDC导致0.00
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -2367,7 +2367,14 @@
|
||||
}
|
||||
}
|
||||
|
||||
function paintPnlStat(el, value) {
|
||||
function statsPnlUnit(d) {
|
||||
const u = String((d && d.pnl_unit) || "").trim().toUpperCase();
|
||||
if (u === "U" || u === "USDT") return "U";
|
||||
if (u === "ETH" || u === "BTC") return u;
|
||||
return "USDC";
|
||||
}
|
||||
|
||||
function paintPnlStat(el, value, unit) {
|
||||
if (!el) return;
|
||||
if (value == null || value === "" || Number.isNaN(Number(value))) {
|
||||
el.textContent = "—";
|
||||
@@ -2375,7 +2382,9 @@
|
||||
return;
|
||||
}
|
||||
const n = Number(value);
|
||||
el.textContent = (n > 0 ? "+" : "") + fmt(n, 2) + " USDC";
|
||||
const label = unit || "USDC";
|
||||
const decimals = label === "ETH" || label === "BTC" ? 6 : 2;
|
||||
el.textContent = (n > 0 ? "+" : "") + fmt(n, decimals) + " " + label;
|
||||
el.classList.toggle("pos-pnl-profit", n > 0);
|
||||
el.classList.toggle("pos-pnl-loss", n < 0);
|
||||
}
|
||||
@@ -2405,9 +2414,10 @@
|
||||
paintStatsCharts(null);
|
||||
return;
|
||||
}
|
||||
paintPnlStat(totalPnlEl, d.total_pnl);
|
||||
paintPnlStat(netRealizedEl, d.net_realized_pnl);
|
||||
paintPnlStat(openFloatEl, d.open_float_pnl);
|
||||
const unit = statsPnlUnit(d);
|
||||
paintPnlStat(totalPnlEl, d.total_pnl, unit);
|
||||
paintPnlStat(netRealizedEl, d.net_realized_pnl, unit);
|
||||
paintPnlStat(openFloatEl, d.open_float_pnl, unit);
|
||||
if (winEl) winEl.textContent = d.total_closed ? d.win_rate + "%" : "0%";
|
||||
if (plrEl) {
|
||||
plrEl.textContent = d.profit_loss_ratio != null ? String(d.profit_loss_ratio) : "—";
|
||||
@@ -2415,11 +2425,11 @@
|
||||
if (closedEl) closedEl.textContent = String(d.total_closed || 0);
|
||||
if (profitEl) {
|
||||
profitEl.textContent = d.avg_win != null && d.avg_win > 0
|
||||
? fmt(d.avg_win, 2) + " USDC" : (d.win_count ? "0 USDC" : "—");
|
||||
? fmt(d.avg_win, 2) + " " + unit : (d.win_count ? "0 " + unit : "—");
|
||||
}
|
||||
if (lossEl) {
|
||||
lossEl.textContent = d.avg_loss != null && d.avg_loss > 0
|
||||
? fmt(d.avg_loss, 2) + " USDC" : (d.loss_count ? "0 USDC" : "—");
|
||||
? fmt(d.avg_loss, 2) + " " + unit : (d.loss_count ? "0 " + unit : "—");
|
||||
}
|
||||
if (avgHoldEl) avgHoldEl.textContent = fmtDuration(d.avg_hold_sec);
|
||||
if (winHoldEl) winHoldEl.textContent = fmtDuration(d.avg_win_hold_sec);
|
||||
@@ -2484,17 +2494,18 @@
|
||||
|
||||
const profit = Math.max(0, Number(d.avg_win) || 0);
|
||||
const loss = Math.max(0, Number(d.avg_loss) || 0);
|
||||
const unit = statsPnlUnit(d);
|
||||
const pnlTotal = profit + loss;
|
||||
if (pnlTotal > 0) {
|
||||
setBarFill(profitBar, (profit / pnlTotal) * 100);
|
||||
setBarFill(lossBar, (loss / pnlTotal) * 100);
|
||||
if (profitBarLabel) profitBarLabel.textContent = fmt(profit, 2) + " USDC";
|
||||
if (lossBarLabel) lossBarLabel.textContent = fmt(loss, 2) + " USDC";
|
||||
if (profitBarLabel) profitBarLabel.textContent = fmt(profit, 2) + " " + unit;
|
||||
if (lossBarLabel) lossBarLabel.textContent = fmt(loss, 2) + " " + unit;
|
||||
} else {
|
||||
setBarFill(profitBar, 0);
|
||||
setBarFill(lossBar, 0);
|
||||
if (profitBarLabel) profitBarLabel.textContent = d.win_count ? "0 USDC" : "—";
|
||||
if (lossBarLabel) lossBarLabel.textContent = d.loss_count ? "0 USDC" : "—";
|
||||
if (profitBarLabel) profitBarLabel.textContent = d.win_count ? "0 " + unit : "—";
|
||||
if (lossBarLabel) lossBarLabel.textContent = d.loss_count ? "0 " + unit : "—";
|
||||
}
|
||||
|
||||
const winHold = Number(d.avg_win_hold_sec) || 0;
|
||||
|
||||
@@ -1815,8 +1815,34 @@ def register_options_routes(app: Flask, cfg: dict[str, Any]) -> None:
|
||||
if raw_live is None:
|
||||
return jsonify({"ok": False, "msg": "获取期权持仓失败"})
|
||||
history = load_options_history(ex, cfg)
|
||||
stats = compute_options_stats_from_history(history)
|
||||
index_px = None
|
||||
try:
|
||||
from lib.exchange.okx_options_lib import fetch_index_price
|
||||
from lib.options.options_margin_mode_lib import (
|
||||
is_coin_margin_mode,
|
||||
normalize_options_margin_mode,
|
||||
)
|
||||
|
||||
underly = (cfg.get("default_underly") or "ETH").strip().upper() or "ETH"
|
||||
if is_coin_margin_mode(normalize_options_margin_mode(cfg.get("margin_mode"))):
|
||||
index_px = fetch_index_price(ex, underly)
|
||||
except Exception:
|
||||
index_px = None
|
||||
stats = compute_options_stats_from_history(history, index_px=index_px)
|
||||
open_float = sum_options_net_pnl_usdc(cfg, ex, raw_live)
|
||||
# 币本位浮盈为币数量,折算为 U 再与已平合计
|
||||
if open_float is not None and str(stats.get("pnl_unit") or "") == "U":
|
||||
px = index_px
|
||||
if px is None or px <= 0:
|
||||
for h in history:
|
||||
try:
|
||||
px = float(h.get("idx_px") or 0)
|
||||
except (TypeError, ValueError):
|
||||
px = 0
|
||||
if px > 0:
|
||||
break
|
||||
if px and px > 0:
|
||||
open_float = round(float(open_float) * float(px), 4)
|
||||
net_realized = _safe_float(stats.get("net_realized_pnl")) or 0.0
|
||||
total_pnl = None
|
||||
if open_float is not None:
|
||||
|
||||
@@ -6,6 +6,7 @@ from typing import Any
|
||||
|
||||
from lib.instance.instance_embed_context_lib import profit_loss_ratio_from_averages
|
||||
from lib.options.options_db import init_options_tables
|
||||
from lib.options.options_margin_mode_lib import margin_mode_from_inst_id, premium_ccy_for_mode
|
||||
|
||||
|
||||
def _parse_ts(raw: Any) -> datetime | None:
|
||||
@@ -33,8 +34,62 @@ def _avg_seconds(values: list[float]) -> float | None:
|
||||
return round(sum(values) / len(values), 1)
|
||||
|
||||
|
||||
def compute_options_stats_from_history(history: list[dict[str, Any]]) -> dict[str, Any]:
|
||||
"""基于期权历史列表(交易所)计算统计."""
|
||||
def _safe_float(v: Any) -> float | None:
|
||||
if v is None or v == "":
|
||||
return None
|
||||
try:
|
||||
return float(v)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def _row_premium_ccy(row: dict[str, Any]) -> str:
|
||||
ccy = str(row.get("premium_ccy") or "").strip().upper()
|
||||
if ccy:
|
||||
return ccy
|
||||
inst = str(row.get("inst_id") or "").strip()
|
||||
mode = str(row.get("margin_mode") or "").strip().lower()
|
||||
underly = str(row.get("underlying") or (inst.split("-")[0] if inst else "ETH") or "ETH")
|
||||
if mode:
|
||||
return premium_ccy_for_mode(mode, underly)
|
||||
if not inst:
|
||||
# 旧统计行无合约信息时按 USDC 口径,避免默认币本位把盈亏跳过
|
||||
return "USDC"
|
||||
return premium_ccy_for_mode(margin_mode_from_inst_id(inst), underly)
|
||||
|
||||
|
||||
def _pnl_as_usdt(row: dict[str, Any], *, fallback_index: float | None = None) -> float | None:
|
||||
"""已平/浮盈统一折算为 USDT(币本位×指数;USDC 原样)."""
|
||||
pnl = _safe_float(row.get("realized_pnl"))
|
||||
if pnl is None:
|
||||
pnl = _safe_float(row.get("upl"))
|
||||
if pnl is None:
|
||||
return None
|
||||
ccy = _row_premium_ccy(row)
|
||||
if ccy in ("ETH", "BTC"):
|
||||
px = _safe_float(row.get("idx_px") or row.get("idxPx") or row.get("index_px"))
|
||||
if px is None or px <= 0:
|
||||
px = fallback_index
|
||||
if px is None or px <= 0:
|
||||
return None
|
||||
return float(pnl) * float(px)
|
||||
return float(pnl)
|
||||
|
||||
|
||||
def _history_index_px(history: list[dict[str, Any]]) -> float | None:
|
||||
for row in history:
|
||||
px = _safe_float(row.get("idx_px") or row.get("idxPx") or row.get("index_px"))
|
||||
if px is not None and px > 0:
|
||||
return px
|
||||
return None
|
||||
|
||||
|
||||
def compute_options_stats_from_history(
|
||||
history: list[dict[str, Any]],
|
||||
*,
|
||||
index_px: float | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""基于期权历史列表计算统计;币本位盈亏按指数折算为 U."""
|
||||
wins: list[float] = []
|
||||
losses: list[float] = []
|
||||
win_holds: list[float] = []
|
||||
@@ -42,8 +97,13 @@ def compute_options_stats_from_history(history: list[dict[str, Any]]) -> dict[st
|
||||
all_holds: list[float] = []
|
||||
open_holds: list[float] = []
|
||||
now = datetime.now()
|
||||
fallback_idx = index_px if index_px is not None and index_px > 0 else _history_index_px(history)
|
||||
coinish = False
|
||||
|
||||
for row in history:
|
||||
ccy = _row_premium_ccy(row)
|
||||
if ccy in ("ETH", "BTC"):
|
||||
coinish = True
|
||||
if row.get("status") == "open":
|
||||
start = _parse_ts(row.get("created_at"))
|
||||
if start is not None:
|
||||
@@ -51,12 +111,8 @@ def compute_options_stats_from_history(history: list[dict[str, Any]]) -> dict[st
|
||||
if sec >= 0:
|
||||
open_holds.append(sec)
|
||||
continue
|
||||
pnl_raw = row.get("realized_pnl")
|
||||
if pnl_raw is None:
|
||||
continue
|
||||
try:
|
||||
pnl = float(pnl_raw)
|
||||
except (TypeError, ValueError):
|
||||
pnl = _pnl_as_usdt(row, fallback_index=fallback_idx)
|
||||
if pnl is None:
|
||||
continue
|
||||
hold = _hold_seconds(row.get("created_at"), row.get("closed_at"))
|
||||
if hold is not None:
|
||||
@@ -94,6 +150,8 @@ def compute_options_stats_from_history(history: list[dict[str, Any]]) -> dict[st
|
||||
"avg_loss_hold_sec": _avg_seconds(loss_holds),
|
||||
"open_count": len(open_holds),
|
||||
"avg_open_hold_sec": _avg_seconds(open_holds),
|
||||
"pnl_unit": "U" if coinish else "USDC",
|
||||
"index_px": fallback_idx,
|
||||
}
|
||||
|
||||
|
||||
@@ -103,7 +161,7 @@ def compute_options_stats(get_db) -> dict[str, Any]:
|
||||
init_options_tables(conn)
|
||||
closed_rows = conn.execute(
|
||||
"""
|
||||
SELECT realized_pnl, created_at, closed_at
|
||||
SELECT realized_pnl, created_at, closed_at, inst_id, premium_ccy, margin_mode
|
||||
FROM options_trades
|
||||
WHERE status = 'closed' AND realized_pnl IS NOT NULL
|
||||
"""
|
||||
@@ -116,58 +174,19 @@ def compute_options_stats(get_db) -> dict[str, Any]:
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
wins: list[float] = []
|
||||
losses: list[float] = []
|
||||
win_holds: list[float] = []
|
||||
loss_holds: list[float] = []
|
||||
all_holds: list[float] = []
|
||||
now = datetime.now()
|
||||
|
||||
hist = []
|
||||
for row in closed_rows:
|
||||
pnl = float(row["realized_pnl"])
|
||||
hold = _hold_seconds(row["created_at"], row["closed_at"])
|
||||
if hold is not None:
|
||||
all_holds.append(hold)
|
||||
if pnl > 0:
|
||||
wins.append(pnl)
|
||||
if hold is not None:
|
||||
win_holds.append(hold)
|
||||
elif pnl < 0:
|
||||
losses.append(pnl)
|
||||
if hold is not None:
|
||||
loss_holds.append(hold)
|
||||
|
||||
open_holds: list[float] = []
|
||||
hist.append(
|
||||
{
|
||||
"status": "closed",
|
||||
"realized_pnl": row["realized_pnl"],
|
||||
"created_at": row["created_at"],
|
||||
"closed_at": row["closed_at"],
|
||||
"inst_id": row["inst_id"] if "inst_id" in row.keys() else None,
|
||||
"premium_ccy": row["premium_ccy"] if "premium_ccy" in row.keys() else None,
|
||||
"margin_mode": row["margin_mode"] if "margin_mode" in row.keys() else None,
|
||||
}
|
||||
)
|
||||
for row in open_rows:
|
||||
start = _parse_ts(row["created_at"])
|
||||
if start is None:
|
||||
continue
|
||||
sec = (now - start).total_seconds()
|
||||
if sec >= 0:
|
||||
open_holds.append(sec)
|
||||
|
||||
total_closed = len(wins) + len(losses)
|
||||
win_rate = round(len(wins) / total_closed * 100, 2) if total_closed else 0
|
||||
avg_win = sum(wins) / len(wins) if wins else None
|
||||
avg_loss = sum(losses) / len(losses) if losses else None
|
||||
|
||||
total_profit = round(sum(wins), 4) if wins else 0.0
|
||||
total_loss = round(abs(sum(losses)), 4) if losses else 0.0
|
||||
net_realized = round(sum(wins) + sum(losses), 4)
|
||||
return {
|
||||
"total_closed": total_closed,
|
||||
"win_count": len(wins),
|
||||
"loss_count": len(losses),
|
||||
"win_rate": win_rate,
|
||||
"profit_loss_ratio": profit_loss_ratio_from_averages(avg_win, avg_loss),
|
||||
"avg_win": round(avg_win, 4) if avg_win is not None else None,
|
||||
"avg_loss": round(abs(avg_loss), 4) if avg_loss is not None else None,
|
||||
"total_profit": total_profit,
|
||||
"total_loss": total_loss,
|
||||
"net_realized_pnl": net_realized,
|
||||
"avg_hold_sec": _avg_seconds(all_holds),
|
||||
"avg_win_hold_sec": _avg_seconds(win_holds),
|
||||
"avg_loss_hold_sec": _avg_seconds(loss_holds),
|
||||
"open_count": len(open_holds),
|
||||
"avg_open_hold_sec": _avg_seconds(open_holds),
|
||||
}
|
||||
hist.append({"status": "open", "created_at": row["created_at"]})
|
||||
return compute_options_stats_from_history(hist)
|
||||
|
||||
@@ -351,4 +351,4 @@
|
||||
</div>
|
||||
</div>
|
||||
<script src="/static/options_expiry_countdown.js?v=1"></script>
|
||||
<script src="/static/options_panel.js?v=65"></script>
|
||||
<script src="/static/options_panel.js?v=66"></script>
|
||||
|
||||
@@ -84,3 +84,21 @@ class OptionsStatsLibTests(TestCase):
|
||||
self.assertAlmostEqual(out["profit_loss_ratio"], 0.33, places=2)
|
||||
self.assertEqual(out["open_count"], 1)
|
||||
self.assertAlmostEqual(out["net_realized_pnl"], round(0.87 - 3.99 - 1.33, 4), places=4)
|
||||
|
||||
def test_compute_options_stats_coin_to_usdt(self):
|
||||
history = [
|
||||
{
|
||||
"status": "closed",
|
||||
"realized_pnl": 0.00078,
|
||||
"premium_ccy": "ETH",
|
||||
"margin_mode": "coin",
|
||||
"inst_id": "ETH-USD-260822-2250-C",
|
||||
"idx_px": 2280,
|
||||
"created_at": "2026-08-20 08:00:00",
|
||||
"closed_at": "2026-08-20 13:32:00",
|
||||
}
|
||||
]
|
||||
out = compute_options_stats_from_history(history)
|
||||
self.assertEqual(out["pnl_unit"], "U")
|
||||
self.assertEqual(out["total_closed"], 1)
|
||||
self.assertAlmostEqual(out["net_realized_pnl"], 0.00078 * 2280, places=4)
|
||||
|
||||
Reference in New Issue
Block a user