feat: expand header stats with total funds and profit-loss ratio

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
dekun
2026-07-07 02:14:18 +08:00
parent 659c0969fe
commit 814fe67a21
10 changed files with 138 additions and 10 deletions
+50 -1
View File
@@ -7,6 +7,8 @@ from typing import Any
EMBED_STRATEGY_PAGES = frozenset({"strategy", "strategy_trend", "strategy_roll", "strategy_records"})
_WIN_EPS = 1e-9
@dataclass(frozen=True)
class EmbedRenderPlan:
@@ -50,6 +52,48 @@ def embed_render_plan(page: str, embed_mode: str | None) -> EmbedRenderPlan:
)
def profit_loss_ratio_from_averages(avg_win: float | None, avg_loss: float | None) -> float | None:
"""盈亏比 = 平均盈利 / |平均亏损|。"""
if avg_win is None or avg_loss is None:
return None
try:
aw = float(avg_win)
al = float(avg_loss)
except (TypeError, ValueError):
return None
if al == 0:
return None
return round(aw / abs(al), 2)
def profit_loss_ratio_from_trades(trades: list[dict[str, Any]] | None) -> float | None:
wins: list[float] = []
losses: list[float] = []
for row in trades or []:
if not isinstance(row, dict):
continue
try:
pnl = float(row.get("effective_pnl_amount") or row.get("pnl_amount") or 0)
except (TypeError, ValueError):
continue
if pnl > _WIN_EPS:
wins.append(pnl)
elif pnl < -_WIN_EPS:
losses.append(pnl)
avg_win = sum(wins) / len(wins) if wins else None
avg_loss = sum(losses) / len(losses) if losses else None
return profit_loss_ratio_from_averages(avg_win, avg_loss)
def total_funds_usdt(funding_usdt: float | None, trading_usdt: float | None) -> float | None:
if funding_usdt is None:
return None
try:
return round(float(funding_usdt) + float(trading_usdt or 0), 2)
except (TypeError, ValueError):
return None
def trade_records_summary(conn, start_bj: str, end_bj: str, tr_ts: str) -> dict[str, Any]:
"""顶栏统计用 COUNT,避免 embed 壳拉 1000 行交易记录。"""
from lib.trade.trade_result_lib import sql_effective_pnl_expr
@@ -59,7 +103,9 @@ def trade_records_summary(conn, start_bj: str, end_bj: str, tr_ts: str) -> dict[
f"""
SELECT
COUNT(*) AS total,
SUM(CASE WHEN {pnl_sql} > 0 THEN 1 ELSE 0 END) AS wins
SUM(CASE WHEN {pnl_sql} > 0 THEN 1 ELSE 0 END) AS wins,
AVG(CASE WHEN {pnl_sql} > 0 THEN {pnl_sql} END) AS avg_win,
AVG(CASE WHEN {pnl_sql} < 0 THEN {pnl_sql} END) AS avg_loss
FROM trade_records
WHERE {tr_ts} >= ? AND {tr_ts} <= ?
AND COALESCE(result, '') != '错过'
@@ -70,10 +116,13 @@ def trade_records_summary(conn, start_bj: str, end_bj: str, tr_ts: str) -> dict[
total = int(row["total"] or 0) if row else 0
wins = int(row["wins"] or 0) if row else 0
rate = round(wins / total * 100, 2) if total else 0
avg_win = float(row["avg_win"]) if row and row["avg_win"] is not None else None
avg_loss = float(row["avg_loss"]) if row and row["avg_loss"] is not None else None
return {
"records": [],
"total": total,
"rate": rate,
"profit_loss_ratio": profit_loss_ratio_from_averages(avg_win, avg_loss),
}
@@ -1053,6 +1053,10 @@ function refreshAccountSnapshot(){
const el = document.getElementById("total-capital");
if(el) el.innerText = (data.funding_usdt === null || data.funding_usdt === undefined) ? "—" : `${Number(data.funding_usdt).toFixed(2)}U`;
}
if (typeof data.total_funds !== "undefined") {
const el = document.getElementById("total-funds");
if(el) el.innerText = (data.total_funds === null || data.total_funds === undefined) ? "—" : `${Number(data.total_funds).toFixed(2)}U`;
}
if (typeof data.current_capital !== "undefined") {
const el = document.getElementById("current-capital");
if(el) el.innerText = `${Number(data.current_capital).toFixed(2)}U`;
+1 -1
View File
@@ -7,7 +7,7 @@
<link rel="stylesheet" href="/static/instance_theme_early.css?v=4">
<link rel="stylesheet" href="/static/account_risk_badge.css?v=4">
<link rel="stylesheet" href="/static/instance_page.css?v=3">
<link rel="stylesheet" href="/static/instance_theme.css?v=59">
<link rel="stylesheet" href="/static/instance_theme.css?v=60">
<script src="/static/account_risk_badge.js?v=4"></script>
<meta name="theme-color" content="#0b0d14">
<title>{{ exchange_display }} · 加密货币 | 交易监控复盘系统</title>
+5 -1
View File
@@ -17,7 +17,7 @@
<link rel="manifest" href="/static/icons/manifest.webmanifest">
<title>{{ exchange_display }} · 加密货币 | 交易监控复盘系统</title>
<link rel="stylesheet" href="/static/instance_page.css?v=1">
<link rel="stylesheet" href="/static/instance_theme.css?v=59">
<link rel="stylesheet" href="/static/instance_theme.css?v=60">
</head>
<body
@@ -1599,6 +1599,10 @@ function refreshAccountSnapshot(){
const el = document.getElementById("total-capital");
if(el) el.innerText = (data.funding_usdt === null || data.funding_usdt === undefined) ? "—" : `${Number(data.funding_usdt).toFixed(2)}U`;
}
if (typeof data.total_funds !== "undefined") {
const el = document.getElementById("total-funds");
if(el) el.innerText = (data.total_funds === null || data.total_funds === undefined) ? "—" : `${Number(data.total_funds).toFixed(2)}U`;
}
if (typeof data.current_capital !== "undefined") {
const el = document.getElementById("current-capital");
if(el) el.innerText = `${Number(data.current_capital).toFixed(2)}U`;
@@ -46,6 +46,10 @@
<div class="label">交易所</div>
<div class="value">{{ exchange_display }}</div>
</div>
<div class="stat-strip-item">
<div class="label">交易日</div>
<div class="value">{{ trading_day }}</div>
</div>
<div class="stat-strip-item stat-strip-item--primary">
<div class="label">总交易</div>
<div class="value" id="stat-total">{{ total }}</div>
@@ -54,16 +58,20 @@
<div class="label">胜率</div>
<div class="value" id="stat-rate">{{ rate }}%</div>
</div>
<div class="stat-strip-item" title="平均盈利 ÷ 平均亏损(当前列表窗口)">
<div class="label">盈亏比</div>
<div class="value" id="stat-pl-ratio">{% if profit_loss_ratio is not none %}{{ profit_loss_ratio }}{% else %}—{% endif %}</div>
</div>
<div class="stat-strip-item">
<div class="label">总资金</div>
<div class="value" id="total-funds">{% if total_funds is not none %}{{ funds_fmt(total_funds) }}U{% else %}—{% endif %}</div>
</div>
<div class="stat-strip-item">
<div class="label">资金账户</div>
<div class="value" id="total-capital">{% if funding_usdt is not none %}{{ funds_fmt(funding_usdt) }}U{% else %}—{% endif %}</div>
</div>
<div class="stat-strip-item">
<div class="label">交易</div>
<div class="value">{{ trading_day }}</div>
</div>
<div class="stat-strip-item">
<div class="label">当日资金</div>
<div class="label">交易账户</div>
<div class="value" id="current-capital">{{ funds_fmt(current_capital) }}U</div>
</div>
<div class="stat-strip-item stat-strip-item--pnl">