Initialize crypto_monitor_user (user edition) from monitor codebase.
Retarget git remote, install path, and deploy docs from crypto_monitor to crypto_monitor_user. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -0,0 +1 @@
|
||||
# hedge_plan package
|
||||
@@ -0,0 +1,385 @@
|
||||
"""对冲计划:情景测算与全仓建议仓(纯函数,无 IO)."""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Optional
|
||||
|
||||
|
||||
def _f(v: Any) -> Optional[float]:
|
||||
if v is None or v == "":
|
||||
return None
|
||||
try:
|
||||
return float(v)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def perp_coin_amount(*, contracts: float, contract_size: float) -> float:
|
||||
return float(contracts) * float(contract_size or 1.0)
|
||||
|
||||
|
||||
def perp_pnl(
|
||||
*,
|
||||
direction: str,
|
||||
entry: float,
|
||||
exit_px: float,
|
||||
contracts: float,
|
||||
contract_size: float,
|
||||
) -> float:
|
||||
coins = perp_coin_amount(contracts=contracts, contract_size=contract_size)
|
||||
d = (direction or "long").strip().lower()
|
||||
if d == "short":
|
||||
return (float(entry) - float(exit_px)) * coins
|
||||
return (float(exit_px) - float(entry)) * coins
|
||||
|
||||
|
||||
def option_premium_total(*, ask: float, sheets: float, ct_mult: float) -> float:
|
||||
"""卖一报价为每 1 币;权利金 = ask × 张数 × ct_mult."""
|
||||
return float(ask) * float(sheets) * float(ct_mult or 0.01)
|
||||
|
||||
|
||||
def option_expiry_pnl(
|
||||
*,
|
||||
opt_type: str,
|
||||
strike: float,
|
||||
spot: float,
|
||||
sheets: float,
|
||||
ct_mult: float,
|
||||
premium_paid: float,
|
||||
) -> float:
|
||||
o = (opt_type or "").strip().upper()
|
||||
intrinsic_per_coin = 0.0
|
||||
if o in ("C", "CALL"):
|
||||
intrinsic_per_coin = max(0.0, float(spot) - float(strike))
|
||||
elif o in ("P", "PUT"):
|
||||
intrinsic_per_coin = max(0.0, float(strike) - float(spot))
|
||||
else:
|
||||
return -float(premium_paid)
|
||||
value = intrinsic_per_coin * float(sheets) * float(ct_mult or 0.01)
|
||||
return value - float(premium_paid)
|
||||
|
||||
|
||||
def suggest_contracts_from_notional(
|
||||
*,
|
||||
notional: float,
|
||||
entry: float,
|
||||
contract_size: float,
|
||||
) -> float:
|
||||
if entry <= 0 or contract_size <= 0 or notional <= 0:
|
||||
return 0.0
|
||||
return float(notional) / (float(entry) * float(contract_size))
|
||||
|
||||
|
||||
def floor_contracts_to_precision(contracts: float, decimals: int) -> float:
|
||||
"""按交易所张数精度向下取整,避免建议张数超过可用保证金."""
|
||||
import math
|
||||
|
||||
raw = float(contracts or 0.0)
|
||||
if raw <= 0:
|
||||
return 0.0
|
||||
try:
|
||||
d = int(decimals)
|
||||
except (TypeError, ValueError):
|
||||
d = 0
|
||||
if d <= 0:
|
||||
return float(math.floor(raw + 1e-12))
|
||||
scale = 10**d
|
||||
return math.floor(raw * scale + 1e-12) / scale
|
||||
|
||||
|
||||
def build_perp_options_preview(
|
||||
*,
|
||||
direction: str,
|
||||
entry: float,
|
||||
tp: float,
|
||||
sl: float,
|
||||
contracts: float,
|
||||
contract_size: float,
|
||||
opt_type: str,
|
||||
strike: float,
|
||||
sheets: float,
|
||||
ct_mult: float,
|
||||
premium_paid: float,
|
||||
index_px: Optional[float] = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
永期情景.
|
||||
止盈账:永续止盈盈利 - 权利金.
|
||||
止损账:期权到期内在(按 SL 价) - 永续止损亏损额.
|
||||
"""
|
||||
d = (direction or "long").strip().lower()
|
||||
pnl_tp_perp = perp_pnl(
|
||||
direction=d, entry=entry, exit_px=tp, contracts=contracts, contract_size=contract_size
|
||||
)
|
||||
pnl_sl_perp = perp_pnl(
|
||||
direction=d, entry=entry, exit_px=sl, contracts=contracts, contract_size=contract_size
|
||||
)
|
||||
# 止盈统计口径
|
||||
tp_total = float(pnl_tp_perp) - float(premium_paid)
|
||||
# 止损:期权按 SL 价结算内在 - |永续亏损|
|
||||
opt_at_sl = option_expiry_pnl(
|
||||
opt_type=opt_type,
|
||||
strike=strike,
|
||||
spot=sl,
|
||||
sheets=sheets,
|
||||
ct_mult=ct_mult,
|
||||
premium_paid=premium_paid,
|
||||
)
|
||||
sl_total = float(opt_at_sl) - abs(float(pnl_sl_perp)) if pnl_sl_perp < 0 else float(opt_at_sl) + float(
|
||||
pnl_sl_perp
|
||||
)
|
||||
# 有符号相加更稳:期权盈亏 + 永续盈亏
|
||||
sl_total_signed = float(opt_at_sl) + float(pnl_sl_perp)
|
||||
|
||||
spot = float(index_px) if index_px is not None else float(entry)
|
||||
opt_flat = option_expiry_pnl(
|
||||
opt_type=opt_type,
|
||||
strike=strike,
|
||||
spot=spot,
|
||||
sheets=sheets,
|
||||
ct_mult=ct_mult,
|
||||
premium_paid=premium_paid,
|
||||
)
|
||||
flat_total = 0.0 + float(opt_flat)
|
||||
|
||||
opt_at_tp = option_expiry_pnl(
|
||||
opt_type=opt_type,
|
||||
strike=strike,
|
||||
spot=tp,
|
||||
sheets=sheets,
|
||||
ct_mult=ct_mult,
|
||||
premium_paid=premium_paid,
|
||||
)
|
||||
|
||||
return {
|
||||
"plan_type": "perp_options",
|
||||
"direction": d,
|
||||
"contracts": contracts,
|
||||
"coin_amount": perp_coin_amount(contracts=contracts, contract_size=contract_size),
|
||||
"premium_paid": round(float(premium_paid), 6),
|
||||
"scenarios": [
|
||||
{
|
||||
"id": "tp",
|
||||
"label": "止盈(计划结束口径)",
|
||||
"spot": tp,
|
||||
"perp_pnl": round(pnl_tp_perp, 4),
|
||||
"options_pnl": round(-float(premium_paid), 4),
|
||||
"total": round(tp_total, 4),
|
||||
"note": "止盈盈利 − 权利金;期权可不强平",
|
||||
},
|
||||
{
|
||||
"id": "sl",
|
||||
"label": "止损(计划结束口径)",
|
||||
"spot": sl,
|
||||
"perp_pnl": round(pnl_sl_perp, 4),
|
||||
"options_pnl": round(opt_at_sl, 4),
|
||||
"total": round(sl_total_signed, 4),
|
||||
"note": "期权盈利 − 永续亏损(有符号相加);期权须强平",
|
||||
},
|
||||
{
|
||||
"id": "flat",
|
||||
"label": "到期·现价附近",
|
||||
"spot": spot,
|
||||
"perp_pnl": 0.0,
|
||||
"options_pnl": round(opt_flat, 4),
|
||||
"total": round(flat_total, 4),
|
||||
"note": "示意:永续未动,期权按到期内在",
|
||||
},
|
||||
{
|
||||
"id": "expiry_tp",
|
||||
"label": "到期·止盈价",
|
||||
"spot": tp,
|
||||
"perp_pnl": round(pnl_tp_perp, 4),
|
||||
"options_pnl": round(opt_at_tp, 4),
|
||||
"total": round(pnl_tp_perp + opt_at_tp, 4),
|
||||
"note": "若期权拿到 TP 价到期(参考)",
|
||||
},
|
||||
{
|
||||
"id": "expiry_sl",
|
||||
"label": "到期·止损价",
|
||||
"spot": sl,
|
||||
"perp_pnl": round(pnl_sl_perp, 4),
|
||||
"options_pnl": round(opt_at_sl, 4),
|
||||
"total": round(pnl_sl_perp + opt_at_sl, 4),
|
||||
"note": "与止损口径相近(期权用内在)",
|
||||
},
|
||||
],
|
||||
"summary": {
|
||||
"tp_total": round(tp_total, 4),
|
||||
"sl_total": round(sl_total_signed, 4),
|
||||
"premium_paid": round(float(premium_paid), 4),
|
||||
"hedge_ratio_at_sl": _hedge_ratio(opt_at_sl, pnl_sl_perp),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _hedge_ratio(opt_pnl: float, perp_pnl: float) -> Optional[float]:
|
||||
loss = abs(float(perp_pnl)) if float(perp_pnl) < 0 else 0.0
|
||||
if loss <= 1e-12:
|
||||
return None
|
||||
if float(opt_pnl) <= 0:
|
||||
return 0.0
|
||||
return round(float(opt_pnl) / loss * 100.0, 2)
|
||||
|
||||
|
||||
def build_options_options_preview(
|
||||
*,
|
||||
target_price: float | None = None,
|
||||
target_price_up: float | None = None,
|
||||
target_price_down: float | None = None,
|
||||
index_px: float,
|
||||
leg_a: dict[str, Any],
|
||||
leg_b: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
"""期期情景:上破/下破目标价 / 到期现价 / 最大保费损耗."""
|
||||
|
||||
def _leg_pnl(leg: dict[str, Any], spot: float) -> float:
|
||||
return option_expiry_pnl(
|
||||
opt_type=str(leg.get("opt_type") or ""),
|
||||
strike=float(leg["strike"]),
|
||||
spot=spot,
|
||||
sheets=float(leg.get("sheets") or 0),
|
||||
ct_mult=float(leg.get("ct_mult") or 0.01),
|
||||
premium_paid=float(leg.get("premium_paid") or 0),
|
||||
)
|
||||
|
||||
# 兼容旧单目标:若未传上下目标则用 target_price 填两边
|
||||
up = target_price_up if target_price_up is not None else target_price
|
||||
down = target_price_down if target_price_down is not None else target_price
|
||||
if up is None or down is None:
|
||||
raise ValueError("缺少上破/下破目标价")
|
||||
up_f = float(up)
|
||||
down_f = float(down)
|
||||
|
||||
prem = float(leg_a.get("premium_paid") or 0) + float(leg_b.get("premium_paid") or 0)
|
||||
a_up = _leg_pnl(leg_a, up_f)
|
||||
b_up = _leg_pnl(leg_b, up_f)
|
||||
at_up = a_up + b_up
|
||||
win_up = "a" if a_up >= b_up else "b"
|
||||
|
||||
a_dn = _leg_pnl(leg_a, down_f)
|
||||
b_dn = _leg_pnl(leg_b, down_f)
|
||||
at_dn = a_dn + b_dn
|
||||
win_dn = "a" if a_dn >= b_dn else "b"
|
||||
|
||||
a_flat = _leg_pnl(leg_a, index_px)
|
||||
b_flat = _leg_pnl(leg_b, index_px)
|
||||
flat_total = a_flat + b_flat
|
||||
expiry_loss = flat_total if flat_total <= 0 else flat_total
|
||||
|
||||
return {
|
||||
"plan_type": "options_options",
|
||||
"premium_paid": round(prem, 6),
|
||||
"target_price": up_f, # 兼容旧字段,取上破
|
||||
"target_price_up": up_f,
|
||||
"target_price_down": down_f,
|
||||
"winner_at_up": win_up,
|
||||
"winner_at_down": win_dn,
|
||||
"winner_at_target": win_up,
|
||||
"scenarios": [
|
||||
{
|
||||
"id": "target_up",
|
||||
"label": "上破目标",
|
||||
"spot": up_f,
|
||||
"leg_a_pnl": round(a_up, 4),
|
||||
"leg_b_pnl": round(b_up, 4),
|
||||
"total": round(at_up, 4),
|
||||
"note": f"盈利方≈腿{win_up.upper()}(可平);亏损方默认到期",
|
||||
},
|
||||
{
|
||||
"id": "target_down",
|
||||
"label": "下破目标",
|
||||
"spot": down_f,
|
||||
"leg_a_pnl": round(a_dn, 4),
|
||||
"leg_b_pnl": round(b_dn, 4),
|
||||
"total": round(at_dn, 4),
|
||||
"note": f"盈利方≈腿{win_dn.upper()}(可平);亏损方默认到期",
|
||||
},
|
||||
{
|
||||
"id": "expiry_flat",
|
||||
"label": "到期·现价(无突破)",
|
||||
"spot": index_px,
|
||||
"leg_a_pnl": round(a_flat, 4),
|
||||
"leg_b_pnl": round(b_flat, 4),
|
||||
"total": round(flat_total, 4),
|
||||
"note": "无盈利则记总亏损结束" if flat_total <= 0 else "到期仍可能有净值",
|
||||
},
|
||||
{
|
||||
"id": "max_premium_loss",
|
||||
"label": "最大保费损耗",
|
||||
"spot": None,
|
||||
"leg_a_pnl": round(-float(leg_a.get("premium_paid") or 0), 4),
|
||||
"leg_b_pnl": round(-float(leg_b.get("premium_paid") or 0), 4),
|
||||
"total": round(-prem, 4),
|
||||
"note": "双腿权利金全部损失",
|
||||
},
|
||||
],
|
||||
"summary": {
|
||||
"at_target_up_total": round(at_up, 4),
|
||||
"at_target_down_total": round(at_dn, 4),
|
||||
"at_target_total": round(at_up, 4),
|
||||
"expiry_flat_total": round(expiry_loss, 4),
|
||||
"premium_paid": round(prem, 6),
|
||||
"expiry_is_loss": flat_total <= 0,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def gate_status(
|
||||
*,
|
||||
hedge_enabled: bool,
|
||||
sizing_mode: str,
|
||||
plan_type: str,
|
||||
options_enabled: bool,
|
||||
live_order: bool = False,
|
||||
live_trading: bool = False,
|
||||
active_count: int = 0,
|
||||
max_active: int = 1,
|
||||
) -> dict[str, Any]:
|
||||
from lib.trade.position_sizing_lib import is_full_margin_mode
|
||||
|
||||
full = is_full_margin_mode(sizing_mode)
|
||||
pt = (plan_type or "").strip().lower()
|
||||
can_preview = True
|
||||
can_start = True
|
||||
reasons: list[str] = []
|
||||
if not hedge_enabled:
|
||||
can_start = False
|
||||
reasons.append("对冲计划未启用(HEDGE_PLAN_ENABLED)")
|
||||
if not options_enabled:
|
||||
can_preview = False
|
||||
can_start = False
|
||||
reasons.append("期权模块未启用")
|
||||
if not live_order:
|
||||
can_start = False
|
||||
reasons.append("未允许对冲真实下单(HEDGE_PLAN_LIVE_ORDER)")
|
||||
if active_count >= max(1, int(max_active or 1)):
|
||||
can_start = False
|
||||
reasons.append(f"活跃计划已达上限({max_active})")
|
||||
if pt == "perp_options":
|
||||
if not full:
|
||||
can_start = False
|
||||
reasons.append("永期开仓仅全仓模式可用(当前可测算)")
|
||||
if not live_trading:
|
||||
can_start = False
|
||||
reasons.append("未开启实盘(LIVE_TRADING_ENABLED)")
|
||||
elif pt == "options_options":
|
||||
pass
|
||||
else:
|
||||
can_start = False
|
||||
reasons.append("未知计划类型")
|
||||
if can_start:
|
||||
reasons = []
|
||||
return {
|
||||
"hedge_enabled": hedge_enabled,
|
||||
"options_enabled": options_enabled,
|
||||
"sizing_mode": sizing_mode,
|
||||
"is_full_margin": full,
|
||||
"plan_type": pt,
|
||||
"live_order": live_order,
|
||||
"live_trading": live_trading,
|
||||
"active_count": active_count,
|
||||
"max_active": max_active,
|
||||
"can_preview": can_preview,
|
||||
"can_start": can_start,
|
||||
"reasons": reasons,
|
||||
}
|
||||
@@ -0,0 +1,373 @@
|
||||
"""对冲计划 SQLite 表."""
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlite3
|
||||
from typing import Any, Optional
|
||||
|
||||
|
||||
def init_hedge_plan_tables(conn: sqlite3.Connection) -> None:
|
||||
conn.execute(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS hedge_plans (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
plan_type TEXT NOT NULL,
|
||||
status TEXT NOT NULL,
|
||||
underlying TEXT NOT NULL,
|
||||
direction TEXT,
|
||||
entry_mark REAL,
|
||||
tp REAL,
|
||||
sl REAL,
|
||||
target_price REAL,
|
||||
sizing_mode_at_open TEXT,
|
||||
perp_size REAL,
|
||||
margin REAL,
|
||||
leverage REAL,
|
||||
premium_total REAL,
|
||||
realized_pnl_perp REAL,
|
||||
realized_pnl_options REAL,
|
||||
realized_pnl_total REAL,
|
||||
stats_bucket TEXT,
|
||||
close_reason TEXT,
|
||||
wechat_start_sent INTEGER DEFAULT 0,
|
||||
wechat_end_sent INTEGER DEFAULT 0,
|
||||
note TEXT,
|
||||
preview_json TEXT,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
opened_at TIMESTAMP,
|
||||
closed_at TIMESTAMP
|
||||
)
|
||||
"""
|
||||
)
|
||||
conn.execute(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS hedge_plan_legs (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
plan_id INTEGER NOT NULL,
|
||||
leg_role TEXT NOT NULL,
|
||||
symbol TEXT,
|
||||
inst_id TEXT,
|
||||
opt_type TEXT,
|
||||
strike REAL,
|
||||
side TEXT,
|
||||
size REAL,
|
||||
avg_open REAL,
|
||||
premium REAL,
|
||||
status TEXT,
|
||||
linked_monitor_id INTEGER,
|
||||
options_trade_id INTEGER,
|
||||
exchange_ord_id TEXT,
|
||||
realized_pnl REAL,
|
||||
close_reason TEXT,
|
||||
opened_at TIMESTAMP,
|
||||
closed_at TIMESTAMP,
|
||||
FOREIGN KEY(plan_id) REFERENCES hedge_plans(id)
|
||||
)
|
||||
"""
|
||||
)
|
||||
conn.execute(
|
||||
"CREATE INDEX IF NOT EXISTS idx_hedge_plans_status ON hedge_plans(status)"
|
||||
)
|
||||
conn.execute(
|
||||
"CREATE INDEX IF NOT EXISTS idx_hedge_plan_legs_plan ON hedge_plan_legs(plan_id)"
|
||||
)
|
||||
_ensure_column(conn, "hedge_plans", "target_price_up", "REAL")
|
||||
_ensure_column(conn, "hedge_plans", "target_price_down", "REAL")
|
||||
|
||||
|
||||
def _ensure_column(conn: sqlite3.Connection, table: str, col: str, typedef: str) -> None:
|
||||
rows = conn.execute(f"PRAGMA table_info({table})").fetchall()
|
||||
names: set[str] = set()
|
||||
for r in rows:
|
||||
try:
|
||||
names.add(str(r["name"]))
|
||||
except (TypeError, KeyError, IndexError):
|
||||
names.add(str(r[1]))
|
||||
if col not in names:
|
||||
conn.execute(f"ALTER TABLE {table} ADD COLUMN {col} {typedef}")
|
||||
|
||||
|
||||
def count_active_plans(conn: sqlite3.Connection, plan_type: Optional[str] = None) -> int:
|
||||
if plan_type:
|
||||
row = conn.execute(
|
||||
"SELECT COUNT(1) AS c FROM hedge_plans WHERE status IN ('opening','active','partial') AND plan_type=?",
|
||||
(plan_type,),
|
||||
).fetchone()
|
||||
else:
|
||||
row = conn.execute(
|
||||
"SELECT COUNT(1) AS c FROM hedge_plans WHERE status IN ('opening','active','partial')"
|
||||
).fetchone()
|
||||
return int((row["c"] if row else 0) or 0)
|
||||
|
||||
|
||||
def insert_plan(conn: sqlite3.Connection, row: dict[str, Any]) -> int:
|
||||
cols = list(row.keys())
|
||||
placeholders = ",".join(["?"] * len(cols))
|
||||
conn.execute(
|
||||
f"INSERT INTO hedge_plans ({','.join(cols)}) VALUES ({placeholders})",
|
||||
[row[c] for c in cols],
|
||||
)
|
||||
return int(conn.execute("SELECT last_insert_rowid()").fetchone()[0])
|
||||
|
||||
|
||||
def insert_leg(conn: sqlite3.Connection, row: dict[str, Any]) -> int:
|
||||
cols = list(row.keys())
|
||||
placeholders = ",".join(["?"] * len(cols))
|
||||
conn.execute(
|
||||
f"INSERT INTO hedge_plan_legs ({','.join(cols)}) VALUES ({placeholders})",
|
||||
[row[c] for c in cols],
|
||||
)
|
||||
return int(conn.execute("SELECT last_insert_rowid()").fetchone()[0])
|
||||
|
||||
|
||||
def update_plan(conn: sqlite3.Connection, plan_id: int, **fields: Any) -> None:
|
||||
if not fields:
|
||||
return
|
||||
sets = ", ".join(f"{k}=?" for k in fields)
|
||||
conn.execute(f"UPDATE hedge_plans SET {sets} WHERE id=?", [*fields.values(), plan_id])
|
||||
|
||||
|
||||
def list_plans(
|
||||
conn: sqlite3.Connection,
|
||||
*,
|
||||
status: Optional[str] = None,
|
||||
plan_type: Optional[str] = None,
|
||||
underlying: Optional[str] = None,
|
||||
limit: int = 50,
|
||||
) -> list[dict[str, Any]]:
|
||||
wheres: list[str] = []
|
||||
args: list[Any] = []
|
||||
if status:
|
||||
wheres.append("status=?")
|
||||
args.append(status)
|
||||
if plan_type:
|
||||
wheres.append("plan_type=?")
|
||||
args.append(plan_type)
|
||||
if underlying:
|
||||
wheres.append("underlying=?")
|
||||
args.append(underlying)
|
||||
where = (" WHERE " + " AND ".join(wheres)) if wheres else ""
|
||||
rows = conn.execute(
|
||||
f"SELECT * FROM hedge_plans{where} ORDER BY id DESC LIMIT ?",
|
||||
[*args, int(limit)],
|
||||
).fetchall()
|
||||
return [dict(r) for r in rows]
|
||||
|
||||
|
||||
def get_plan(conn: sqlite3.Connection, plan_id: int) -> Optional[dict[str, Any]]:
|
||||
row = conn.execute("SELECT * FROM hedge_plans WHERE id=?", (plan_id,)).fetchone()
|
||||
return dict(row) if row else None
|
||||
|
||||
|
||||
def get_plan_legs(conn: sqlite3.Connection, plan_id: int) -> list[dict[str, Any]]:
|
||||
rows = conn.execute(
|
||||
"SELECT * FROM hedge_plan_legs WHERE plan_id=? ORDER BY id", (plan_id,)
|
||||
).fetchall()
|
||||
return [dict(r) for r in rows]
|
||||
|
||||
|
||||
def delete_plan(conn: sqlite3.Connection, plan_id: int) -> dict[str, Any]:
|
||||
"""删除已结束/失败/取消的计划及其腿;活跃计划拒绝删除."""
|
||||
plan = get_plan(conn, int(plan_id))
|
||||
if not plan:
|
||||
return {"ok": False, "msg": "计划不存在"}
|
||||
st = str(plan.get("status") or "")
|
||||
if st in ("opening", "active", "partial"):
|
||||
return {"ok": False, "msg": "进行中的计划不可删除,请先结束"}
|
||||
conn.execute("DELETE FROM hedge_plan_legs WHERE plan_id=?", (int(plan_id),))
|
||||
conn.execute("DELETE FROM hedge_plans WHERE id=?", (int(plan_id),))
|
||||
return {"ok": True, "deleted_id": int(plan_id)}
|
||||
|
||||
|
||||
def legs_contract_summary(legs: list[dict[str, Any]]) -> str:
|
||||
parts: list[str] = []
|
||||
for leg in legs:
|
||||
role = str(leg.get("leg_role") or "")
|
||||
if role == "perp":
|
||||
name = str(leg.get("symbol") or "永续")
|
||||
parts.append(f"永续 {name}")
|
||||
else:
|
||||
inst = str(leg.get("inst_id") or "")
|
||||
ot = str(leg.get("opt_type") or "").upper()
|
||||
strike = leg.get("strike")
|
||||
label = inst or (f"{ot}{strike}" if ot or strike is not None else role)
|
||||
parts.append(label)
|
||||
return " · ".join(parts) if parts else "—"
|
||||
|
||||
|
||||
def attach_legs_to_plans(conn: sqlite3.Connection, plans: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
out: list[dict[str, Any]] = []
|
||||
for p in plans:
|
||||
legs = get_plan_legs(conn, int(p["id"]))
|
||||
row = dict(p)
|
||||
row["legs"] = legs
|
||||
row["contracts_summary"] = legs_contract_summary(legs)
|
||||
out.append(row)
|
||||
return out
|
||||
|
||||
|
||||
def active_options_targets_by_inst(conn: sqlite3.Connection) -> dict[str, dict[str, Any]]:
|
||||
"""返回由进行中「期期对冲」托管的期权目标位,仅供期权页只读展示。
|
||||
|
||||
这些目标由 hedge_plan_monitor_lib 执行,绝不能写入 options_target_monitors,
|
||||
否则两套监控会同时尝试平掉同一条期权腿。
|
||||
"""
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT p.id AS plan_id, p.underlying, p.target_price_up, p.target_price_down,
|
||||
l.inst_id, l.opt_type
|
||||
FROM hedge_plans p
|
||||
JOIN hedge_plan_legs l ON l.plan_id = p.id
|
||||
WHERE p.plan_type = 'options_options'
|
||||
AND p.status IN ('opening', 'active', 'partial')
|
||||
AND l.status = 'open'
|
||||
AND l.inst_id IS NOT NULL
|
||||
AND l.inst_id != ''
|
||||
ORDER BY p.id DESC, l.id DESC
|
||||
"""
|
||||
).fetchall()
|
||||
out: dict[str, dict[str, Any]] = {}
|
||||
for raw in rows:
|
||||
row = dict(raw)
|
||||
inst_id = str(row.get("inst_id") or "")
|
||||
opt_type = str(row.get("opt_type") or "").upper()
|
||||
target = row.get("target_price_up") if opt_type == "C" else row.get("target_price_down")
|
||||
target_f = _sf(target)
|
||||
if not inst_id or target_f is None or target_f <= 0 or inst_id in out:
|
||||
continue
|
||||
out[inst_id] = {
|
||||
"plan_id": int(row["plan_id"]),
|
||||
"inst_id": inst_id,
|
||||
"underlying": row.get("underlying"),
|
||||
"opt_type": opt_type,
|
||||
"target_index": target_f,
|
||||
"plan_type": "options_options",
|
||||
"managed_by": "hedge_plan",
|
||||
}
|
||||
return out
|
||||
|
||||
|
||||
def _sf(v: Any) -> Optional[float]:
|
||||
try:
|
||||
if v is None or v == "":
|
||||
return None
|
||||
return float(v)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def _metrics_from_pnls(rows: list[dict[str, Any]]) -> dict[str, Any]:
|
||||
"""对一组已结束计划计算胜率/盈亏比/最大盈亏/最大回撤."""
|
||||
pnls: list[float] = []
|
||||
timed: list[tuple[str, float]] = []
|
||||
for r in rows:
|
||||
pnl = _sf(r.get("realized_pnl_total"))
|
||||
if pnl is None:
|
||||
continue
|
||||
pnls.append(pnl)
|
||||
t = str(r.get("closed_at") or r.get("opened_at") or r.get("created_at") or "")
|
||||
timed.append((t, pnl))
|
||||
n = len(pnls)
|
||||
if n == 0:
|
||||
return {
|
||||
"count": 0,
|
||||
"wins": 0,
|
||||
"losses": 0,
|
||||
"win_rate": None,
|
||||
"net_pnl": 0.0,
|
||||
"avg_pnl": None,
|
||||
"avg_premium": None,
|
||||
"profit_factor": None,
|
||||
"max_profit": None,
|
||||
"max_loss": None,
|
||||
"max_drawdown": None,
|
||||
}
|
||||
wins = [x for x in pnls if x > 0]
|
||||
losses = [x for x in pnls if x < 0]
|
||||
gross_win = sum(wins)
|
||||
gross_loss = abs(sum(losses))
|
||||
if gross_loss > 0:
|
||||
profit_factor = round(gross_win / gross_loss, 4)
|
||||
elif gross_win > 0:
|
||||
profit_factor = None # 全胜,标无限
|
||||
else:
|
||||
profit_factor = 0.0
|
||||
|
||||
timed.sort(key=lambda x: x[0] or "")
|
||||
cum = 0.0
|
||||
peak = 0.0
|
||||
mdd = 0.0
|
||||
for _, p in timed:
|
||||
cum += p
|
||||
if cum > peak:
|
||||
peak = cum
|
||||
dd = peak - cum
|
||||
if dd > mdd:
|
||||
mdd = dd
|
||||
|
||||
premiums = [_sf(r.get("premium_total")) for r in rows]
|
||||
premiums_f = [x for x in premiums if x is not None]
|
||||
return {
|
||||
"count": n,
|
||||
"wins": len(wins),
|
||||
"losses": len(losses),
|
||||
"win_rate": round(len(wins) / n, 4),
|
||||
"net_pnl": round(sum(pnls), 4),
|
||||
"avg_pnl": round(sum(pnls) / n, 4),
|
||||
"avg_premium": round(sum(premiums_f) / len(premiums_f), 4) if premiums_f else None,
|
||||
"profit_factor": profit_factor,
|
||||
"profit_factor_infinite": bool(gross_loss <= 0 and gross_win > 0),
|
||||
"max_profit": round(max(pnls), 4),
|
||||
"max_loss": round(min(pnls), 4),
|
||||
"max_drawdown": round(mdd, 4),
|
||||
}
|
||||
|
||||
|
||||
def stats_summary(conn: sqlite3.Connection) -> dict[str, Any]:
|
||||
reason_rows = conn.execute(
|
||||
"""
|
||||
SELECT plan_type, close_reason, COUNT(1) AS n,
|
||||
COALESCE(SUM(realized_pnl_total), 0) AS pnl
|
||||
FROM hedge_plans
|
||||
WHERE status='closed'
|
||||
GROUP BY plan_type, close_reason
|
||||
"""
|
||||
).fetchall()
|
||||
closed_rows = [
|
||||
dict(r)
|
||||
for r in conn.execute(
|
||||
"SELECT * FROM hedge_plans WHERE status='closed' ORDER BY COALESCE(closed_at, opened_at, created_at), id"
|
||||
).fetchall()
|
||||
]
|
||||
active = count_active_plans(conn)
|
||||
overall = _metrics_from_pnls(closed_rows)
|
||||
by_type = {
|
||||
"perp_options": _metrics_from_pnls(
|
||||
[r for r in closed_rows if r.get("plan_type") == "perp_options"]
|
||||
),
|
||||
"options_options": _metrics_from_pnls(
|
||||
[r for r in closed_rows if r.get("plan_type") == "options_options"]
|
||||
),
|
||||
}
|
||||
# 永期止盈/止损分桶
|
||||
po = [r for r in closed_rows if r.get("plan_type") == "perp_options"]
|
||||
by_type["perp_options"]["buckets"] = {
|
||||
"tp": _metrics_from_pnls([r for r in po if r.get("close_reason") == "perp_tp"]),
|
||||
"sl": _metrics_from_pnls([r for r in po if r.get("close_reason") == "perp_sl"]),
|
||||
}
|
||||
oo = [r for r in closed_rows if r.get("plan_type") == "options_options"]
|
||||
by_type["options_options"]["buckets"] = {
|
||||
"expiry_loss": _metrics_from_pnls(
|
||||
[r for r in oo if r.get("close_reason") == "oo_expiry_loss"]
|
||||
),
|
||||
"expiry_win": _metrics_from_pnls(
|
||||
[r for r in oo if r.get("close_reason") == "oo_expiry_win"]
|
||||
),
|
||||
}
|
||||
return {
|
||||
"active": active,
|
||||
"closed_count": overall["count"],
|
||||
"closed_pnl_total": overall["net_pnl"],
|
||||
"overall": overall,
|
||||
"by_type": by_type,
|
||||
"by_reason": [dict(r) for r in reason_rows],
|
||||
}
|
||||
@@ -0,0 +1,414 @@
|
||||
"""对冲计划监控:永期 TP/SL、期期目标价、到期结算与微信收口推送."""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, Optional
|
||||
|
||||
from lib.hedge_plan.hedge_plan_db import get_plan, get_plan_legs, list_plans, update_plan
|
||||
from lib.hedge_plan.hedge_plan_notify_lib import notify_hedge, notify_plan_end, build_hedge_alert_message
|
||||
from lib.hedge_plan.hedge_plan_orders_lib import _sell_option
|
||||
from lib.hedge_plan.hedge_plan_settle_lib import leg_is_expired, settle_option_leg_at_spot
|
||||
|
||||
|
||||
def _now() -> str:
|
||||
return datetime.now(timezone.utc).astimezone().strftime("%Y-%m-%d %H:%M:%S")
|
||||
|
||||
|
||||
def _env_bool(key: str, default: bool = False) -> bool:
|
||||
raw = (os.getenv(key) or "").strip().lower()
|
||||
if not raw:
|
||||
return default
|
||||
return raw in ("1", "true", "yes", "on")
|
||||
|
||||
|
||||
def _sf(v: Any) -> Optional[float]:
|
||||
try:
|
||||
if v is None or v == "":
|
||||
return None
|
||||
return float(v)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def _perp_live_contracts(cfg: dict[str, Any], symbol: str, direction: str) -> Optional[float]:
|
||||
fn = cfg.get("get_live_position_contracts")
|
||||
if not callable(fn):
|
||||
return None
|
||||
try:
|
||||
return fn(symbol, direction)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def _index_px(cfg: dict[str, Any], underlying: str) -> Optional[float]:
|
||||
ex = cfg.get("exchange_options")
|
||||
fn = cfg.get("fetch_index_price")
|
||||
if callable(fn) and ex is not None:
|
||||
try:
|
||||
return fn(ex, underlying)
|
||||
except Exception:
|
||||
return None
|
||||
# 无期权账户时回退永续 ticker
|
||||
ex_perp = cfg.get("exchange")
|
||||
if ex_perp is not None:
|
||||
try:
|
||||
base = (underlying or "ETH").upper()
|
||||
sym = f"{base}/USDT:USDT"
|
||||
t = ex_perp.fetch_ticker(sym)
|
||||
return _sf((t.get("info") or {}).get("markPx")) or _sf(t.get("last"))
|
||||
except Exception:
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def tick_active_plans(cfg: dict[str, Any]) -> dict[str, Any]:
|
||||
"""扫描 active 计划 + 止盈后遗留期权到期收口.返回处理摘要."""
|
||||
get_db = cfg.get("get_db")
|
||||
if not callable(get_db):
|
||||
return {"ok": False, "msg": "get_db missing"}
|
||||
conn = get_db()
|
||||
acted: list[dict[str, Any]] = []
|
||||
try:
|
||||
from lib.hedge_plan.hedge_plan_db import init_hedge_plan_tables
|
||||
|
||||
init_hedge_plan_tables(conn)
|
||||
plans = list_plans(conn, status="active", limit=40)
|
||||
for plan in plans:
|
||||
r = _tick_one(cfg, conn, plan)
|
||||
if r:
|
||||
acted.append(r)
|
||||
orphaned = _settle_orphaned_after_tp(cfg, conn)
|
||||
acted.extend(orphaned)
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
return {"ok": True, "acted": acted}
|
||||
|
||||
|
||||
def _notify_end_reload(cfg: dict[str, Any], conn: Any, plan_id: int) -> None:
|
||||
plan = get_plan(conn, int(plan_id))
|
||||
if plan:
|
||||
notify_plan_end(cfg, conn, plan)
|
||||
|
||||
|
||||
def _tick_one(cfg: dict[str, Any], conn: Any, plan: dict[str, Any]) -> Optional[dict[str, Any]]:
|
||||
pt = plan.get("plan_type")
|
||||
legs = get_plan_legs(conn, int(plan["id"]))
|
||||
if pt == "perp_options":
|
||||
# 先判断期权是否已过期且永续仍在(罕见);主路径仍是永续平仓侦测
|
||||
r = _tick_po(cfg, conn, plan, legs)
|
||||
return r
|
||||
if pt == "options_options":
|
||||
r = _tick_oo_expiry(cfg, conn, plan, legs)
|
||||
if r:
|
||||
return r
|
||||
return _tick_oo_target(cfg, conn, plan, legs)
|
||||
return None
|
||||
|
||||
|
||||
def _tick_po(cfg: dict[str, Any], conn: Any, plan: dict[str, Any], legs: list[dict[str, Any]]) -> Optional[dict[str, Any]]:
|
||||
perp = next((x for x in legs if x.get("leg_role") == "perp"), None)
|
||||
opt = next((x for x in legs if x.get("leg_role") == "option_hedge"), None)
|
||||
if not perp or perp.get("status") != "open":
|
||||
return None
|
||||
symbol = perp.get("symbol") or ""
|
||||
direction = (plan.get("direction") or "long").lower()
|
||||
live = _perp_live_contracts(cfg, symbol, direction)
|
||||
# 仍有仓 → 未触达交易所 TP/SL
|
||||
if live is not None and live > 0:
|
||||
return None
|
||||
# 仓已平:用标记/最新粗判 TP or SL
|
||||
entry = _sf(plan.get("entry_mark")) or _sf(perp.get("avg_open")) or 0
|
||||
tp = _sf(plan.get("tp"))
|
||||
sl = _sf(plan.get("sl"))
|
||||
mark = None
|
||||
ex = cfg.get("exchange")
|
||||
if ex is not None and symbol:
|
||||
try:
|
||||
t = ex.fetch_ticker(symbol)
|
||||
mark = _sf((t.get("info") or {}).get("markPx")) or _sf(t.get("last"))
|
||||
except Exception:
|
||||
mark = None
|
||||
reason = "perp_tp"
|
||||
if mark is not None and sl is not None and entry:
|
||||
if direction == "long" and mark <= sl:
|
||||
reason = "perp_sl"
|
||||
elif direction == "short" and mark >= sl:
|
||||
reason = "perp_sl"
|
||||
elif tp is not None:
|
||||
if direction == "long" and mark >= tp:
|
||||
reason = "perp_tp"
|
||||
elif direction == "short" and mark <= tp:
|
||||
reason = "perp_tp"
|
||||
premium = float(plan.get("premium_total") or 0)
|
||||
cs = float(cfg.get("default_contract_size") or 0.01)
|
||||
get_cs = cfg.get("get_contract_size")
|
||||
if callable(get_cs) and symbol:
|
||||
try:
|
||||
cs = float(get_cs(symbol) or cs)
|
||||
except Exception:
|
||||
pass
|
||||
size = float(perp.get("size") or 0)
|
||||
exit_px = mark or (tp if reason == "perp_tp" else sl) or entry
|
||||
coins = size * cs
|
||||
if direction == "short":
|
||||
perp_pnl = (entry - exit_px) * coins
|
||||
else:
|
||||
perp_pnl = (exit_px - entry) * coins
|
||||
|
||||
opt_pnl = -premium
|
||||
if reason == "perp_sl" and opt and _env_bool("HEDGE_PLAN_ON_PERP_SL_CLOSE_OPTIONS", True):
|
||||
close_r = _sell_option(
|
||||
cfg,
|
||||
inst_id=str(opt.get("inst_id") or ""),
|
||||
sheets=float(opt.get("size") or 1),
|
||||
)
|
||||
if not close_r.get("ok"):
|
||||
notify_hedge(
|
||||
cfg,
|
||||
build_hedge_alert_message(
|
||||
title="永续止损后期权强制平仓失败",
|
||||
plan_id=plan.get("id"),
|
||||
detail=str(close_r.get("msg") or close_r),
|
||||
),
|
||||
)
|
||||
if close_r.get("ok"):
|
||||
bid = _sf(close_r.get("bid"))
|
||||
ask_open = _sf(opt.get("avg_open"))
|
||||
if bid is not None and ask_open is not None:
|
||||
ct = float(opt.get("ct_mult") or 0.01)
|
||||
opt_pnl = (bid - ask_open) * float(opt.get("size") or 1) * ct
|
||||
else:
|
||||
opt_pnl = -premium
|
||||
conn.execute(
|
||||
"UPDATE hedge_plan_legs SET status=?, close_reason=?, closed_at=?, realized_pnl=? WHERE id=?",
|
||||
("closed", reason, _now(), opt_pnl, opt["id"]),
|
||||
)
|
||||
elif reason == "perp_tp" and opt:
|
||||
if _env_bool("HEDGE_PLAN_ON_PERP_TP_CLOSE_OPTIONS", False):
|
||||
close_r = _sell_option(cfg, inst_id=str(opt.get("inst_id") or ""), sheets=float(opt.get("size") or 1))
|
||||
if not close_r.get("ok"):
|
||||
notify_hedge(
|
||||
cfg,
|
||||
build_hedge_alert_message(
|
||||
title="永续止盈后期权平仓失败",
|
||||
plan_id=plan.get("id"),
|
||||
detail=str(close_r.get("msg") or close_r),
|
||||
),
|
||||
)
|
||||
conn.execute(
|
||||
"UPDATE hedge_plan_legs SET status=?, close_reason=?, closed_at=? WHERE id=?",
|
||||
("closed", reason, _now(), opt["id"]),
|
||||
)
|
||||
else:
|
||||
conn.execute(
|
||||
"UPDATE hedge_plan_legs SET status=?, close_reason=? WHERE id=?",
|
||||
("hold_to_expiry", "orphaned_after_tp", opt["id"]),
|
||||
)
|
||||
opt_pnl = -premium
|
||||
|
||||
if reason == "perp_tp":
|
||||
total = perp_pnl + opt_pnl
|
||||
else:
|
||||
total = opt_pnl + perp_pnl
|
||||
|
||||
conn.execute(
|
||||
"UPDATE hedge_plan_legs SET status=?, close_reason=?, closed_at=?, realized_pnl=? WHERE id=?",
|
||||
("closed", reason, _now(), perp_pnl, perp["id"]),
|
||||
)
|
||||
update_plan(
|
||||
conn,
|
||||
int(plan["id"]),
|
||||
status="closed",
|
||||
close_reason=reason,
|
||||
realized_pnl_perp=round(perp_pnl, 4),
|
||||
realized_pnl_options=round(opt_pnl, 4),
|
||||
realized_pnl_total=round(total, 4),
|
||||
stats_bucket="tp" if reason == "perp_tp" else "sl",
|
||||
closed_at=_now(),
|
||||
)
|
||||
_notify_end_reload(cfg, conn, int(plan["id"]))
|
||||
return {"plan_id": plan["id"], "close_reason": reason, "total": total}
|
||||
|
||||
|
||||
def _tick_oo_target(
|
||||
cfg: dict[str, Any], conn: Any, plan: dict[str, Any], legs: list[dict[str, Any]]
|
||||
) -> Optional[dict[str, Any]]:
|
||||
"""期期:触及上破或下破目标价时平盈利腿."""
|
||||
idx = _index_px(cfg, str(plan.get("underlying") or "ETH"))
|
||||
if idx is None:
|
||||
return None
|
||||
up = _sf(plan.get("target_price_up"))
|
||||
down = _sf(plan.get("target_price_down"))
|
||||
# 旧计划仅有单目标:两边都用它
|
||||
legacy = _sf(plan.get("target_price"))
|
||||
if up is None and legacy is not None:
|
||||
up = legacy
|
||||
if down is None and legacy is not None:
|
||||
down = legacy
|
||||
if up is None and down is None:
|
||||
return None
|
||||
|
||||
hit_side: Optional[str] = None
|
||||
# 上破:现价接近或超过上破目标
|
||||
if up is not None and idx >= up * 0.998:
|
||||
hit_side = "up"
|
||||
# 下破:现价接近或低于下破目标
|
||||
elif down is not None and idx <= down * 1.002:
|
||||
hit_side = "down"
|
||||
if not hit_side:
|
||||
return None
|
||||
if not _env_bool("HEDGE_PLAN_OO_CLOSE_WINNER_ONLY", True):
|
||||
return None
|
||||
open_legs = [x for x in legs if x.get("status") == "open" and str(x.get("leg_role") or "").startswith("option")]
|
||||
if len(open_legs) < 2:
|
||||
return None
|
||||
winners = []
|
||||
for leg in open_legs:
|
||||
strike = _sf(leg.get("strike")) or 0
|
||||
o = (leg.get("opt_type") or "").upper()
|
||||
intrinsic = max(0.0, idx - strike) if o == "C" else max(0.0, strike - idx)
|
||||
premium = float(leg.get("premium") or 0)
|
||||
pnl = intrinsic * float(leg.get("size") or 1) * float(leg.get("ct_mult") or 0.01) - premium
|
||||
winners.append((pnl, leg))
|
||||
winners.sort(key=lambda x: x[0], reverse=True)
|
||||
best_pnl, best = winners[0]
|
||||
if best_pnl <= 0:
|
||||
return None
|
||||
close_r = _sell_option(cfg, inst_id=str(best.get("inst_id") or ""), sheets=float(best.get("size") or 1))
|
||||
if not close_r.get("ok"):
|
||||
notify_hedge(
|
||||
cfg,
|
||||
build_hedge_alert_message(
|
||||
title="期期平盈利腿失败",
|
||||
plan_id=plan.get("id"),
|
||||
detail=str(close_r.get("msg") or close_r),
|
||||
),
|
||||
)
|
||||
return {"plan_id": plan["id"], "msg": "平盈利腿失败", "close": close_r}
|
||||
reason = "target_up_win_leg" if hit_side == "up" else "target_down_win_leg"
|
||||
conn.execute(
|
||||
"UPDATE hedge_plan_legs SET status=?, close_reason=?, closed_at=?, realized_pnl=? WHERE id=?",
|
||||
("closed", reason, _now(), best_pnl, best["id"]),
|
||||
)
|
||||
update_plan(conn, int(plan["id"]), close_reason=reason)
|
||||
mid = dict(plan)
|
||||
mid["close_reason"] = reason
|
||||
mid["status"] = "active"
|
||||
notify_plan_end(cfg, conn, mid)
|
||||
return {
|
||||
"plan_id": plan["id"],
|
||||
"close_reason": reason,
|
||||
"hit_side": hit_side,
|
||||
"closed_leg": best.get("id"),
|
||||
"index": idx,
|
||||
}
|
||||
|
||||
|
||||
def _tick_oo_expiry(
|
||||
cfg: dict[str, Any], conn: Any, plan: dict[str, Any], legs: list[dict[str, Any]]
|
||||
) -> Optional[dict[str, Any]]:
|
||||
"""期期:剩余期权腿全部到期 → 结算合计并结束计划."""
|
||||
pending = [
|
||||
x
|
||||
for x in legs
|
||||
if str(x.get("leg_role") or "").startswith("option")
|
||||
and str(x.get("status") or "") in ("open", "hold_to_expiry")
|
||||
]
|
||||
if not pending:
|
||||
# 若腿已全部 closed 但计划仍 active(异常残留)则用腿合计收口
|
||||
closed_opts = [
|
||||
x for x in legs if str(x.get("leg_role") or "").startswith("option") and x.get("status") == "closed"
|
||||
]
|
||||
if len(closed_opts) < 1:
|
||||
return None
|
||||
total_opts = sum(float(x.get("realized_pnl") or 0) for x in closed_opts)
|
||||
reason = "oo_expiry_loss" if total_opts <= 0 else "oo_expiry_win"
|
||||
update_plan(
|
||||
conn,
|
||||
int(plan["id"]),
|
||||
status="closed",
|
||||
close_reason=reason,
|
||||
realized_pnl_options=round(total_opts, 4),
|
||||
realized_pnl_total=round(total_opts, 4),
|
||||
stats_bucket=reason if reason == "oo_expiry_loss" else "oo_target",
|
||||
closed_at=_now(),
|
||||
)
|
||||
_notify_end_reload(cfg, conn, int(plan["id"]))
|
||||
return {"plan_id": plan["id"], "close_reason": reason, "total": total_opts}
|
||||
|
||||
if not all(leg_is_expired(x) for x in pending):
|
||||
return None
|
||||
|
||||
spot = _index_px(cfg, str(plan.get("underlying") or "ETH"))
|
||||
if spot is None:
|
||||
return None
|
||||
|
||||
settled_sum = 0.0
|
||||
for leg in pending:
|
||||
pnl = settle_option_leg_at_spot(leg, float(spot))
|
||||
settled_sum += pnl
|
||||
conn.execute(
|
||||
"UPDATE hedge_plan_legs SET status=?, close_reason=?, closed_at=?, realized_pnl=? WHERE id=?",
|
||||
("closed", "expiry", _now(), round(pnl, 4), leg["id"]),
|
||||
)
|
||||
|
||||
already = sum(
|
||||
float(x.get("realized_pnl") or 0)
|
||||
for x in legs
|
||||
if str(x.get("leg_role") or "").startswith("option") and x.get("status") == "closed"
|
||||
)
|
||||
total = already + settled_sum
|
||||
reason = "oo_expiry_loss" if total <= 0 else "oo_expiry_win"
|
||||
bucket = "oo_expiry_loss" if reason == "oo_expiry_loss" else "oo_target"
|
||||
update_plan(
|
||||
conn,
|
||||
int(plan["id"]),
|
||||
status="closed",
|
||||
close_reason=reason,
|
||||
realized_pnl_options=round(total, 4),
|
||||
realized_pnl_total=round(total, 4),
|
||||
stats_bucket=bucket,
|
||||
closed_at=_now(),
|
||||
)
|
||||
_notify_end_reload(cfg, conn, int(plan["id"]))
|
||||
return {"plan_id": plan["id"], "close_reason": reason, "total": total, "spot": spot}
|
||||
|
||||
|
||||
def _settle_orphaned_after_tp(cfg: dict[str, Any], conn: Any) -> list[dict[str, Any]]:
|
||||
"""永期止盈后 hold_to_expiry 期权到期:只更新腿,不回写计划合计."""
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT l.id AS leg_id, l.plan_id, l.inst_id, l.opt_type, l.strike, l.size, l.premium, l.status,
|
||||
p.underlying, p.status AS plan_status
|
||||
FROM hedge_plan_legs l
|
||||
JOIN hedge_plans p ON p.id = l.plan_id
|
||||
WHERE l.status = 'hold_to_expiry' AND l.close_reason = 'orphaned_after_tp'
|
||||
LIMIT 40
|
||||
"""
|
||||
).fetchall()
|
||||
acted: list[dict[str, Any]] = []
|
||||
for row in rows:
|
||||
leg = dict(row)
|
||||
if not leg_is_expired(leg):
|
||||
continue
|
||||
spot = _index_px(cfg, str(leg.get("underlying") or "ETH"))
|
||||
if spot is None:
|
||||
continue
|
||||
pnl = settle_option_leg_at_spot(leg, float(spot))
|
||||
conn.execute(
|
||||
"UPDATE hedge_plan_legs SET status=?, close_reason=?, closed_at=?, realized_pnl=? WHERE id=?",
|
||||
("closed", "expiry", _now(), round(pnl, 4), leg["leg_id"]),
|
||||
)
|
||||
# 故意不 UPDATE hedge_plans.realized_pnl_*
|
||||
acted.append(
|
||||
{
|
||||
"plan_id": leg["plan_id"],
|
||||
"close_reason": "orphaned_option_expiry",
|
||||
"leg_id": leg["leg_id"],
|
||||
"leg_pnl": round(pnl, 4),
|
||||
"note": "不回写计划合计",
|
||||
}
|
||||
)
|
||||
return acted
|
||||
@@ -0,0 +1,186 @@
|
||||
"""对冲计划企业微信推送(起止必发,幂等落库标记)."""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Callable, Optional
|
||||
|
||||
from lib.hedge_plan.hedge_plan_db import update_plan
|
||||
|
||||
|
||||
def _fmt(v: Any, d: int = 2) -> str:
|
||||
try:
|
||||
if v is None or v == "":
|
||||
return "—"
|
||||
return f"{float(v):.{d}f}"
|
||||
except (TypeError, ValueError):
|
||||
return str(v)
|
||||
|
||||
|
||||
def _type_label(plan_type: str) -> str:
|
||||
return "永期对冲" if (plan_type or "") == "perp_options" else "期期对冲"
|
||||
|
||||
|
||||
def _dir_label(direction: str) -> str:
|
||||
d = (direction or "").lower()
|
||||
if d == "long":
|
||||
return "做多"
|
||||
if d == "short":
|
||||
return "做空"
|
||||
return "—"
|
||||
|
||||
|
||||
def build_hedge_start_message(plan: dict[str, Any], *, legs: Optional[list[dict[str, Any]]] = None) -> str:
|
||||
pt = plan.get("plan_type") or ""
|
||||
lines = [
|
||||
f"🟢 对冲计划启动 #{plan.get('id')}",
|
||||
f"📌 类型:{_type_label(pt)}",
|
||||
f"🪙 标的:{plan.get('underlying') or '—'}",
|
||||
]
|
||||
if pt == "perp_options":
|
||||
lines.extend(
|
||||
[
|
||||
f"📈 方向:{_dir_label(plan.get('direction') or '')}",
|
||||
f"💵 开仓参考:{_fmt(plan.get('entry_mark'))}",
|
||||
f"🎯 止盈:{_fmt(plan.get('tp'))}|止损:{_fmt(plan.get('sl'))}",
|
||||
f"📦 永续张数:{_fmt(plan.get('perp_size'), 4)}|杠杆:{_fmt(plan.get('leverage'), 0)}x",
|
||||
f"💎 期权保费合计:{_fmt(plan.get('premium_total'), 4)} USDC",
|
||||
]
|
||||
)
|
||||
else:
|
||||
lines.extend(
|
||||
[
|
||||
f"🎯 上破:{_fmt(plan.get('target_price_up') or plan.get('target_price'))}"
|
||||
f"|下破:{_fmt(plan.get('target_price_down') or plan.get('target_price'))}",
|
||||
f"💎 期权保费合计:{_fmt(plan.get('premium_total'), 4)} USDC",
|
||||
]
|
||||
)
|
||||
if legs:
|
||||
for leg in legs:
|
||||
role = leg.get("leg_role") or ""
|
||||
if role == "perp":
|
||||
lines.append(f"· 永续腿 {leg.get('symbol') or ''} ×{_fmt(leg.get('size'), 4)}")
|
||||
else:
|
||||
lines.append(
|
||||
f"· {role} {(leg.get('opt_type') or '')} K{_fmt(leg.get('strike'), 0)} "
|
||||
f"×{_fmt(leg.get('size'), 0)}张 {leg.get('inst_id') or ''}"
|
||||
)
|
||||
lines.append("📎 独立模块推送,不进普通交易复盘")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def build_hedge_end_message(plan: dict[str, Any]) -> str:
|
||||
reason = plan.get("close_reason") or "—"
|
||||
total = plan.get("realized_pnl_total")
|
||||
try:
|
||||
tv = float(total) if total is not None else None
|
||||
except (TypeError, ValueError):
|
||||
tv = None
|
||||
head = "🔴" if (tv is not None and tv < 0) else "🟢"
|
||||
reason_map = {
|
||||
"perp_tp": "永续止盈(期权默认不平)",
|
||||
"perp_sl": "永续止损(期权强制平)",
|
||||
"target_win_leg": "期期已平盈利腿(中间态)",
|
||||
"target_up_win_leg": "期期上破·已平盈利腿",
|
||||
"target_down_win_leg": "期期下破·已平盈利腿",
|
||||
"oo_expiry_loss": "期期到期无盈利·总亏损",
|
||||
"oo_expiry_win": "期期到期仍盈利",
|
||||
"expiry": "到期收口",
|
||||
"manual": "人工结束",
|
||||
"partial_fail": "半腿失败收尾",
|
||||
"cancelled": "已取消",
|
||||
}
|
||||
lines = [
|
||||
f"{head} 对冲计划结束 #{plan.get('id')}",
|
||||
f"📌 类型:{_type_label(plan.get('plan_type') or '')}",
|
||||
f"🪙 标的:{plan.get('underlying') or '—'}",
|
||||
f"📎 原因:{reason_map.get(reason, reason)}",
|
||||
f"💰 合计≈U:{_fmt(total)}",
|
||||
f"· 永续分项:{_fmt(plan.get('realized_pnl_perp'))} USDT",
|
||||
f"· 期权分项:{_fmt(plan.get('realized_pnl_options'))} USDC(≈U 1:1)",
|
||||
f"⏱ 开仓:{plan.get('opened_at') or '—'}|结束:{plan.get('closed_at') or '—'}",
|
||||
]
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def build_hedge_alert_message(
|
||||
*,
|
||||
title: str,
|
||||
plan_id: Any = None,
|
||||
detail: str = "",
|
||||
) -> str:
|
||||
lines = [f"⚠️ 对冲计划告警{(' #' + str(plan_id)) if plan_id else ''}", f"📌 {title}"]
|
||||
if detail:
|
||||
lines.append(str(detail)[:800])
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def notify_hedge(
|
||||
cfg: dict[str, Any],
|
||||
content: str,
|
||||
) -> bool:
|
||||
send: Optional[Callable[[str], Any]] = cfg.get("send_wechat")
|
||||
if not callable(send):
|
||||
return False
|
||||
try:
|
||||
send(content)
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def notify_plan_start(
|
||||
cfg: dict[str, Any],
|
||||
conn: Any,
|
||||
plan: dict[str, Any],
|
||||
legs: Optional[list[dict[str, Any]]] = None,
|
||||
) -> bool:
|
||||
if int(plan.get("wechat_start_sent") or 0):
|
||||
return False
|
||||
ok = notify_hedge(cfg, build_hedge_start_message(plan, legs=legs))
|
||||
if ok and plan.get("id") is not None:
|
||||
update_plan(conn, int(plan["id"]), wechat_start_sent=1)
|
||||
plan["wechat_start_sent"] = 1
|
||||
return ok
|
||||
|
||||
|
||||
def notify_plan_end(cfg: dict[str, Any], conn: Any, plan: dict[str, Any]) -> bool:
|
||||
if int(plan.get("wechat_end_sent") or 0):
|
||||
return False
|
||||
# 中间态 target_win_leg 不算正式结束推送(用告警)
|
||||
if (plan.get("close_reason") or "") in (
|
||||
"target_win_leg",
|
||||
"target_up_win_leg",
|
||||
"target_down_win_leg",
|
||||
) and (plan.get("status") or "") != "closed":
|
||||
side = "上破" if "up" in str(plan.get("close_reason")) else (
|
||||
"下破" if "down" in str(plan.get("close_reason")) else "目标价"
|
||||
)
|
||||
notify_hedge(
|
||||
cfg,
|
||||
build_hedge_alert_message(
|
||||
title=f"期期{side}已平盈利腿,亏损腿继续持有至到期",
|
||||
plan_id=plan.get("id"),
|
||||
detail=(
|
||||
f"上破 {_fmt(plan.get('target_price_up') or plan.get('target_price'))}"
|
||||
f"|下破 {_fmt(plan.get('target_price_down') or plan.get('target_price'))}"
|
||||
),
|
||||
),
|
||||
)
|
||||
return True
|
||||
ok = notify_hedge(cfg, build_hedge_end_message(plan))
|
||||
if ok and plan.get("id") is not None:
|
||||
update_plan(conn, int(plan["id"]), wechat_end_sent=1)
|
||||
plan["wechat_end_sent"] = 1
|
||||
return ok
|
||||
|
||||
|
||||
def notify_partial_fail(cfg: dict[str, Any], *, plan_type: str, msg: str, results: Any = None) -> bool:
|
||||
detail = msg
|
||||
if results:
|
||||
try:
|
||||
detail = f"{msg}\n路径结果:{results}"[:800]
|
||||
except Exception:
|
||||
pass
|
||||
return notify_hedge(
|
||||
cfg,
|
||||
build_hedge_alert_message(title=f"{_type_label(plan_type)}半腿失败", detail=detail),
|
||||
)
|
||||
@@ -0,0 +1,429 @@
|
||||
"""对冲计划开仓/平仓编排(可 dry_run 校验下单路径)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, Callable, Optional
|
||||
|
||||
|
||||
def _now() -> str:
|
||||
return datetime.now(timezone.utc).astimezone().strftime("%Y-%m-%d %H:%M:%S")
|
||||
|
||||
|
||||
def _env_bool(key: str, default: bool = False) -> bool:
|
||||
raw = (os.getenv(key) or "").strip().lower()
|
||||
if not raw:
|
||||
return default
|
||||
return raw in ("1", "true", "yes", "on")
|
||||
|
||||
|
||||
def open_order_mode() -> str:
|
||||
v = (os.getenv("HEDGE_PLAN_OPEN_ORDER") or "options_first").strip().lower()
|
||||
return v if v in ("options_first", "perp_first") else "options_first"
|
||||
|
||||
|
||||
def build_po_path_plan(body: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
"""永期下单路径清单(不交易)."""
|
||||
mode = open_order_mode()
|
||||
opt = {
|
||||
"step": "options_buy_limit",
|
||||
"account": "options",
|
||||
"inst_id": body.get("opt_inst_id"),
|
||||
"sheets": float(body.get("sheets") or 1),
|
||||
"side": "buy",
|
||||
"price_hint": "ask",
|
||||
}
|
||||
perp = {
|
||||
"step": "perp_market_open",
|
||||
"account": "swap",
|
||||
"symbol": body.get("exchange_symbol"),
|
||||
"direction": body.get("direction") or "long",
|
||||
"contracts": float(body.get("contracts") or 0),
|
||||
"tp": body.get("tp"),
|
||||
"sl": body.get("sl"),
|
||||
"attach_tpsl": True,
|
||||
}
|
||||
return [opt, perp] if mode == "options_first" else [perp, opt]
|
||||
|
||||
|
||||
def build_oo_path_plan(body: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
return [
|
||||
{
|
||||
"step": "options_buy_limit",
|
||||
"account": "options",
|
||||
"leg": "a",
|
||||
"inst_id": (body.get("leg_a") or {}).get("inst_id"),
|
||||
"sheets": float((body.get("leg_a") or {}).get("sheets") or 1),
|
||||
"side": "buy",
|
||||
"price_hint": "ask",
|
||||
},
|
||||
{
|
||||
"step": "options_buy_limit",
|
||||
"account": "options",
|
||||
"leg": "b",
|
||||
"inst_id": (body.get("leg_b") or {}).get("inst_id"),
|
||||
"sheets": float((body.get("leg_b") or {}).get("sheets") or 1),
|
||||
"side": "buy",
|
||||
"price_hint": "ask",
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
def _buy_option(
|
||||
cfg: dict[str, Any],
|
||||
*,
|
||||
inst_id: str,
|
||||
sheets: float,
|
||||
dry_run: bool,
|
||||
) -> dict[str, Any]:
|
||||
from lib.exchange.okx_options_lib import (
|
||||
cap_option_buy_sheets_to_ask_depth,
|
||||
option_buy_liquidity_ok,
|
||||
)
|
||||
|
||||
ex = cfg.get("exchange_options")
|
||||
quote_fn = cfg.get("quote_option_contract")
|
||||
place_fn = cfg.get("place_option_limit_order")
|
||||
td_buy = cfg.get("td_mode_for_option_buy")
|
||||
if not inst_id:
|
||||
return {"ok": False, "msg": "缺少期权合约"}
|
||||
if not callable(quote_fn) or ex is None:
|
||||
return {"ok": False, "msg": "期权报价能力未就绪"}
|
||||
q = quote_fn(ex, inst_id)
|
||||
if not q.get("ok"):
|
||||
return {"ok": False, "msg": q.get("msg") or "期权报价失败", "quote": q}
|
||||
ask = q.get("ask")
|
||||
ask_sz = q.get("ask_sz")
|
||||
can_open, block_msg = option_buy_liquidity_ok(ask, ask_sz)
|
||||
if not can_open:
|
||||
return {
|
||||
"ok": False,
|
||||
"msg": block_msg or q.get("open_block_msg") or "暂无卖一深度,无法买入",
|
||||
"quote": q,
|
||||
"mark": q.get("mark"),
|
||||
"ref_ask": q.get("ref_ask"),
|
||||
"can_open": False,
|
||||
}
|
||||
sheets_i = max(1, int(round(float(sheets))))
|
||||
capped, cap_msg = cap_option_buy_sheets_to_ask_depth(sheets_i, ask_sz, min_sz=1)
|
||||
if capped is None:
|
||||
return {"ok": False, "msg": cap_msg or "卖一深度不足,无法买入", "quote": q}
|
||||
sheets_i = capped
|
||||
ct_mult = float(q.get("ct_mult") or 0.01)
|
||||
premium = float(ask) * sheets_i * ct_mult
|
||||
if dry_run:
|
||||
return {
|
||||
"ok": True,
|
||||
"dry_run": True,
|
||||
"inst_id": inst_id,
|
||||
"sheets": sheets_i,
|
||||
"ask": float(ask),
|
||||
"ask_sz": float(ask_sz),
|
||||
"premium": premium,
|
||||
"ct_mult": ct_mult,
|
||||
"tick_sz": q.get("tick_sz"),
|
||||
"meta": q.get("meta") or {},
|
||||
"strike": q.get("strike"),
|
||||
"exp_time": q.get("exp_time"),
|
||||
"opt_type": (q.get("meta") or {}).get("optType") or q.get("opt_type"),
|
||||
"can_open": True,
|
||||
}
|
||||
if not callable(place_fn):
|
||||
return {"ok": False, "msg": "期权限价下单未注入"}
|
||||
td = "isolated"
|
||||
if callable(td_buy):
|
||||
td = td_buy(cfg.get("options_td_mode") or "isolated")
|
||||
order = place_fn(
|
||||
ex,
|
||||
inst_id=inst_id,
|
||||
side="buy",
|
||||
sheets=sheets_i,
|
||||
price=float(ask),
|
||||
td_mode=td,
|
||||
tick_sz=q.get("tick_sz"),
|
||||
)
|
||||
if not order.get("ok"):
|
||||
return order
|
||||
return {
|
||||
"ok": True,
|
||||
"inst_id": inst_id,
|
||||
"sheets": sheets_i,
|
||||
"ask": float(ask),
|
||||
"ask_sz": float(ask_sz),
|
||||
"premium": premium,
|
||||
"ct_mult": ct_mult,
|
||||
"tick_sz": q.get("tick_sz"),
|
||||
"meta": q.get("meta") or {},
|
||||
"strike": q.get("strike"),
|
||||
"exp_time": q.get("exp_time"),
|
||||
"opt_type": (q.get("meta") or {}).get("optType") or q.get("opt_type"),
|
||||
"exchange_ord_id": (order.get("data") or {}).get("ordId"),
|
||||
"order": order,
|
||||
"can_open": True,
|
||||
}
|
||||
|
||||
|
||||
def _open_perp(
|
||||
cfg: dict[str, Any],
|
||||
*,
|
||||
symbol: str,
|
||||
direction: str,
|
||||
contracts: float,
|
||||
leverage: int,
|
||||
tp: float,
|
||||
sl: float,
|
||||
dry_run: bool,
|
||||
) -> dict[str, Any]:
|
||||
if not symbol or contracts <= 0:
|
||||
return {"ok": False, "msg": "永续符号或张数无效"}
|
||||
amount = float(contracts)
|
||||
to_prec = cfg.get("amount_to_precision")
|
||||
ex = cfg.get("exchange")
|
||||
if callable(to_prec) and ex is not None:
|
||||
try:
|
||||
amount = float(to_prec(symbol, amount))
|
||||
except Exception:
|
||||
pass
|
||||
if amount <= 0:
|
||||
return {"ok": False, "msg": "张数经精度舍入后为 0"}
|
||||
if dry_run:
|
||||
return {
|
||||
"ok": True,
|
||||
"dry_run": True,
|
||||
"symbol": symbol,
|
||||
"direction": direction,
|
||||
"contracts": amount,
|
||||
"leverage": leverage,
|
||||
"tp": tp,
|
||||
"sl": sl,
|
||||
}
|
||||
ensure = cfg.get("ensure_okx_live_ready")
|
||||
if callable(ensure):
|
||||
ok, msg = ensure()
|
||||
if not ok:
|
||||
return {"ok": False, "msg": msg or "实盘未就绪"}
|
||||
place = cfg.get("place_exchange_order")
|
||||
if not callable(place):
|
||||
return {"ok": False, "msg": "永续下单函数未注入"}
|
||||
try:
|
||||
order = place(symbol, direction, amount, leverage, stop_loss=sl, take_profit=tp)
|
||||
except Exception as e:
|
||||
return {"ok": False, "msg": f"永续开仓失败: {e}"}
|
||||
return {
|
||||
"ok": True,
|
||||
"symbol": symbol,
|
||||
"direction": direction,
|
||||
"contracts": amount,
|
||||
"leverage": leverage,
|
||||
"tp": tp,
|
||||
"sl": sl,
|
||||
"order": order,
|
||||
"exchange_ord_id": str((order or {}).get("id") or (order or {}).get("info", {}).get("ordId") or ""),
|
||||
}
|
||||
|
||||
|
||||
def _sell_option(
|
||||
cfg: dict[str, Any],
|
||||
*,
|
||||
inst_id: str,
|
||||
sheets: float,
|
||||
dry_run: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
ex = cfg.get("exchange_options")
|
||||
quote_fn = cfg.get("quote_option_contract")
|
||||
place_fn = cfg.get("place_option_limit_order")
|
||||
if not callable(quote_fn) or ex is None:
|
||||
return {"ok": False, "msg": "期权报价能力未就绪"}
|
||||
q = quote_fn(ex, inst_id)
|
||||
bid = q.get("bid") if q.get("ok") else None
|
||||
if bid is None or float(bid) <= 0:
|
||||
return {"ok": False, "msg": "暂无买一价,无法平期权"}
|
||||
sheets_i = max(1, int(round(float(sheets))))
|
||||
if dry_run:
|
||||
return {"ok": True, "dry_run": True, "inst_id": inst_id, "sheets": sheets_i, "bid": float(bid)}
|
||||
if not callable(place_fn):
|
||||
return {"ok": False, "msg": "期权平仓未注入"}
|
||||
order = place_fn(
|
||||
ex,
|
||||
inst_id=inst_id,
|
||||
side="sell",
|
||||
sheets=sheets_i,
|
||||
price=float(bid),
|
||||
td_mode="isolated",
|
||||
tick_sz=q.get("tick_sz"),
|
||||
reduce_only=True,
|
||||
)
|
||||
return order if order.get("ok") else order
|
||||
|
||||
|
||||
def execute_perp_options_start(
|
||||
cfg: dict[str, Any],
|
||||
body: dict[str, Any],
|
||||
*,
|
||||
dry_run: bool = False,
|
||||
persist: Optional[Callable[..., Any]] = None,
|
||||
) -> dict[str, Any]:
|
||||
path = build_po_path_plan(body)
|
||||
results: list[dict[str, Any]] = []
|
||||
opt_res: Optional[dict[str, Any]] = None
|
||||
perp_res: Optional[dict[str, Any]] = None
|
||||
for step in path:
|
||||
if step["step"] == "options_buy_limit":
|
||||
opt_res = _buy_option(
|
||||
cfg,
|
||||
inst_id=str(body.get("opt_inst_id") or ""),
|
||||
sheets=float(body.get("sheets") or 1),
|
||||
dry_run=dry_run,
|
||||
)
|
||||
results.append({"step": step["step"], **opt_res})
|
||||
if not opt_res.get("ok"):
|
||||
return {"ok": False, "msg": opt_res.get("msg") or "期权开仓失败", "path": path, "results": results}
|
||||
else:
|
||||
perp_res = _open_perp(
|
||||
cfg,
|
||||
symbol=str(body.get("exchange_symbol") or ""),
|
||||
direction=str(body.get("direction") or "long"),
|
||||
contracts=float(body.get("contracts") or 0),
|
||||
leverage=int(body.get("leverage") or 10),
|
||||
tp=float(body["tp"]),
|
||||
sl=float(body["sl"]),
|
||||
dry_run=dry_run,
|
||||
)
|
||||
results.append({"step": step["step"], **perp_res})
|
||||
if not perp_res.get("ok"):
|
||||
# 半腿补偿:期权已成 + 配置允许则平期权
|
||||
if opt_res and opt_res.get("ok") and not dry_run and _env_bool("HEDGE_PLAN_PARTIAL_AUTO_CLOSE_OPTION", True):
|
||||
close_r = _sell_option(
|
||||
cfg,
|
||||
inst_id=str(opt_res.get("inst_id") or body.get("opt_inst_id") or ""),
|
||||
sheets=float(opt_res.get("sheets") or body.get("sheets") or 1),
|
||||
)
|
||||
results.append({"step": "options_auto_close_on_perp_fail", **close_r})
|
||||
msg = perp_res.get("msg") or "永续开仓失败"
|
||||
if not dry_run:
|
||||
try:
|
||||
from lib.hedge_plan.hedge_plan_notify_lib import notify_partial_fail
|
||||
|
||||
notify_partial_fail(
|
||||
cfg, plan_type="perp_options", msg=msg, results=results
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return {
|
||||
"ok": False,
|
||||
"msg": msg,
|
||||
"path": path,
|
||||
"results": results,
|
||||
"partial": True,
|
||||
}
|
||||
|
||||
out = {
|
||||
"ok": True,
|
||||
"dry_run": dry_run,
|
||||
"plan_type": "perp_options",
|
||||
"path": path,
|
||||
"results": results,
|
||||
"option": opt_res,
|
||||
"perp": perp_res,
|
||||
"opened_at": _now(),
|
||||
}
|
||||
if persist and not dry_run:
|
||||
out["plan_id"] = persist(out, body)
|
||||
return out
|
||||
|
||||
|
||||
def execute_options_options_start(
|
||||
cfg: dict[str, Any],
|
||||
body: dict[str, Any],
|
||||
*,
|
||||
dry_run: bool = False,
|
||||
persist: Optional[Callable[..., Any]] = None,
|
||||
) -> dict[str, Any]:
|
||||
path = build_oo_path_plan(body)
|
||||
results: list[dict[str, Any]] = []
|
||||
leg_a = body.get("leg_a") or {}
|
||||
leg_b = body.get("leg_b") or {}
|
||||
a_res = _buy_option(cfg, inst_id=str(leg_a.get("inst_id") or ""), sheets=float(leg_a.get("sheets") or 1), dry_run=dry_run)
|
||||
results.append({"step": "options_buy_limit", "leg": "a", **a_res})
|
||||
if not a_res.get("ok"):
|
||||
return {"ok": False, "msg": a_res.get("msg") or "腿A开仓失败", "path": path, "results": results}
|
||||
b_res = _buy_option(cfg, inst_id=str(leg_b.get("inst_id") or ""), sheets=float(leg_b.get("sheets") or 1), dry_run=dry_run)
|
||||
results.append({"step": "options_buy_limit", "leg": "b", **b_res})
|
||||
if not b_res.get("ok"):
|
||||
if not dry_run and _env_bool("HEDGE_PLAN_PARTIAL_AUTO_CLOSE_OPTION", True):
|
||||
close_r = _sell_option(cfg, inst_id=str(a_res.get("inst_id") or ""), sheets=float(a_res.get("sheets") or 1))
|
||||
results.append({"step": "options_auto_close_leg_a", **close_r})
|
||||
msg = b_res.get("msg") or "腿B开仓失败"
|
||||
if not dry_run:
|
||||
try:
|
||||
from lib.hedge_plan.hedge_plan_notify_lib import notify_partial_fail
|
||||
|
||||
notify_partial_fail(cfg, plan_type="options_options", msg=msg, results=results)
|
||||
except Exception:
|
||||
pass
|
||||
return {
|
||||
"ok": False,
|
||||
"msg": msg,
|
||||
"path": path,
|
||||
"results": results,
|
||||
"partial": True,
|
||||
}
|
||||
out = {
|
||||
"ok": True,
|
||||
"dry_run": dry_run,
|
||||
"plan_type": "options_options",
|
||||
"path": path,
|
||||
"results": results,
|
||||
"leg_a": a_res,
|
||||
"leg_b": b_res,
|
||||
"opened_at": _now(),
|
||||
}
|
||||
if persist and not dry_run:
|
||||
out["plan_id"] = persist(out, body)
|
||||
return out
|
||||
|
||||
|
||||
def validate_start_body(plan_type: str, body: dict[str, Any]) -> Optional[str]:
|
||||
pt = (plan_type or "").strip().lower()
|
||||
if pt == "perp_options":
|
||||
need = ("direction", "entry", "tp", "sl", "contracts", "opt_inst_id", "sheets", "exchange_symbol")
|
||||
for k in need:
|
||||
if body.get(k) in (None, ""):
|
||||
return f"缺少字段: {k}"
|
||||
try:
|
||||
if float(body["contracts"]) <= 0 or float(body["sheets"]) <= 0:
|
||||
return "张数必须大于 0"
|
||||
if float(body["tp"]) <= 0 or float(body["sl"]) <= 0:
|
||||
return "止盈/止损无效"
|
||||
except (TypeError, ValueError):
|
||||
return "数值字段无效"
|
||||
return None
|
||||
if pt == "options_options":
|
||||
a = body.get("leg_a") or {}
|
||||
b = body.get("leg_b") or {}
|
||||
if not a.get("inst_id") or not b.get("inst_id"):
|
||||
return "请选用两条期权腿"
|
||||
up = body.get("target_price_up")
|
||||
down = body.get("target_price_down")
|
||||
legacy = body.get("target_price")
|
||||
if up in (None, "") and legacy not in (None, ""):
|
||||
up = legacy
|
||||
if down in (None, "") and legacy not in (None, ""):
|
||||
down = legacy
|
||||
if up in (None, "") or down in (None, ""):
|
||||
return "请填写上破与下破目标价"
|
||||
try:
|
||||
if float(up) <= float(down):
|
||||
return "上破目标价必须大于下破目标价"
|
||||
except (TypeError, ValueError):
|
||||
return "目标价无效"
|
||||
return None
|
||||
return "未知计划类型"
|
||||
|
||||
|
||||
def dump_preview(preview: Any) -> str:
|
||||
try:
|
||||
return json.dumps(preview, ensure_ascii=False)[:8000]
|
||||
except Exception:
|
||||
return ""
|
||||
@@ -0,0 +1,816 @@
|
||||
"""OKX 对冲计划:P0 测算页与 API 注册."""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from typing import Any
|
||||
|
||||
from flask import Flask, jsonify, request
|
||||
from jinja2 import ChoiceLoader, FileSystemLoader
|
||||
|
||||
from lib.hedge_plan.hedge_plan_calc_lib import (
|
||||
build_options_options_preview,
|
||||
build_perp_options_preview,
|
||||
floor_contracts_to_precision,
|
||||
gate_status,
|
||||
option_premium_total,
|
||||
suggest_contracts_from_notional,
|
||||
)
|
||||
from lib.hub.hub_calculator_market_lib import amount_decimals_from_exchange
|
||||
from lib.trade.position_sizing_lib import (
|
||||
compute_full_margin_sizing,
|
||||
load_position_sizing_mode,
|
||||
)
|
||||
|
||||
|
||||
def _env_bool(key: str, default: bool = False) -> bool:
|
||||
raw = (os.getenv(key) or "").strip().lower()
|
||||
if not raw:
|
||||
return default
|
||||
return raw in ("1", "true", "yes", "on")
|
||||
|
||||
|
||||
def attach_hedge_plan_templates(app: Flask, repo_root: str) -> None:
|
||||
tpl_dir = os.path.join(repo_root, "lib", "hedge_plan", "templates")
|
||||
if not os.path.isdir(tpl_dir):
|
||||
return
|
||||
existing = app.jinja_loader
|
||||
loaders = [FileSystemLoader(tpl_dir)]
|
||||
if existing is not None:
|
||||
if isinstance(existing, ChoiceLoader):
|
||||
loaders = list(existing.loaders) + loaders
|
||||
else:
|
||||
loaders.insert(0, existing)
|
||||
app.jinja_loader = ChoiceLoader(loaders)
|
||||
|
||||
|
||||
def install_hedge_plan(app: Flask, repo_root: str, app_module: Any) -> None:
|
||||
attach_hedge_plan_templates(app, repo_root)
|
||||
cfg = _build_cfg(app_module)
|
||||
app.extensions["hedge_plan_cfg"] = cfg
|
||||
register_hedge_plan_routes(app, cfg)
|
||||
_maybe_start_monitor(cfg)
|
||||
|
||||
|
||||
def _build_cfg(app_module: Any) -> dict[str, Any]:
|
||||
from lib.exchange.okx_options_lib import (
|
||||
build_option_chain,
|
||||
fetch_index_price,
|
||||
options_header_balances,
|
||||
place_option_limit_order,
|
||||
quote_option_contract,
|
||||
td_mode_for_option_buy,
|
||||
)
|
||||
|
||||
def _amount_to_precision(sym: str, amt: float) -> float:
|
||||
ex = getattr(app_module, "exchange", None)
|
||||
if ex is None:
|
||||
return float(amt)
|
||||
return float(ex.amount_to_precision(sym, amt))
|
||||
|
||||
return {
|
||||
"get_db": app_module.get_db,
|
||||
"login_required": app_module.login_required,
|
||||
"render_main_page": app_module.render_main_page,
|
||||
"exchange": getattr(app_module, "exchange", None),
|
||||
"exchange_options": getattr(app_module, "exchange_options", None),
|
||||
"get_available_trading_usdt": getattr(app_module, "get_available_trading_usdt", None),
|
||||
"get_contract_size": getattr(app_module, "get_contract_size", None),
|
||||
"normalize_exchange_symbol": getattr(app_module, "normalize_exchange_symbol", None),
|
||||
"ensure_markets_loaded": getattr(app_module, "ensure_markets_loaded", None),
|
||||
"ensure_okx_live_ready": getattr(app_module, "ensure_okx_live_ready", None),
|
||||
"place_exchange_order": getattr(app_module, "place_exchange_order", None),
|
||||
"get_live_position_contracts": getattr(app_module, "get_live_position_contracts", None),
|
||||
"amount_to_precision": _amount_to_precision,
|
||||
"build_option_chain": build_option_chain,
|
||||
"options_header_balances": options_header_balances,
|
||||
"quote_option_contract": quote_option_contract,
|
||||
"place_option_limit_order": place_option_limit_order,
|
||||
"td_mode_for_option_buy": td_mode_for_option_buy,
|
||||
"fetch_index_price": fetch_index_price,
|
||||
"options_td_mode": (os.getenv("OKX_OPTIONS_TD_MODE") or "isolated").strip(),
|
||||
"btc_leverage": int(getattr(app_module, "BTC_LEVERAGE", 10) or 10),
|
||||
"alt_leverage": int(getattr(app_module, "ALT_LEVERAGE", 5) or 5),
|
||||
"full_margin_buffer": float(getattr(app_module, "FULL_MARGIN_BUFFER_RATIO", 0.98) or 0.98),
|
||||
"funds_decimals": int(getattr(app_module, "FUNDS_DECIMALS", 2) or 2),
|
||||
"options_enabled": _env_bool("OKX_OPTIONS_ENABLED", False),
|
||||
"default_underly": (os.getenv("OKX_OPTIONS_DEFAULT_UNDERLY") or "ETH").strip().upper(),
|
||||
"chain_max_dte": float(os.getenv("OKX_OPTIONS_CHAIN_MAX_DTE_DAYS") or os.getenv("OKX_OPTIONS_MAX_DTE_DAYS") or "14"),
|
||||
"perp_account_label": (os.getenv("OKX_ACCOUNT_LABEL") or "合约账户").strip(),
|
||||
"options_account_label": (os.getenv("OKX_OPTIONS_ACCOUNT_LABEL") or "期权账户").strip(),
|
||||
"live_trading": _env_bool("LIVE_TRADING_ENABLED", False),
|
||||
"send_wechat": getattr(app_module, "send_wechat_msg", None),
|
||||
}
|
||||
|
||||
|
||||
def _hedge_enabled() -> bool:
|
||||
return _env_bool("HEDGE_PLAN_ENABLED", False)
|
||||
|
||||
|
||||
def _live_order() -> bool:
|
||||
return _env_bool("HEDGE_PLAN_LIVE_ORDER", False)
|
||||
|
||||
|
||||
def _max_active() -> int:
|
||||
try:
|
||||
return max(1, int(os.getenv("MAX_ACTIVE_HEDGE_PLANS") or "1"))
|
||||
except ValueError:
|
||||
return 1
|
||||
|
||||
|
||||
def _gates_dict(cfg: dict[str, Any], plan_type: str) -> dict[str, Any]:
|
||||
active = 0
|
||||
try:
|
||||
from lib.hedge_plan.hedge_plan_db import count_active_plans, init_hedge_plan_tables
|
||||
|
||||
conn = cfg["get_db"]()
|
||||
try:
|
||||
init_hedge_plan_tables(conn)
|
||||
active = count_active_plans(conn)
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
except Exception:
|
||||
active = 0
|
||||
return gate_status(
|
||||
hedge_enabled=_hedge_enabled(),
|
||||
sizing_mode=load_position_sizing_mode(),
|
||||
plan_type=plan_type,
|
||||
options_enabled=bool(cfg.get("options_enabled")),
|
||||
live_order=_live_order(),
|
||||
live_trading=bool(cfg.get("live_trading")) or _env_bool("LIVE_TRADING_ENABLED", False),
|
||||
active_count=active,
|
||||
max_active=_max_active(),
|
||||
)
|
||||
|
||||
|
||||
def _maybe_start_monitor(cfg: dict[str, Any]) -> None:
|
||||
if not _hedge_enabled():
|
||||
return
|
||||
try:
|
||||
secs = float(os.getenv("HEDGE_PLAN_MONITOR_POLL_SECONDS") or "15")
|
||||
except ValueError:
|
||||
secs = 15.0
|
||||
secs = max(5.0, secs)
|
||||
|
||||
def _loop() -> None:
|
||||
import time
|
||||
|
||||
from lib.hedge_plan.hedge_plan_monitor_lib import tick_active_plans
|
||||
|
||||
while True:
|
||||
try:
|
||||
tick_active_plans(cfg)
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(secs)
|
||||
|
||||
import threading
|
||||
|
||||
t = threading.Thread(target=_loop, name="hedge-plan-monitor", daemon=True)
|
||||
t.start()
|
||||
cfg["hedge_monitor_thread"] = t
|
||||
|
||||
|
||||
def _persist_po(cfg: dict[str, Any], result: dict[str, Any], body: dict[str, Any]) -> int:
|
||||
from lib.hedge_plan.hedge_plan_db import (
|
||||
get_plan,
|
||||
get_plan_legs,
|
||||
init_hedge_plan_tables,
|
||||
insert_leg,
|
||||
insert_plan,
|
||||
)
|
||||
from lib.hedge_plan.hedge_plan_notify_lib import notify_plan_start
|
||||
|
||||
conn = cfg["get_db"]()
|
||||
try:
|
||||
init_hedge_plan_tables(conn)
|
||||
opt = result.get("option") or {}
|
||||
perp = result.get("perp") or {}
|
||||
premium = float(opt.get("premium") or 0)
|
||||
plan_id = insert_plan(
|
||||
conn,
|
||||
{
|
||||
"plan_type": "perp_options",
|
||||
"status": "active",
|
||||
"underlying": str(body.get("underlying") or "ETH").upper(),
|
||||
"direction": str(body.get("direction") or "long"),
|
||||
"entry_mark": float(body.get("entry") or 0),
|
||||
"tp": float(body.get("tp") or 0),
|
||||
"sl": float(body.get("sl") or 0),
|
||||
"sizing_mode_at_open": load_position_sizing_mode(),
|
||||
"perp_size": float(perp.get("contracts") or body.get("contracts") or 0),
|
||||
"margin": body.get("margin"),
|
||||
"leverage": float(body.get("leverage") or 10),
|
||||
"premium_total": premium,
|
||||
"opened_at": result.get("opened_at"),
|
||||
},
|
||||
)
|
||||
insert_leg(
|
||||
conn,
|
||||
{
|
||||
"plan_id": plan_id,
|
||||
"leg_role": "perp",
|
||||
"symbol": str(body.get("exchange_symbol") or ""),
|
||||
"side": str(body.get("direction") or "long"),
|
||||
"size": float(perp.get("contracts") or body.get("contracts") or 0),
|
||||
"avg_open": float(body.get("entry") or 0),
|
||||
"status": "open",
|
||||
"exchange_ord_id": str(perp.get("exchange_ord_id") or ""),
|
||||
"opened_at": result.get("opened_at"),
|
||||
},
|
||||
)
|
||||
insert_leg(
|
||||
conn,
|
||||
{
|
||||
"plan_id": plan_id,
|
||||
"leg_role": "option_hedge",
|
||||
"inst_id": str(opt.get("inst_id") or body.get("opt_inst_id") or ""),
|
||||
"opt_type": str(opt.get("opt_type") or body.get("opt_type") or ""),
|
||||
"strike": opt.get("strike") or body.get("strike"),
|
||||
"side": "buy",
|
||||
"size": float(opt.get("sheets") or body.get("sheets") or 1),
|
||||
"avg_open": float(opt.get("ask") or 0),
|
||||
"premium": premium,
|
||||
"status": "open",
|
||||
"exchange_ord_id": str(opt.get("exchange_ord_id") or ""),
|
||||
"opened_at": result.get("opened_at"),
|
||||
},
|
||||
)
|
||||
conn.commit()
|
||||
plan = get_plan(conn, plan_id)
|
||||
legs = get_plan_legs(conn, plan_id)
|
||||
if plan:
|
||||
notify_plan_start(cfg, conn, plan, legs)
|
||||
conn.commit()
|
||||
return plan_id
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def _persist_oo(cfg: dict[str, Any], result: dict[str, Any], body: dict[str, Any]) -> int:
|
||||
from lib.hedge_plan.hedge_plan_db import (
|
||||
get_plan,
|
||||
get_plan_legs,
|
||||
init_hedge_plan_tables,
|
||||
insert_leg,
|
||||
insert_plan,
|
||||
)
|
||||
from lib.hedge_plan.hedge_plan_notify_lib import notify_plan_start
|
||||
|
||||
conn = cfg["get_db"]()
|
||||
try:
|
||||
init_hedge_plan_tables(conn)
|
||||
a = result.get("leg_a") or {}
|
||||
b = result.get("leg_b") or {}
|
||||
premium = float(a.get("premium") or 0) + float(b.get("premium") or 0)
|
||||
plan_id = insert_plan(
|
||||
conn,
|
||||
{
|
||||
"plan_type": "options_options",
|
||||
"status": "active",
|
||||
"underlying": str(body.get("underlying") or "ETH").upper(),
|
||||
"target_price": float(
|
||||
body.get("target_price_up")
|
||||
or body.get("target_price")
|
||||
or 0
|
||||
),
|
||||
"target_price_up": float(
|
||||
body.get("target_price_up")
|
||||
or body.get("target_price")
|
||||
or 0
|
||||
),
|
||||
"target_price_down": float(
|
||||
body.get("target_price_down")
|
||||
or body.get("target_price")
|
||||
or 0
|
||||
),
|
||||
"sizing_mode_at_open": load_position_sizing_mode(),
|
||||
"premium_total": premium,
|
||||
"opened_at": result.get("opened_at"),
|
||||
},
|
||||
)
|
||||
for role, res, src in (("option_a", a, body.get("leg_a") or {}), ("option_b", b, body.get("leg_b") or {})):
|
||||
insert_leg(
|
||||
conn,
|
||||
{
|
||||
"plan_id": plan_id,
|
||||
"leg_role": role,
|
||||
"inst_id": str(res.get("inst_id") or src.get("inst_id") or ""),
|
||||
"opt_type": str(res.get("opt_type") or src.get("opt_type") or ""),
|
||||
"strike": res.get("strike") or src.get("strike"),
|
||||
"side": "buy",
|
||||
"size": float(res.get("sheets") or src.get("sheets") or 1),
|
||||
"avg_open": float(res.get("ask") or 0),
|
||||
"premium": float(res.get("premium") or 0),
|
||||
"status": "open",
|
||||
"exchange_ord_id": str(res.get("exchange_ord_id") or ""),
|
||||
"opened_at": result.get("opened_at"),
|
||||
},
|
||||
)
|
||||
conn.commit()
|
||||
plan = get_plan(conn, plan_id)
|
||||
legs = get_plan_legs(conn, plan_id)
|
||||
if plan:
|
||||
notify_plan_start(cfg, conn, plan, legs)
|
||||
conn.commit()
|
||||
return plan_id
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def register_hedge_plan_routes(app: Flask, cfg: dict[str, Any]) -> None:
|
||||
lr = cfg["login_required"]
|
||||
|
||||
@app.route("/hedge-plan")
|
||||
@lr
|
||||
def page_hedge_plan():
|
||||
from lib.instance.instance_embed_lib import redirect_to_embed_shell_if_enabled
|
||||
|
||||
redir = redirect_to_embed_shell_if_enabled("hedge_plan")
|
||||
if redir is not None:
|
||||
return redir
|
||||
return cfg["render_main_page"]("hedge_plan")
|
||||
|
||||
@app.route("/api/hedge-plan/gates")
|
||||
@lr
|
||||
def api_hedge_gates():
|
||||
plan_type = (request.args.get("plan_type") or "perp_options").strip()
|
||||
return jsonify({"ok": True, **_gates_dict(cfg, plan_type)})
|
||||
|
||||
@app.route("/api/hedge-plan/market")
|
||||
@lr
|
||||
def api_hedge_market():
|
||||
base = (request.args.get("base") or cfg.get("default_underly") or "ETH").strip().upper()
|
||||
if base not in ("BTC", "ETH"):
|
||||
return jsonify({"ok": False, "msg": "对冲计划仅支持 BTC/ETH"}), 400
|
||||
direction = (request.args.get("direction") or "long").strip().lower()
|
||||
if direction not in ("long", "short"):
|
||||
direction = "long"
|
||||
data, err = _fetch_perp_market(cfg, base)
|
||||
if err:
|
||||
return jsonify({"ok": False, "msg": err}), 400
|
||||
sizing_mode = load_position_sizing_mode()
|
||||
gates = _gates_dict(cfg, "perp_options")
|
||||
out = {
|
||||
"ok": True,
|
||||
"base": base,
|
||||
"direction": direction,
|
||||
"suggested_opt_type": "P" if direction == "long" else "C",
|
||||
**data,
|
||||
"gates": gates,
|
||||
"sizing_mode": sizing_mode,
|
||||
"account_kind": "perp",
|
||||
"account_label": cfg.get("perp_account_label") or "合约账户",
|
||||
"account_note": "永续腿使用合约(交易)账户可用 USDT",
|
||||
}
|
||||
return jsonify(out)
|
||||
|
||||
@app.route("/api/hedge-plan/options-chain")
|
||||
@lr
|
||||
def api_hedge_options_chain():
|
||||
if not cfg.get("options_enabled"):
|
||||
return jsonify({"ok": False, "msg": "期权模块未启用"}), 400
|
||||
ex = cfg.get("exchange_options")
|
||||
if ex is None:
|
||||
return jsonify({"ok": False, "msg": "期权交易所未初始化"}), 400
|
||||
u = (request.args.get("underlying") or cfg.get("default_underly") or "ETH").upper()
|
||||
try:
|
||||
chain = cfg["build_option_chain"](
|
||||
ex,
|
||||
u,
|
||||
max_dte_days=float(cfg.get("chain_max_dte") or 14),
|
||||
itm_only=False,
|
||||
itm_max_dist_usd=float(os.getenv("OKX_OPTIONS_ITM_MAX_DIST_USD") or "30"),
|
||||
)
|
||||
except Exception as e:
|
||||
return jsonify({"ok": False, "msg": f"拉取期权链失败: {e}"}), 500
|
||||
opt_acct = _options_account_snapshot(cfg)
|
||||
return jsonify(
|
||||
{
|
||||
"ok": True,
|
||||
**chain,
|
||||
"underlying": u,
|
||||
"chain_max_dte_days": cfg.get("chain_max_dte"),
|
||||
"account_kind": "options",
|
||||
"account_label": cfg.get("options_account_label") or "期权账户",
|
||||
"account_note": "期权腿使用期权账户(交易 USDC)",
|
||||
"options_account": opt_acct,
|
||||
}
|
||||
)
|
||||
|
||||
@app.route("/api/hedge-plan/preview", methods=["POST"])
|
||||
@lr
|
||||
def api_hedge_preview():
|
||||
body = request.get_json(silent=True) or {}
|
||||
plan_type = (body.get("plan_type") or "perp_options").strip().lower()
|
||||
gates = _gates_dict(cfg, plan_type)
|
||||
if not gates.get("can_preview"):
|
||||
return jsonify({"ok": False, "msg": "; ".join(gates.get("reasons") or ["不可测算"]), "gates": gates}), 400
|
||||
try:
|
||||
if plan_type == "options_options":
|
||||
data = _preview_oo(body)
|
||||
else:
|
||||
data = _preview_po(body)
|
||||
except ValueError as e:
|
||||
return jsonify({"ok": False, "msg": str(e)}), 400
|
||||
except Exception as e:
|
||||
return jsonify({"ok": False, "msg": f"测算失败: {e}"}), 500
|
||||
return jsonify({"ok": True, "gates": gates, **data})
|
||||
|
||||
@app.route("/api/hedge-plan/validate-path", methods=["POST"])
|
||||
@lr
|
||||
def api_hedge_validate_path():
|
||||
"""只校验下单路径(强制 dry_run),不真实成交."""
|
||||
from lib.hedge_plan.hedge_plan_orders_lib import (
|
||||
execute_options_options_start,
|
||||
execute_perp_options_start,
|
||||
validate_start_body,
|
||||
)
|
||||
|
||||
body = request.get_json(silent=True) or {}
|
||||
plan_type = (body.get("plan_type") or "perp_options").strip().lower()
|
||||
err = validate_start_body(plan_type, body)
|
||||
if err:
|
||||
return jsonify({"ok": False, "msg": err}), 400
|
||||
if plan_type == "options_options":
|
||||
out = execute_options_options_start(cfg, body, dry_run=True)
|
||||
else:
|
||||
out = execute_perp_options_start(cfg, body, dry_run=True)
|
||||
return jsonify(out), (200 if out.get("ok") else 400)
|
||||
|
||||
@app.route("/api/hedge-plan/start", methods=["POST"])
|
||||
@lr
|
||||
def api_hedge_start():
|
||||
from lib.hedge_plan.hedge_plan_orders_lib import (
|
||||
execute_options_options_start,
|
||||
execute_perp_options_start,
|
||||
validate_start_body,
|
||||
)
|
||||
|
||||
body = request.get_json(silent=True) or {}
|
||||
plan_type = (body.get("plan_type") or "perp_options").strip().lower()
|
||||
dry_run = bool(body.get("dry_run")) or _env_bool("HEDGE_PLAN_DRY_RUN", False)
|
||||
gates = _gates_dict(cfg, plan_type)
|
||||
if not dry_run and not gates.get("can_start"):
|
||||
return jsonify(
|
||||
{"ok": False, "msg": "; ".join(gates.get("reasons") or ["不可开仓"]), "gates": gates}
|
||||
), 400
|
||||
err = validate_start_body(plan_type, body)
|
||||
if err:
|
||||
return jsonify({"ok": False, "msg": err, "gates": gates}), 400
|
||||
# 补齐永续杠杆
|
||||
if plan_type == "perp_options" and not body.get("leverage"):
|
||||
base = str(body.get("underlying") or "ETH").upper()
|
||||
body["leverage"] = cfg.get("btc_leverage") if base == "BTC" else (cfg.get("btc_leverage") or 10)
|
||||
# ETH 也用 BTC 档 10x 按方案;ALT 为 alt_leverage 仅非 BTC/ETH
|
||||
if base in ("BTC", "ETH"):
|
||||
body["leverage"] = int(cfg.get("btc_leverage") or 10)
|
||||
if plan_type == "options_options":
|
||||
out = execute_options_options_start(
|
||||
cfg,
|
||||
body,
|
||||
dry_run=dry_run,
|
||||
persist=(None if dry_run else (lambda r, b: _persist_oo(cfg, r, b))),
|
||||
)
|
||||
else:
|
||||
out = execute_perp_options_start(
|
||||
cfg,
|
||||
body,
|
||||
dry_run=dry_run,
|
||||
persist=(None if dry_run else (lambda r, b: _persist_po(cfg, r, b))),
|
||||
)
|
||||
out["gates"] = gates
|
||||
return jsonify(out), (200 if out.get("ok") else 400)
|
||||
|
||||
@app.route("/api/hedge-plan/list")
|
||||
@lr
|
||||
def api_hedge_list():
|
||||
from lib.hedge_plan.hedge_plan_db import init_hedge_plan_tables, list_plans
|
||||
|
||||
status = (request.args.get("status") or "").strip() or None
|
||||
plan_type = (request.args.get("plan_type") or "").strip() or None
|
||||
underlying = (request.args.get("underlying") or "").strip() or None
|
||||
conn = cfg["get_db"]()
|
||||
try:
|
||||
init_hedge_plan_tables(conn)
|
||||
rows = list_plans(
|
||||
conn, status=status, plan_type=plan_type, underlying=underlying, limit=80
|
||||
)
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
return jsonify({"ok": True, "plans": rows})
|
||||
|
||||
@app.route("/api/hedge-plan/history")
|
||||
@lr
|
||||
def api_hedge_history():
|
||||
from lib.hedge_plan.hedge_plan_db import (
|
||||
attach_legs_to_plans,
|
||||
init_hedge_plan_tables,
|
||||
list_plans,
|
||||
)
|
||||
|
||||
conn = cfg["get_db"]()
|
||||
try:
|
||||
init_hedge_plan_tables(conn)
|
||||
rows = list_plans(conn, status="closed", limit=100)
|
||||
failed = list_plans(conn, status="failed", limit=50)
|
||||
cancelled = list_plans(conn, status="cancelled", limit=50)
|
||||
merged = attach_legs_to_plans(conn, rows + failed + cancelled)
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
return jsonify({"ok": True, "plans": merged})
|
||||
|
||||
@app.route("/api/hedge-plan/active")
|
||||
@lr
|
||||
def api_hedge_active():
|
||||
from lib.hedge_plan.hedge_plan_db import (
|
||||
attach_legs_to_plans,
|
||||
init_hedge_plan_tables,
|
||||
list_plans,
|
||||
)
|
||||
|
||||
conn = cfg["get_db"]()
|
||||
try:
|
||||
init_hedge_plan_tables(conn)
|
||||
rows = []
|
||||
for status in ("opening", "active", "partial"):
|
||||
rows.extend(list_plans(conn, status=status, limit=80))
|
||||
rows.sort(key=lambda row: int(row.get("id") or 0), reverse=True)
|
||||
plans = attach_legs_to_plans(conn, rows)
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
return jsonify({"ok": True, "plans": plans})
|
||||
|
||||
@app.route("/api/hedge-plan/stats")
|
||||
@lr
|
||||
def api_hedge_stats():
|
||||
from lib.hedge_plan.hedge_plan_db import init_hedge_plan_tables, stats_summary
|
||||
|
||||
conn = cfg["get_db"]()
|
||||
try:
|
||||
init_hedge_plan_tables(conn)
|
||||
s = stats_summary(conn)
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
return jsonify({"ok": True, **s})
|
||||
|
||||
@app.route("/api/hedge-plan/<int:plan_id>")
|
||||
@lr
|
||||
def api_hedge_detail(plan_id: int):
|
||||
from lib.hedge_plan.hedge_plan_db import (
|
||||
get_plan,
|
||||
get_plan_legs,
|
||||
init_hedge_plan_tables,
|
||||
legs_contract_summary,
|
||||
)
|
||||
|
||||
conn = cfg["get_db"]()
|
||||
try:
|
||||
init_hedge_plan_tables(conn)
|
||||
plan = get_plan(conn, plan_id)
|
||||
if not plan:
|
||||
return jsonify({"ok": False, "msg": "计划不存在"}), 404
|
||||
legs = get_plan_legs(conn, plan_id)
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
return jsonify(
|
||||
{
|
||||
"ok": True,
|
||||
"plan": plan,
|
||||
"legs": legs,
|
||||
"contracts_summary": legs_contract_summary(legs),
|
||||
}
|
||||
)
|
||||
|
||||
@app.route("/api/hedge-plan/<int:plan_id>", methods=["DELETE"])
|
||||
@lr
|
||||
def api_hedge_delete(plan_id: int):
|
||||
from lib.hedge_plan.hedge_plan_db import delete_plan, init_hedge_plan_tables
|
||||
|
||||
conn = cfg["get_db"]()
|
||||
try:
|
||||
init_hedge_plan_tables(conn)
|
||||
out = delete_plan(conn, plan_id)
|
||||
if not out.get("ok"):
|
||||
return jsonify(out), 400
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
return jsonify(out)
|
||||
|
||||
@app.route("/api/hedge-plan/monitor-tick", methods=["POST"])
|
||||
@lr
|
||||
def api_hedge_monitor_tick():
|
||||
from lib.hedge_plan.hedge_plan_monitor_lib import tick_active_plans
|
||||
|
||||
return jsonify(tick_active_plans(cfg))
|
||||
|
||||
|
||||
def _preview_po(body: dict[str, Any]) -> dict[str, Any]:
|
||||
direction = str(body.get("direction") or "long").lower()
|
||||
entry = float(body["entry"])
|
||||
tp = float(body["tp"])
|
||||
sl = float(body["sl"])
|
||||
contracts = float(body["contracts"])
|
||||
contract_size = float(body.get("contract_size") or 0.01)
|
||||
opt_type = str(body.get("opt_type") or ("P" if direction == "long" else "C"))
|
||||
strike = float(body["strike"])
|
||||
sheets = float(body.get("sheets") or 1)
|
||||
ct_mult = float(body.get("ct_mult") or 0.01)
|
||||
ask = body.get("ask")
|
||||
premium = body.get("premium_paid")
|
||||
if premium is None:
|
||||
if ask is None:
|
||||
raise ValueError("缺少权利金或卖一价")
|
||||
premium = option_premium_total(ask=float(ask), sheets=sheets, ct_mult=ct_mult)
|
||||
index_px = body.get("index_px")
|
||||
return build_perp_options_preview(
|
||||
direction=direction,
|
||||
entry=entry,
|
||||
tp=tp,
|
||||
sl=sl,
|
||||
contracts=contracts,
|
||||
contract_size=contract_size,
|
||||
opt_type=opt_type,
|
||||
strike=strike,
|
||||
sheets=sheets,
|
||||
ct_mult=ct_mult,
|
||||
premium_paid=float(premium),
|
||||
index_px=float(index_px) if index_px is not None else None,
|
||||
)
|
||||
|
||||
|
||||
def _preview_oo(body: dict[str, Any]) -> dict[str, Any]:
|
||||
up = body.get("target_price_up")
|
||||
down = body.get("target_price_down")
|
||||
legacy = body.get("target_price")
|
||||
if up in (None, "") and legacy not in (None, ""):
|
||||
up = legacy
|
||||
if down in (None, "") and legacy not in (None, ""):
|
||||
down = legacy
|
||||
if up in (None, "") or down in (None, ""):
|
||||
raise ValueError("请填写上破与下破目标价")
|
||||
up_f = float(up)
|
||||
down_f = float(down)
|
||||
if up_f <= down_f:
|
||||
raise ValueError("上破目标价必须大于下破目标价")
|
||||
index_px = float(body.get("index_px") or ((up_f + down_f) / 2))
|
||||
leg_a = body.get("leg_a") or {}
|
||||
leg_b = body.get("leg_b") or {}
|
||||
for name, leg in (("leg_a", leg_a), ("leg_b", leg_b)):
|
||||
if not leg.get("strike"):
|
||||
raise ValueError(f"缺少 {name} 行权价")
|
||||
if leg.get("premium_paid") is None and leg.get("ask") is not None:
|
||||
leg["premium_paid"] = option_premium_total(
|
||||
ask=float(leg["ask"]),
|
||||
sheets=float(leg.get("sheets") or 1),
|
||||
ct_mult=float(leg.get("ct_mult") or 0.01),
|
||||
)
|
||||
if leg.get("premium_paid") is None:
|
||||
raise ValueError(f"缺少 {name} 权利金")
|
||||
return build_options_options_preview(
|
||||
target_price_up=up_f,
|
||||
target_price_down=down_f,
|
||||
index_px=index_px,
|
||||
leg_a=leg_a,
|
||||
leg_b=leg_b,
|
||||
)
|
||||
|
||||
|
||||
def _fetch_perp_market(cfg: dict[str, Any], base: str) -> tuple[dict[str, Any], str | None]:
|
||||
ex = cfg.get("exchange")
|
||||
if ex is None:
|
||||
return {}, "永续交易所未初始化"
|
||||
ensure = cfg.get("ensure_markets_loaded")
|
||||
if callable(ensure):
|
||||
try:
|
||||
ensure()
|
||||
except Exception as e:
|
||||
return {}, f"加载市场失败: {e}"
|
||||
norm = cfg.get("normalize_exchange_symbol")
|
||||
sym = f"{base}/USDT:USDT"
|
||||
if callable(norm):
|
||||
try:
|
||||
sym = norm(f"{base}/USDT")
|
||||
except Exception:
|
||||
sym = f"{base}/USDT:USDT"
|
||||
mark = bid = ask = last = None
|
||||
try:
|
||||
t = ex.fetch_ticker(sym)
|
||||
last = _sf(t.get("last"))
|
||||
mark = _sf(t.get("info", {}).get("markPx")) if isinstance(t.get("info"), dict) else None
|
||||
if mark is None:
|
||||
mark = _sf(t.get("mark")) or last
|
||||
bid = _sf(t.get("bid"))
|
||||
ask = _sf(t.get("ask"))
|
||||
except Exception as e:
|
||||
return {}, f"拉永续行情失败: {e}"
|
||||
|
||||
cs = 0.01
|
||||
get_cs = cfg.get("get_contract_size")
|
||||
if callable(get_cs):
|
||||
try:
|
||||
cs = float(get_cs(sym) or 0.01)
|
||||
except Exception:
|
||||
cs = 0.01
|
||||
|
||||
available = None
|
||||
get_av = cfg.get("get_available_trading_usdt")
|
||||
if callable(get_av):
|
||||
try:
|
||||
available = get_av()
|
||||
except Exception:
|
||||
available = None
|
||||
|
||||
entry = float(mark or last or 0)
|
||||
sizing = None
|
||||
suggest_contracts = None
|
||||
amount_precision = 4
|
||||
try:
|
||||
amount_precision = int(amount_decimals_from_exchange(ex, sym))
|
||||
except Exception:
|
||||
amount_precision = 4
|
||||
if available is not None and entry > 0:
|
||||
sizing, _serr = compute_full_margin_sizing(
|
||||
symbol=sym,
|
||||
available_usdt=float(available),
|
||||
capital_base=float(available),
|
||||
buffer_ratio=float(cfg.get("full_margin_buffer") or 0.98),
|
||||
btc_leverage=int(cfg.get("btc_leverage") or 10),
|
||||
alt_leverage=int(cfg.get("alt_leverage") or 5),
|
||||
funds_decimals=int(cfg.get("funds_decimals") or 2),
|
||||
)
|
||||
if sizing:
|
||||
raw_contracts = suggest_contracts_from_notional(
|
||||
notional=float(sizing["notional_value"]),
|
||||
entry=entry,
|
||||
contract_size=cs,
|
||||
)
|
||||
# 优先走交易所 amount_to_precision;失败则按精度位数向下取整
|
||||
suggest_contracts = None
|
||||
try:
|
||||
precise = float(ex.amount_to_precision(sym, raw_contracts))
|
||||
if precise > raw_contracts + 1e-12:
|
||||
precise = floor_contracts_to_precision(raw_contracts, amount_precision)
|
||||
suggest_contracts = precise
|
||||
except Exception:
|
||||
suggest_contracts = floor_contracts_to_precision(raw_contracts, amount_precision)
|
||||
|
||||
return {
|
||||
"exchange_symbol": sym,
|
||||
"mark": mark,
|
||||
"last": last,
|
||||
"bid": bid,
|
||||
"ask": ask,
|
||||
"contract_size": cs,
|
||||
"available_usdt": available,
|
||||
"full_margin_sizing": sizing,
|
||||
"suggest_contracts": suggest_contracts,
|
||||
"amount_precision": amount_precision,
|
||||
"unit_quote": "USDT",
|
||||
"unit_contracts": "合约张",
|
||||
"unit_note": "价格单位 USDT;张数=交易所永续合约张(与下单精度一致);名义≈张数×面值×价格",
|
||||
"entry_ref": entry or None,
|
||||
}, None
|
||||
|
||||
|
||||
def _options_account_snapshot(cfg: dict[str, Any]) -> dict[str, Any]:
|
||||
"""期权账户资金快照(与期权页同源: exchange_options)."""
|
||||
out: dict[str, Any] = {
|
||||
"label": cfg.get("options_account_label") or "期权账户",
|
||||
"trading_usdc": None,
|
||||
"funding_usdc": None,
|
||||
"trading_usdt": None,
|
||||
"funding_usdt": None,
|
||||
}
|
||||
ex = cfg.get("exchange_options")
|
||||
hdr = cfg.get("options_header_balances")
|
||||
if ex is None or not callable(hdr):
|
||||
return out
|
||||
try:
|
||||
trading_usdc, funding_usdc, funding_usdt, trading_usdt = hdr(ex, force=False)
|
||||
out.update(
|
||||
{
|
||||
"trading_usdc": trading_usdc,
|
||||
"funding_usdc": funding_usdc,
|
||||
"trading_usdt": trading_usdt,
|
||||
"funding_usdt": funding_usdt,
|
||||
}
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return out
|
||||
|
||||
|
||||
def _sf(v: Any) -> float | None:
|
||||
if v is None or v == "":
|
||||
return None
|
||||
try:
|
||||
return float(v)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
@@ -0,0 +1,62 @@
|
||||
"""对冲计划结算辅助:到期内在价值与期权腿收口."""
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from typing import Any, Optional
|
||||
|
||||
from lib.exchange.okx_options_lib import normalize_option_exp_ms
|
||||
from lib.hedge_plan.hedge_plan_calc_lib import option_expiry_pnl
|
||||
|
||||
|
||||
def _sf(v: Any) -> Optional[float]:
|
||||
try:
|
||||
if v is None or v == "":
|
||||
return None
|
||||
return float(v)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def leg_exp_ms(leg: dict[str, Any]) -> Optional[int]:
|
||||
return normalize_option_exp_ms(leg.get("exp_time"), str(leg.get("inst_id") or ""))
|
||||
|
||||
|
||||
def leg_is_expired(leg: dict[str, Any], *, now_ms: Optional[int] = None) -> bool:
|
||||
exp = leg_exp_ms(leg)
|
||||
if exp is None:
|
||||
return False
|
||||
now = int(now_ms if now_ms is not None else time.time() * 1000)
|
||||
return now >= int(exp)
|
||||
|
||||
|
||||
def settle_option_leg_at_spot(leg: dict[str, Any], spot: float) -> float:
|
||||
"""按到期结算口径估算腿盈亏(USDC)."""
|
||||
premium = float(leg.get("premium") or 0)
|
||||
strike = _sf(leg.get("strike"))
|
||||
if strike is None:
|
||||
return -premium
|
||||
sheets = float(leg.get("size") or 1)
|
||||
# ct_mult 未入库时默认 0.01
|
||||
ct = float(leg.get("ct_mult") or 0.01)
|
||||
return float(
|
||||
option_expiry_pnl(
|
||||
opt_type=str(leg.get("opt_type") or "P"),
|
||||
strike=float(strike),
|
||||
spot=float(spot),
|
||||
sheets=sheets,
|
||||
ct_mult=ct,
|
||||
premium_paid=premium,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def all_option_legs_expired(legs: list[dict[str, Any]], *, now_ms: Optional[int] = None) -> bool:
|
||||
opts = [
|
||||
x
|
||||
for x in legs
|
||||
if str(x.get("leg_role") or "").startswith("option")
|
||||
and str(x.get("status") or "") in ("open", "hold_to_expiry")
|
||||
]
|
||||
if not opts:
|
||||
return False
|
||||
return all(leg_is_expired(x, now_ms=now_ms) for x in opts)
|
||||
@@ -0,0 +1,258 @@
|
||||
<div class="hedge-plan-page-wrap" style="grid-column:1/-1" id="hedge-plan-root"
|
||||
data-default-underly="{{ options_default_underly | default('ETH') }}"
|
||||
data-hedge-enabled="{{ '1' if hedge_plan_enabled else '0' }}"
|
||||
data-options-enabled="{{ '1' if options_enabled else '0' }}"
|
||||
data-sizing-mode="{{ position_sizing_mode | default('risk') }}"
|
||||
data-is-full-margin="{{ '1' if position_sizing_mode == 'full_margin' else '0' }}">
|
||||
{% if not hedge_plan_enabled %}
|
||||
<div class="flash" style="margin-bottom:12px">对冲计划未启用:请在 <code>env配置 → 对冲计划</code> 打开 <code>HEDGE_PLAN_ENABLED</code>(可热更).</div>
|
||||
{% endif %}
|
||||
{% if not options_enabled %}
|
||||
<div class="flash" style="margin-bottom:12px">期权模块未启用,无法拉期权链.请先配置期权账户.</div>
|
||||
{% endif %}
|
||||
|
||||
<div class="card hp-head-card">
|
||||
<div class="hp-head-row">
|
||||
<h2 class="hp-title">对冲计划 <span class="muted hp-title-sub">测算 · 下单</span>
|
||||
<a class="muted" href="/options/guide" target="_blank" rel="noopener" style="font-size:13px;font-weight:500;margin-left:8px">期权开平仓与监控说明</a>
|
||||
</h2>
|
||||
<button type="button" class="btn-secondary" id="hp-refresh" title="刷新永续行情与期权链">刷新行情</button>
|
||||
</div>
|
||||
<div class="hp-tabs" role="tablist" aria-label="对冲计划分类">
|
||||
<button type="button" class="hp-tab active" role="tab" aria-selected="true" data-tab="perp_options">永期对冲</button>
|
||||
<button type="button" class="hp-tab" role="tab" aria-selected="false" data-tab="options_options">期期对冲</button>
|
||||
<button type="button" class="hp-tab" role="tab" aria-selected="false" data-tab="active">进行中的计划</button>
|
||||
<button type="button" class="hp-tab" role="tab" aria-selected="false" data-tab="history">历史记录</button>
|
||||
<button type="button" class="hp-tab" role="tab" aria-selected="false" data-tab="stats">统计分析</button>
|
||||
</div>
|
||||
<p class="muted" id="hp-gate-line"></p>
|
||||
<p class="muted hp-acct-hint" id="hp-acct-hint">永续腿→合约账户 · 期权腿→期权账户</p>
|
||||
</div>
|
||||
|
||||
<div id="hp-tab-perp_options" class="hp-tab-panel" role="tabpanel">
|
||||
<div class="options-dual-grid" id="hp-po-layout">
|
||||
<div class="card">
|
||||
<h2>永续 · <span id="hp-perp-uly-label">ETH</span> <span class="muted hp-acct-tag" id="hp-perp-acct-tag">合约账户</span></h2>
|
||||
<div class="form-row hp-uly-row">
|
||||
<button type="button" class="btn-secondary hp-uly-btn active" data-uly="ETH">ETH</button>
|
||||
<button type="button" class="btn-secondary hp-uly-btn" data-uly="BTC">BTC</button>
|
||||
<select id="hp-direction">
|
||||
<option value="long">做多</option>
|
||||
<option value="short">做空</option>
|
||||
</select>
|
||||
</div>
|
||||
<div id="hp-perp-quote" class="muted hp-quote-line">加载中…</div>
|
||||
<p class="muted hp-unit-hint">单位说明:价格=USDT · 张数=交易所<strong>永续合约张</strong>(精度与 OKX 下单一致) · 盈亏=USDT</p>
|
||||
<div class="form-row" style="flex-wrap:wrap">
|
||||
<label>开仓价 <span class="hp-unit">USDT</span> <input type="number" step="any" id="hp-entry" /></label>
|
||||
<label>止盈 <span class="hp-unit">USDT</span> <input type="number" step="any" id="hp-tp" /></label>
|
||||
<label>止损 <span class="hp-unit">USDT</span> <input type="number" step="any" id="hp-sl" /></label>
|
||||
<label>张数 <span class="hp-unit">合约张</span> <input type="number" step="any" id="hp-contracts" /></label>
|
||||
</div>
|
||||
<p class="muted" id="hp-perp-pnl-line"></p>
|
||||
<p class="muted" id="hp-sizing-line"></p>
|
||||
</div>
|
||||
<div class="card hp-opt-card">
|
||||
<h2>期权(列表) · <span id="hp-opt-type-label">Put</span> <span class="muted hp-acct-tag" id="hp-opt-acct-tag">期权账户</span></h2>
|
||||
<div class="form-row hp-opt-toolbar">
|
||||
<select id="hp-exp-select"><option value="">选择到期日</option></select>
|
||||
<button type="button" class="btn-secondary hp-money-btn active" data-money="all">全部</button>
|
||||
<button type="button" class="btn-secondary hp-money-btn" data-money="itm">实值</button>
|
||||
<button type="button" class="btn-secondary hp-money-btn" data-money="otm">虚值</button>
|
||||
<button type="button" class="btn-secondary" id="hp-load-chain">刷新链</button>
|
||||
</div>
|
||||
<div id="hp-index-line" class="muted hp-quote-line"></div>
|
||||
<div class="options-strike-table-wrap hp-strike-table-wrap--5">
|
||||
<table class="options-strike-table" id="hp-strike-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>行权价</th>
|
||||
<th>实虚值</th>
|
||||
<th>卖一/张</th>
|
||||
<th>买一/张</th>
|
||||
<th>操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="hp-strike-tbody">
|
||||
<tr><td colspan="5" class="muted">请刷新期权链</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div class="form-row hp-pick-row">
|
||||
<label>已选 <code id="hp-sel-inst">—</code></label>
|
||||
<label>张数 <span class="hp-unit">期权张</span> <input type="number" step="1" min="1" id="hp-sheets" value="1" /></label>
|
||||
<span class="muted" id="hp-premium-line"></span>
|
||||
</div>
|
||||
<p class="muted hp-unit-hint">单位说明:权利金结算币=<strong>USDC</strong> · 张数=期权张(整张) · 卖一/买一=价格/张.期权买入仅认真实卖一价且卖一深度>0;无深度不可开仓(链上~为参考估算).</p>
|
||||
<div id="hp-opt-bal-line" class="muted hp-quote-line hp-opt-bal-line"></div>
|
||||
<div class="form-row hp-action-row">
|
||||
<button type="button" class="primary" id="hp-preview-btn">计算</button>
|
||||
<button type="button" class="btn-secondary" id="hp-start-btn" disabled title="需开启 HEDGE_PLAN_LIVE_ORDER 等门禁">启动计划</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card hp-preview-card" id="hp-preview-card-po">
|
||||
<h2 style="margin:0 0 8px">情景测算</h2>
|
||||
<div id="hp-summary" class="muted" style="margin:8px 0"></div>
|
||||
<div class="options-strike-table-wrap">
|
||||
<table class="options-strike-table" id="hp-result-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>情景</th>
|
||||
<th>现货价</th>
|
||||
<th>永续/腿盈亏</th>
|
||||
<th>期权盈亏</th>
|
||||
<th>合计≈U</th>
|
||||
<th>说明</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="hp-result-tbody">
|
||||
<tr><td colspan="6" class="muted">填写参数后点计算</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="hp-tab-options_options" class="hp-tab-panel hidden" role="tabpanel" hidden>
|
||||
<div class="options-dual-grid" id="hp-oo-layout">
|
||||
<div class="card">
|
||||
<h2>期期参数 · <span id="hp-oo-uly-label">ETH</span> <span class="muted hp-acct-tag">期权账户</span></h2>
|
||||
<div class="form-row hp-uly-row">
|
||||
<button type="button" class="btn-secondary hp-uly-btn-oo active" data-uly="ETH">ETH</button>
|
||||
<button type="button" class="btn-secondary hp-uly-btn-oo" data-uly="BTC">BTC</button>
|
||||
</div>
|
||||
<div class="form-row hp-target-row">
|
||||
<label>上破目标 <input type="number" step="any" id="hp-target-up" placeholder="向上突破" /></label>
|
||||
<label>下破目标 <input type="number" step="any" id="hp-target-down" placeholder="向下突破" /></label>
|
||||
</div>
|
||||
<div id="hp-oo-index" class="muted hp-quote-line"></div>
|
||||
<div id="hp-oo-bal-line" class="muted hp-quote-line"></div>
|
||||
<p class="muted hp-unit-hint">震荡突破:设上下两个目标价(USD);触达任一侧重平盈利腿。张数=<strong>期权张</strong> · 权利金=USDC</p>
|
||||
<div id="hp-oo-legs" class="hp-oo-legs">
|
||||
<div class="hp-oo-leg-row" data-leg="a">
|
||||
<div class="muted" id="hp-oo-leg-a-info">腿A: 尚未选用</div>
|
||||
<label>张数 <span class="hp-unit">期权张</span>
|
||||
<input type="number" step="1" min="1" id="hp-oo-sheets-a" value="1" disabled />
|
||||
</label>
|
||||
</div>
|
||||
<div class="hp-oo-leg-row" data-leg="b">
|
||||
<div class="muted" id="hp-oo-leg-b-info">腿B: 尚未选用</div>
|
||||
<label>张数 <span class="hp-unit">期权张</span>
|
||||
<input type="number" step="1" min="1" id="hp-oo-sheets-b" value="1" disabled />
|
||||
</label>
|
||||
</div>
|
||||
<p class="muted" id="hp-oo-prem-line"></p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card hp-opt-card">
|
||||
<h2>期权 T 型报价</h2>
|
||||
<div class="form-row">
|
||||
<select id="hp-oo-exp-select"><option value="">选择到期日</option></select>
|
||||
<button type="button" class="btn-secondary" id="hp-oo-load-chain">刷新链</button>
|
||||
</div>
|
||||
<div class="options-strike-table-wrap options-strike-table-wrap--t">
|
||||
<table class="options-strike-table options-strike-table--t" id="hp-oo-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th colspan="3" class="opt-t-head-call">Call</th>
|
||||
<th class="opt-t-head-mid">行权</th>
|
||||
<th colspan="3" class="opt-t-head-put">Put</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>卖一/张</th><th>实虚值</th><th>选用</th>
|
||||
<th>K</th>
|
||||
<th>实虚值</th><th>卖一/张</th><th>选用</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="hp-oo-tbody">
|
||||
<tr><td colspan="7" class="muted">请刷新期权链</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div class="form-row hp-action-row">
|
||||
<button type="button" class="primary" id="hp-preview-btn-oo">计算</button>
|
||||
<button type="button" class="btn-secondary" id="hp-start-btn-oo" title="需开启 HEDGE_PLAN_LIVE_ORDER">启动计划</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card hp-preview-card">
|
||||
<h2 style="margin:0 0 8px">情景测算</h2>
|
||||
<div id="hp-summary-oo" class="muted" style="margin:8px 0"></div>
|
||||
<div class="options-strike-table-wrap">
|
||||
<table class="options-strike-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>情景</th>
|
||||
<th>现货价</th>
|
||||
<th>腿盈亏</th>
|
||||
<th>期权</th>
|
||||
<th>合计≈U</th>
|
||||
<th>说明</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="hp-result-tbody-oo">
|
||||
<tr><td colspan="6" class="muted">选用两腿并填上破/下破目标后点计算</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="hp-tab-active" class="hp-tab-panel hidden" role="tabpanel" hidden>
|
||||
<div class="card">
|
||||
<h2>进行中的计划</h2>
|
||||
<p class="muted">仅显示已启动但尚未结束的计划;可查看每条腿的当前记录状态。</p>
|
||||
<div class="options-strike-table-wrap">
|
||||
<table class="options-strike-table hp-history-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>ID</th><th>类型</th><th>标的</th><th>合约</th><th>状态</th><th>目标/止盈止损</th><th>开仓</th><th>操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="hp-active-tbody">
|
||||
<tr><td colspan="8" class="muted">加载中…</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="hp-tab-history" class="hp-tab-panel hidden" role="tabpanel" hidden>
|
||||
<div class="card">
|
||||
<h2>历史记录</h2>
|
||||
<p class="muted">独立对冲计划历史(与普通交易记录分离)。点「成交细节」查看合约名与成交字段。</p>
|
||||
<div class="options-strike-table-wrap">
|
||||
<table class="options-strike-table hp-history-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>ID</th><th>类型</th><th>标的</th><th>合约</th><th>状态</th><th>合计≈U</th><th>原因</th><th>开仓</th><th>结束</th><th>操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="hp-history-tbody">
|
||||
<tr><td colspan="10" class="muted">加载中…</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="hp-tab-stats" class="hp-tab-panel hidden" role="tabpanel" hidden>
|
||||
<div class="card">
|
||||
<h2>统计分析</h2>
|
||||
<p class="muted">按永期 / 期期分别统计:胜率、盈亏比、最大盈利、最大亏损、最大回撤(按结束时间累积)</p>
|
||||
<div id="hp-stats-box" class="muted">加载中…</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="hp-detail-modal" class="hp-modal-backdrop" hidden>
|
||||
<div class="hp-modal" role="dialog" aria-modal="true" aria-labelledby="hp-detail-title">
|
||||
<div class="hp-modal-head">
|
||||
<h3 id="hp-detail-title">成交细节</h3>
|
||||
<button type="button" class="btn-secondary" id="hp-detail-close">关闭</button>
|
||||
</div>
|
||||
<div id="hp-detail-body" class="hp-modal-body muted">加载中…</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<script src="/static/hedge_plan.js?v=13"></script>
|
||||
Reference in New Issue
Block a user