Hub monitor: read-only OKX options positions aggregation (Phase B).
Expose /api/hub/options/snapshot from OKX instance and render options summary on hub monitor cards when the options capability is enabled. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -0,0 +1,83 @@
|
||||
"""中控只读聚合:OKX 期权持仓 / 资金 / 本地统计。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
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
|
||||
|
||||
|
||||
def _compute_options_stats(get_db) -> dict[str, Any]:
|
||||
conn = get_db()
|
||||
try:
|
||||
init_options_tables(conn)
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT realized_pnl FROM options_trades
|
||||
WHERE status = 'closed' AND realized_pnl IS NOT NULL
|
||||
"""
|
||||
).fetchall()
|
||||
finally:
|
||||
conn.close()
|
||||
wins: list[float] = []
|
||||
losses: list[float] = []
|
||||
for row in rows:
|
||||
pnl = float(row["realized_pnl"])
|
||||
if pnl > 0:
|
||||
wins.append(pnl)
|
||||
elif pnl < 0:
|
||||
losses.append(pnl)
|
||||
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
|
||||
return {
|
||||
"total_closed": total_closed,
|
||||
"win_rate": win_rate,
|
||||
"profit_loss_ratio": profit_loss_ratio_from_averages(avg_win, avg_loss),
|
||||
"total_profit": round(sum(wins), 4) if wins else 0.0,
|
||||
"total_loss": round(abs(sum(losses)), 4) if losses else 0.0,
|
||||
}
|
||||
|
||||
|
||||
def build_options_hub_snapshot(cfg: dict[str, Any]) -> dict[str, Any]:
|
||||
if not cfg.get("enabled"):
|
||||
return {"ok": True, "enabled": False}
|
||||
ex = cfg.get("exchange_options")
|
||||
ready_fn = cfg.get("options_api_ready")
|
||||
if not callable(ready_fn):
|
||||
return {"ok": False, "enabled": True, "msg": "期权模块未就绪"}
|
||||
ok, reason = ready_fn(ex)
|
||||
if not ok:
|
||||
return {"ok": False, "enabled": True, "msg": reason or "期权 API 未配置"}
|
||||
try:
|
||||
raw = cfg["fetch_option_positions"](ex)
|
||||
positions = [cfg["format_position_row"](p) for p in raw]
|
||||
upl_total = 0.0
|
||||
has_upl = False
|
||||
for p in positions:
|
||||
upl = p.get("upl")
|
||||
if upl is None:
|
||||
continue
|
||||
has_upl = True
|
||||
upl_total += float(upl)
|
||||
bal = cfg["fetch_options_balances"](ex)
|
||||
stats = _compute_options_stats(cfg["get_db"])
|
||||
return {
|
||||
"ok": True,
|
||||
"enabled": True,
|
||||
"positions": positions,
|
||||
"position_count": len(positions),
|
||||
"upl_total_usdc": round(upl_total, 4) if has_upl else None,
|
||||
"balances": bal,
|
||||
"funding_usdc": bal.get("funding_usdc"),
|
||||
"funding_usdt": bal.get("funding_usdt"),
|
||||
"trading_usdc": bal.get("trading_usdc"),
|
||||
"trading_usdt": bal.get("trading_usdt"),
|
||||
"stats": stats,
|
||||
"trade_budget": cfg.get("trade_budget"),
|
||||
"account_label": cfg.get("account_label") or "OKX期权",
|
||||
}
|
||||
except Exception as e:
|
||||
return {"ok": False, "enabled": True, "msg": str(e)}
|
||||
@@ -54,10 +54,22 @@ def install_options_trading(app: Flask, repo_root: str, app_module: Any) -> None
|
||||
cfg = _build_cfg(app_module)
|
||||
app.extensions["options_cfg"] = cfg
|
||||
register_options_routes(app, cfg)
|
||||
_register_options_hub_bridge(app, cfg)
|
||||
if enabled:
|
||||
_start_monitor_thread(app, cfg)
|
||||
|
||||
|
||||
def _register_options_hub_bridge(app: Flask, cfg: dict[str, Any]) -> None:
|
||||
from lib.options.options_hub_lib import build_options_hub_snapshot
|
||||
|
||||
def snapshot_fn():
|
||||
return build_options_hub_snapshot(cfg)
|
||||
|
||||
hub_ctx = dict(app.config.get("HUB_CTX") or {})
|
||||
hub_ctx["options_snapshot_fn"] = snapshot_fn
|
||||
app.config["HUB_CTX"] = hub_ctx
|
||||
|
||||
|
||||
def _build_cfg(app_module: Any) -> dict[str, Any]:
|
||||
from lib.exchange.okx_options_lib import (
|
||||
build_option_chain,
|
||||
|
||||
Reference in New Issue
Block a user