Compare commits
130 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| c73e36309e | |||
| 21c80f2ac9 | |||
| a908dccaba | |||
| 4bcf88b5cb | |||
| f360242188 | |||
| f53f2814ab | |||
| e5051fb309 | |||
| 1dc7914701 | |||
| 58e2bf3e8b | |||
| 19debee581 | |||
| 1755f67eca | |||
| 6886de0bad | |||
| f04a91efe6 | |||
| b43e33e24f | |||
| b5a061e758 | |||
| 4ef3b40353 | |||
| 4a79e010c4 | |||
| 791cc750da | |||
| c8231ea194 | |||
| aaccdcfc16 | |||
| f993a89a21 | |||
| 9dc363270e | |||
| 9a83dfe209 | |||
| 32c42b8447 | |||
| a2075ba73e | |||
| 846f3de525 | |||
| a7b75895e6 | |||
| d870178b83 | |||
| 7ebe1671b2 | |||
| cb4f6aaa4b | |||
| eb175820e9 | |||
| 890659f173 | |||
| ca499c6104 | |||
| 54f1857fa2 | |||
| 6f1ae14b3d | |||
| 29d59d6a53 | |||
| 58a4dafe9a | |||
| 9e0591c676 | |||
| ed3033d793 | |||
| b6156e0049 | |||
| 8e3c00641f | |||
| f11f89e760 | |||
| 0096467d14 | |||
| 8a9dee267f | |||
| 910c938d0a | |||
| 0a9e3aa95c | |||
| b64c742fc9 | |||
| 789ab43dbe | |||
| 61e8da1e8b | |||
| 40be3a5ab7 | |||
| 4ccfb838f6 | |||
| 58e9c8f85e | |||
| eb0eddbc9d | |||
| c5f40cba2b | |||
| a7216428ab | |||
| 77f66bf200 | |||
| 488b931959 | |||
| b89cba3b6e | |||
| e7f8e9201e | |||
| 301a464f29 | |||
| a4be294c06 | |||
| 1a163c0a43 | |||
| 2a60d47b2d | |||
| 64b24fd6a6 | |||
| 60ff45f098 | |||
| 67a09b1de8 | |||
| 7e7666adfb | |||
| 6876515160 | |||
| 1bc12a32c6 | |||
| 6def61fae3 | |||
| 10ee7614b5 | |||
| 221e8c3cad | |||
| 29c080f8e0 | |||
| 7a01535802 | |||
| f467f94fe9 | |||
| 913c7d5be6 | |||
| 0f5fe801e2 | |||
| 977d62bddf | |||
| 3ed8dabc76 | |||
| eb2afb3c55 | |||
| ee3c1bcdca | |||
| d2028ed0ee | |||
| 3ae7def999 | |||
| c9229d64bf | |||
| 3923818508 | |||
| 4a3e6a2a1d | |||
| 00d76ba20f | |||
| 5b346a5760 | |||
| a43cb35d9a | |||
| 8597e47596 | |||
| 88d460d484 | |||
| ed1ec6f14a | |||
| 7eb098def6 | |||
| 972ef4f910 | |||
| 4e614eb9ed | |||
| 547eedeec4 | |||
| 19b46d19fd | |||
| debfb116fd | |||
| 3c21680763 | |||
| bc08a5852d | |||
| a2d4507028 | |||
| 17cd835e5d | |||
| ac018cb618 | |||
| 220aab9b63 | |||
| 72dddc5106 | |||
| 12574ae88a | |||
| 426afb8dbe | |||
| 38ac258497 | |||
| 7938628485 | |||
| e3cd2a75de | |||
| bc797cb1db | |||
| 0ed2eabf0d | |||
| 5e0ce43415 | |||
| eea4d4ff8f | |||
| d74d0aeae0 | |||
| e11c13747a | |||
| 899a2de931 | |||
| fa2127d66c | |||
| d5f3f315dc | |||
| 1c155328b4 | |||
| 3093d07167 | |||
| 79420904f4 | |||
| 3119486105 | |||
| b3548240cc | |||
| f21e4d1166 | |||
| 9e1343981d | |||
| 2f7e6355a1 | |||
| 023bf6a814 | |||
| 9198aa0dcd | |||
| 82c910fbf8 |
@@ -1,18 +0,0 @@
|
||||
---
|
||||
description: After each completed code change, commit, push origin/main, and deploy to zk.hyf2.cc
|
||||
alwaysApply: true
|
||||
---
|
||||
|
||||
# Auto push & deploy
|
||||
|
||||
When a user-facing code change is **finished** (not mid-debug / not "先不要改代码"):
|
||||
|
||||
1. Commit only the relevant files (skip unrelated CRLF-only docs noise).
|
||||
2. `git push origin main` to `https://git.bz121.com/dekun/crypto_monitor.git`.
|
||||
3. Deploy to production `zk.hyf2.cc`:`cd /opt/crypto_monitor && git pull && bash deploy/pull_and_restart.sh`.
|
||||
4. Confirm PM2 processes are online; briefly report commit hash + deploy status.
|
||||
|
||||
Do **not** wait for the user to say "推送并部署" again unless they cancel this habit.
|
||||
|
||||
SSH: Prefer key auth; if BatchMode fails, use existing Paramiko root login path used in this project.
|
||||
Do not print or put passwords in user-facing replies.
|
||||
@@ -3,5 +3,8 @@
|
||||
deploy/** text eol=lf
|
||||
# 文档统一 LF,避免 Windows 编辑后产生 CRLF 脏 diff
|
||||
docs/** text eol=lf
|
||||
# XMind 为 ZIP 二进制;须覆盖上面 docs/** 的 text/eol,否则入库会损坏打不开
|
||||
*.xmind -text -diff -merge -eol
|
||||
docs/**/*.xmind -text -diff -merge -eol
|
||||
# .env 模板统一 LF,避免 Linux PM2 source 报 $'\r': command not found
|
||||
**/.env.example text eol=lf
|
||||
|
||||
@@ -15,12 +15,17 @@
|
||||
**/.env.backup*
|
||||
**/.env.bak
|
||||
**/.env.local
|
||||
|
||||
# Cursor 本机规则/配置(勿提交;只留本地)
|
||||
.cursor/
|
||||
|
||||
manual_trading_hub/hub_settings.json
|
||||
manual_trading_hub/hub_backup_state.json
|
||||
manual_trading_hub/hub_fund_history.json
|
||||
manual_trading_hub/hub_supervisor_state.json
|
||||
manual_trading_hub/hub_ai_summaries.json
|
||||
manual_trading_hub/hub_ai_chat.json
|
||||
manual_trading_hub/amp_stats_history.json
|
||||
manual_trading_hub/hub_ai_fund_history.json
|
||||
manual_trading_hub/data/
|
||||
backups/
|
||||
|
||||
@@ -158,6 +158,8 @@ RISK_CONTROL_ENABLED=true
|
||||
RISK_COOLING_HOURS_MANUAL=4
|
||||
RISK_COOLING_HOURS_MANUAL_JOURNAL=1
|
||||
RISK_MANUAL_CLOSE_DAILY_LIMIT=2
|
||||
# 日亏损次数上限:平仓盈亏<0 计1次;达限当日冻结开仓;0=不启用
|
||||
RISK_DAILY_LOSS_LIMIT=2
|
||||
RISK_MOOD_ISSUES_DAILY_FREEZE=true
|
||||
|
||||
# 资金与仓位刷新周期(秒)
|
||||
|
||||
@@ -411,7 +411,7 @@ _APP_STARTED_AT = time.time()
|
||||
_RECONCILE_FLAT_STREAK = {}
|
||||
KLINE_TIMEFRAME = os.getenv("KLINE_TIMEFRAME", "5m")
|
||||
FULL_MARGIN_BUFFER_RATIO = float(os.getenv("FULL_MARGIN_BUFFER_RATIO", "0.98"))
|
||||
TRANSFER_CCY = os.getenv("TRANSFER_CCY", "USDT")
|
||||
TRANSFER_CCY = (os.getenv("TRANSFER_CCY", "USDT") or "USDT").strip().upper() or "USDT"
|
||||
UPLOAD_FOLDER = resolve_path(os.getenv("UPLOAD_DIR", "static/images"))
|
||||
ORDER_CHART_ENABLED = os.getenv("ORDER_CHART_ENABLED", "true").lower() == "true"
|
||||
ORDER_CHART_TFS = [x.strip() for x in (os.getenv("ORDER_CHART_TFS", "4h,1h,15m,5m") or "").split(",") if x.strip()]
|
||||
@@ -2751,6 +2751,17 @@ def insert_trade_record(
|
||||
opened_at_ms=open_ts_ms,
|
||||
closed_at_ms=close_ts_ms,
|
||||
)
|
||||
try:
|
||||
from lib.trade.account_risk_lib import on_closed_trade_pnl
|
||||
|
||||
close_dt = parse_dt_for_trading_day(close_ts)
|
||||
on_closed_trade_pnl(
|
||||
conn,
|
||||
pnl_amount=pnl_amount,
|
||||
trading_day=get_trading_day(close_dt),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return tid
|
||||
|
||||
|
||||
@@ -7482,6 +7493,15 @@ def risk_policy_page():
|
||||
return render_main_page("risk_policy")
|
||||
|
||||
|
||||
@app.route("/system_guide")
|
||||
@login_required
|
||||
def system_guide_page():
|
||||
redir = redirect_to_embed_shell_if_enabled("system_guide")
|
||||
if redir is not None:
|
||||
return redir
|
||||
return render_main_page("system_guide")
|
||||
|
||||
|
||||
@app.route("/env_config")
|
||||
@login_required
|
||||
def env_config_page():
|
||||
@@ -9850,7 +9870,7 @@ def manual_transfer():
|
||||
amount = float(request.form.get("amount", "0"))
|
||||
except Exception:
|
||||
flash("划转金额格式错误")
|
||||
return redirect("/settings")
|
||||
return redirect("/settings?settings_tab=transfer")
|
||||
from_account = (request.form.get("from_account") or AUTO_TRANSFER_FROM).strip()
|
||||
to_account = (request.form.get("to_account") or AUTO_TRANSFER_TO).strip()
|
||||
ok, msg, _ = execute_transfer_usdt(amount, from_account, to_account)
|
||||
@@ -9865,7 +9885,7 @@ def manual_transfer():
|
||||
flash(f"手动划转成功:{amount}U {from_account}->{to_account}")
|
||||
else:
|
||||
flash(f"手动划转失败:{msg}")
|
||||
return redirect("/settings")
|
||||
return redirect("/settings?settings_tab=transfer")
|
||||
|
||||
|
||||
def _journal_ai_chart_builder(row):
|
||||
|
||||
@@ -160,6 +160,8 @@ RISK_CONTROL_ENABLED=true
|
||||
RISK_COOLING_HOURS_MANUAL=4
|
||||
RISK_COOLING_HOURS_MANUAL_JOURNAL=1
|
||||
RISK_MANUAL_CLOSE_DAILY_LIMIT=2
|
||||
# 日亏损次数上限:平仓盈亏<0 计1次;达限当日冻结开仓;0=不启用
|
||||
RISK_DAILY_LOSS_LIMIT=2
|
||||
RISK_MOOD_ISSUES_DAILY_FREEZE=true
|
||||
|
||||
# 资金与仓位刷新周期(秒)
|
||||
|
||||
@@ -404,7 +404,7 @@ KLINE_TIMEFRAME = os.getenv("KLINE_TIMEFRAME", "5m")
|
||||
_APP_STARTED_AT = time.time()
|
||||
_RECONCILE_FLAT_STREAK = {}
|
||||
FULL_MARGIN_BUFFER_RATIO = float(os.getenv("FULL_MARGIN_BUFFER_RATIO", "0.98"))
|
||||
TRANSFER_CCY = os.getenv("TRANSFER_CCY", "USDT")
|
||||
TRANSFER_CCY = (os.getenv("TRANSFER_CCY", "USDT") or "USDT").strip().upper() or "USDT"
|
||||
UPLOAD_FOLDER = resolve_path(os.getenv("UPLOAD_DIR", "static/images"))
|
||||
ORDER_CHART_ENABLED = os.getenv("ORDER_CHART_ENABLED", "true").lower() == "true"
|
||||
ORDER_CHART_TFS = [x.strip() for x in (os.getenv("ORDER_CHART_TFS", "4h,1h,15m,5m") or "").split(",") if x.strip()]
|
||||
@@ -2440,6 +2440,22 @@ def insert_trade_record(
|
||||
opened_at_ms=open_ts_ms,
|
||||
closed_at_ms=close_ts_ms,
|
||||
)
|
||||
# 中控只拉 /api/trade_records,平仓当下也尝试回填交易所盈亏(内部 25s 节流)
|
||||
try:
|
||||
sync_trade_records_from_exchange(conn, force=False)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
from lib.trade.account_risk_lib import on_closed_trade_pnl
|
||||
|
||||
close_dt = parse_dt_for_trading_day(close_ts)
|
||||
on_closed_trade_pnl(
|
||||
conn,
|
||||
pnl_amount=pnl_amount,
|
||||
trading_day=get_trading_day(close_dt),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return tid
|
||||
|
||||
|
||||
@@ -6942,7 +6958,11 @@ def sync_trade_records_from_exchange(conn, force=False):
|
||||
matched += 1
|
||||
stats["matched"] = matched
|
||||
stats["ok"] = True
|
||||
_LAST_EXCHANGE_PNL_SYNC_AT = now
|
||||
# 仍有未匹配且历史非空:缩短节流,避免平仓后历史稍晚入库时卡在「估」
|
||||
if matched < stats["pending"] and hist:
|
||||
_LAST_EXCHANGE_PNL_SYNC_AT = now - 15.0
|
||||
else:
|
||||
_LAST_EXCHANGE_PNL_SYNC_AT = now
|
||||
try:
|
||||
conn.commit()
|
||||
except Exception:
|
||||
@@ -7269,6 +7289,15 @@ def risk_policy_page():
|
||||
return render_main_page("risk_policy")
|
||||
|
||||
|
||||
@app.route("/system_guide")
|
||||
@login_required
|
||||
def system_guide_page():
|
||||
redir = redirect_to_embed_shell_if_enabled("system_guide")
|
||||
if redir is not None:
|
||||
return redir
|
||||
return render_main_page("system_guide")
|
||||
|
||||
|
||||
@app.route("/env_config")
|
||||
@login_required
|
||||
def env_config_page():
|
||||
@@ -9369,6 +9398,7 @@ register_trade_records_api(
|
||||
filter_trade_records_excluding_miss=filter_trade_records_excluding_miss,
|
||||
app_tz=APP_TZ,
|
||||
format_price_fn=format_price_for_symbol,
|
||||
sync_exchange_pnl_fn=lambda conn: sync_trade_records_from_exchange(conn, force=False),
|
||||
)
|
||||
|
||||
def _dashboard_enrich_orders(items):
|
||||
@@ -9697,7 +9727,7 @@ def manual_transfer():
|
||||
amount = float(request.form.get("amount", "0"))
|
||||
except Exception:
|
||||
flash("划转金额格式错误")
|
||||
return redirect("/settings")
|
||||
return redirect("/settings?settings_tab=transfer")
|
||||
from_account = (request.form.get("from_account") or AUTO_TRANSFER_FROM).strip()
|
||||
to_account = (request.form.get("to_account") or AUTO_TRANSFER_TO).strip()
|
||||
ok, msg, _ = execute_transfer_usdt(amount, from_account, to_account)
|
||||
@@ -9712,7 +9742,7 @@ def manual_transfer():
|
||||
flash(f"手动划转成功:{amount}U {from_account}->{to_account}")
|
||||
else:
|
||||
flash(f"手动划转失败:{msg}")
|
||||
return redirect("/settings")
|
||||
return redirect("/settings?settings_tab=transfer")
|
||||
|
||||
|
||||
def _journal_ai_chart_builder(row):
|
||||
|
||||
@@ -112,6 +112,8 @@ OKX_OPTIONS_ACCOUNT_LABEL=主账户·期权
|
||||
OKX_OPTIONS_TRADE_BUDGET_USDC=10
|
||||
OKX_OPTIONS_BUDGET_BUFFER=0.95
|
||||
OKX_OPTIONS_DEFAULT_UNDERLY=ETH
|
||||
# 期权链仅显示卖一深度≥1张的合约(估算卖一/无深度不显示);false 则显示全部
|
||||
OKX_OPTIONS_CHAIN_ASK_LIQ_FILTER_ENABLED=true
|
||||
OKX_OPTIONS_MAX_DTE_DAYS=2
|
||||
OKX_OPTIONS_CHAIN_MAX_DTE_DAYS=14
|
||||
OKX_SUB_ACCOUNT_NAME=
|
||||
@@ -120,19 +122,35 @@ OKX_OPTIONS_PROFIT_ALERT_RATIO=1.0
|
||||
OKX_OPTIONS_POLL_SECONDS=15
|
||||
OKX_OPTIONS_TD_MODE=isolated
|
||||
OKX_OPTIONS_ALLOW_MARKET_CLOSE=false
|
||||
# 对冲买期权等成交超时(秒);超时撤未成交部分,未完全成交则开仓失败
|
||||
OKX_OPTIONS_OPEN_FILL_TIMEOUT_SEC=12
|
||||
|
||||
# =============================================================================
|
||||
# 对冲计划(仅 OKX;前端 env「对冲计划」;详见 docs/对冲计划开发方案.md)
|
||||
# =============================================================================
|
||||
HEDGE_PLAN_ENABLED=false
|
||||
# 页面 Tab 显示(默认全部显示,可单独关闭;不影响已有进行中/历史计划)
|
||||
HEDGE_PLAN_SHOW_PERP_OPTIONS=true
|
||||
HEDGE_PLAN_SHOW_OPTIONS_OPTIONS=true
|
||||
HEDGE_PLAN_LIVE_ORDER=false
|
||||
HEDGE_PLAN_OPEN_ORDER=options_first
|
||||
HEDGE_PLAN_ON_PERP_SL_CLOSE_OPTIONS=true
|
||||
HEDGE_PLAN_ON_PERP_TP_CLOSE_OPTIONS=false
|
||||
HEDGE_PLAN_OO_CLOSE_WINNER_ONLY=true
|
||||
# 方案C:期期页面显示「平仓模式」(到期平/全平);关则固定到期平.默认开启,页面默认选全平
|
||||
HEDGE_PLAN_OO_CLOSE_MODE_ENABLED=true
|
||||
# 期期「做多/做空」拆分口径:budget=按权利金预算(默认);sheets=先算同张数总张数(2n)再按比例拆
|
||||
HEDGE_PLAN_OO_BIAS_SPLIT_BY=budget
|
||||
# 期期「做多/做空」主腿占比(0~1,默认 0.7=7:3);做多主腿=Call,做空主腿=Put
|
||||
HEDGE_PLAN_OO_BIAS_RATIO=0.7
|
||||
# 对冲与单独期权互斥(默认 true):有对冲计划不可单独开期权;有单独期权不可启动对冲;false=可同时开
|
||||
HEDGE_PLAN_OPTIONS_MUTUAL_EXCLUSIVE=true
|
||||
# 半腿失败改手动补开(默认 true):不自动平已成腿,计划挂 partial,页面补开;开启时下方自动平强制无效
|
||||
HEDGE_PLAN_MANUAL_COMPLETE_ON_PARTIAL=true
|
||||
MAX_ACTIVE_HEDGE_PLANS=1
|
||||
HEDGE_PLAN_MONITOR_POLL_SECONDS=15
|
||||
HEDGE_PLAN_PARTIAL_AUTO_CLOSE_OPTION=true
|
||||
# 半腿失败自动平期权;若 MANUAL_COMPLETE_ON_PARTIAL=true 则运行时强制无效(建议一并写成 false)
|
||||
HEDGE_PLAN_PARTIAL_AUTO_CLOSE_OPTION=false
|
||||
|
||||
# =============================================================================
|
||||
# 关键位程序自动下单(与 POSITION_SIZING_MODE 联动,修改后须重启 PM2)
|
||||
@@ -201,6 +219,8 @@ RISK_CONTROL_ENABLED=true
|
||||
RISK_COOLING_HOURS_MANUAL=4
|
||||
RISK_COOLING_HOURS_MANUAL_JOURNAL=1
|
||||
RISK_MANUAL_CLOSE_DAILY_LIMIT=2
|
||||
# 日亏损次数上限:平仓盈亏<0 计1次;达限当日冻结开仓;0=不启用
|
||||
RISK_DAILY_LOSS_LIMIT=2
|
||||
RISK_MOOD_ISSUES_DAILY_FREEZE=true
|
||||
|
||||
# 资金与仓位刷新周期(秒)
|
||||
|
||||
@@ -384,7 +384,7 @@ BREAKEVEN_EXCHANGE_MIN_INTERVAL_SEC = max(
|
||||
_BREAKEVEN_LAST_EX_SYNC: dict[int, float] = {}
|
||||
KLINE_TIMEFRAME = os.getenv("KLINE_TIMEFRAME", "5m")
|
||||
FULL_MARGIN_BUFFER_RATIO = float(os.getenv("FULL_MARGIN_BUFFER_RATIO", "0.98"))
|
||||
TRANSFER_CCY = os.getenv("TRANSFER_CCY", "USDT")
|
||||
TRANSFER_CCY = (os.getenv("TRANSFER_CCY", "USDT") or "USDT").strip().upper() or "USDT"
|
||||
OKX_POSITION_INST_TYPE = os.getenv("OKX_POSITION_INST_TYPE", "SWAP")
|
||||
EXCHANGE_POSITION_SYNC_FROM_BJ = (os.getenv("EXCHANGE_POSITION_SYNC_FROM_BJ") or "").strip()
|
||||
EXCHANGE_POSITION_HISTORY_LIMIT = max(50, min(1000, int(os.getenv("EXCHANGE_POSITION_HISTORY_LIMIT", "200"))))
|
||||
@@ -2359,6 +2359,22 @@ def insert_trade_record(
|
||||
opened_at_ms=open_ts_ms,
|
||||
closed_at_ms=close_ts_ms,
|
||||
)
|
||||
# 中控只拉 /api/trade_records,平仓当下也尝试回填交易所盈亏(内部 25s 节流)
|
||||
try:
|
||||
sync_trade_records_from_exchange(conn, force=False)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
from lib.trade.account_risk_lib import on_closed_trade_pnl
|
||||
|
||||
close_dt = parse_dt_for_trading_day(close_ts)
|
||||
on_closed_trade_pnl(
|
||||
conn,
|
||||
pnl_amount=pnl_amount,
|
||||
trading_day=get_trading_day(close_dt),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return tid
|
||||
|
||||
|
||||
@@ -4090,7 +4106,11 @@ def sync_trade_records_from_exchange(conn, force=False):
|
||||
matched += 1
|
||||
stats["matched"] = matched
|
||||
stats["ok"] = True
|
||||
_LAST_EXCHANGE_PNL_SYNC_AT = now
|
||||
# 仍有未匹配且历史非空:缩短节流,避免平仓后历史稍晚入库时卡在「估」
|
||||
if matched < stats["pending"] and hist:
|
||||
_LAST_EXCHANGE_PNL_SYNC_AT = now - 15.0
|
||||
else:
|
||||
_LAST_EXCHANGE_PNL_SYNC_AT = now
|
||||
try:
|
||||
conn.commit()
|
||||
except Exception:
|
||||
@@ -6785,8 +6805,20 @@ def render_main_page(page="trade", embed_mode=None):
|
||||
options_nav_visible=True,
|
||||
hedge_plan_enabled=os.getenv("HEDGE_PLAN_ENABLED", "false").lower() in ("1", "true", "yes", "on"),
|
||||
hedge_plan_nav_visible=os.getenv("HEDGE_PLAN_ENABLED", "false").lower() in ("1", "true", "yes", "on"),
|
||||
hedge_plan_show_perp_options=os.getenv("HEDGE_PLAN_SHOW_PERP_OPTIONS", "true").lower()
|
||||
in ("1", "true", "yes", "on"),
|
||||
hedge_plan_show_options_options=os.getenv("HEDGE_PLAN_SHOW_OPTIONS_OPTIONS", "true").lower()
|
||||
in ("1", "true", "yes", "on"),
|
||||
hedge_plan_oo_close_mode_enabled=os.getenv("HEDGE_PLAN_OO_CLOSE_MODE_ENABLED", "true").lower()
|
||||
in ("1", "true", "yes", "on"),
|
||||
hedge_plan_budget_buffer=float(os.getenv("HEDGE_PLAN_BUDGET_BUFFER") or "0.95"),
|
||||
options_trade_budget=OKX_OPTIONS_TRADE_BUDGET_USDC,
|
||||
options_budget_buffer=float(os.getenv("OKX_OPTIONS_BUDGET_BUFFER") or "0.95"),
|
||||
options_default_underly=OKX_OPTIONS_DEFAULT_UNDERLY,
|
||||
options_chain_ask_liq_filter=os.getenv(
|
||||
"OKX_OPTIONS_CHAIN_ASK_LIQ_FILTER_ENABLED", "true"
|
||||
).lower()
|
||||
in ("1", "true", "yes", "on"),
|
||||
risk_status=risk_status,
|
||||
max_active_positions=MAX_ACTIVE_POSITIONS,
|
||||
manual_min_planned_rr=MANUAL_MIN_PLANNED_RR,
|
||||
@@ -6806,6 +6838,7 @@ def render_main_page(page="trade", embed_mode=None):
|
||||
risk_status=risk_status,
|
||||
trade_policy=TRADE_POLICY,
|
||||
data_export_version=3,
|
||||
open_guard_enabled=open_guard_enabled,
|
||||
),
|
||||
**force_close_template_context(
|
||||
FORCE_CLOSE_ENABLED,
|
||||
@@ -6893,6 +6926,15 @@ def risk_policy_page():
|
||||
return render_main_page("risk_policy")
|
||||
|
||||
|
||||
@app.route("/system_guide")
|
||||
@login_required
|
||||
def system_guide_page():
|
||||
redir = redirect_to_embed_shell_if_enabled("system_guide")
|
||||
if redir is not None:
|
||||
return redir
|
||||
return render_main_page("system_guide")
|
||||
|
||||
|
||||
@app.route("/env_config")
|
||||
@login_required
|
||||
def env_config_page():
|
||||
@@ -9044,6 +9086,7 @@ register_trade_records_api(
|
||||
filter_trade_records_excluding_miss=filter_trade_records_excluding_miss,
|
||||
app_tz=APP_TZ,
|
||||
format_price_fn=format_price_for_symbol,
|
||||
sync_exchange_pnl_fn=lambda conn: sync_trade_records_from_exchange(conn, force=False),
|
||||
)
|
||||
|
||||
|
||||
@@ -9412,7 +9455,7 @@ def manual_transfer():
|
||||
amount = float(request.form.get("amount", "0"))
|
||||
except Exception:
|
||||
flash("划转金额格式错误")
|
||||
return redirect("/settings")
|
||||
return redirect("/settings?settings_tab=transfer")
|
||||
from_account = (request.form.get("from_account") or AUTO_TRANSFER_FROM).strip()
|
||||
to_account = (request.form.get("to_account") or AUTO_TRANSFER_TO).strip()
|
||||
ok, msg, _ = execute_transfer_usdt(amount, from_account, to_account)
|
||||
@@ -9434,7 +9477,7 @@ def manual_transfer():
|
||||
flash(f"手动划转成功:{amount}U {from_account}->{to_account}")
|
||||
else:
|
||||
flash(f"手动划转失败:{msg}")
|
||||
return redirect("/settings")
|
||||
return redirect("/settings?settings_tab=transfer")
|
||||
|
||||
|
||||
def _journal_ai_chart_builder(row):
|
||||
|
||||
@@ -0,0 +1,262 @@
|
||||
# 标的时段振幅统计 — 开发方案
|
||||
|
||||
> 状态:**方案冻结**(按本文实现;改需求先改本文).
|
||||
> 范围:**中控**新增只读统计工具;不改开平仓、不接 AI 教练(首版).
|
||||
> 数据源:**仅 OKX**.
|
||||
> 相关:[交易执行手册-期权与Gate.md](./交易执行手册-期权与Gate.md)(16:00 会话窗纪律) · [振幅统计说明.md](./振幅统计说明.md)
|
||||
|
||||
---
|
||||
|
||||
## 1. 目标
|
||||
|
||||
在中控提供 **自定义时段、固定 16:00 收窗** 的历史振幅档案:
|
||||
|
||||
- **标的下拉**:`ETH` / `BTC`(默认 ETH)
|
||||
- 按整点起点 + **终点固定北京时间 16:00** 切出每日统计窗
|
||||
- 回溯周期可选(1 月 / 2 月 / 3 月 / 半年 / 1 年 / 自定义)
|
||||
- 日表明细分页展示;下方为汇总统计
|
||||
- 每次有效计算可写入 **历史**;支持 **下载**(明细 + 统计摘要)
|
||||
|
||||
定位:服务一天期期权开仓前的「空间」判断(已实现波动点数档案),**不算 IV / 权利金 / Greeks**.
|
||||
|
||||
---
|
||||
|
||||
## 2. 不做(首版外)
|
||||
|
||||
- 币安 / Gate 等非 OKX 价源
|
||||
- 百分比振幅列(可后加「参考 %」,不进必须统计)
|
||||
- 未完成窗(当天尚未到 16:00)计入样本
|
||||
- 自动推送企业微信 / 注入交易教练
|
||||
- 中控代下单或改期权仓
|
||||
|
||||
---
|
||||
|
||||
## 3. 时间与样本规则
|
||||
|
||||
### 3.1 时区与终点
|
||||
|
||||
- 时区:**Asia/Shanghai(北京时间)**
|
||||
- **到期/收窗时刻固定 `16:00`**,不可改
|
||||
- 起点时刻:**仅整点** `00:00`~`23:00`(下拉选择)
|
||||
|
||||
### 3.2 跨天切窗(结算日 D)
|
||||
|
||||
对每个结算日 **D**(窗终点 = `D 日 16:00`):
|
||||
|
||||
| 起点整点 T | 窗起点 | 窗终点 |
|
||||
|------------|--------|--------|
|
||||
| `T >= 16:00` | **D-1 日 T:00** | D 日 16:00 |
|
||||
| `T < 16:00` | **D 日 T:00** | D 日 16:00 |
|
||||
|
||||
示例:
|
||||
|
||||
| 用户选择 | 某一结算日 D 的实际窗 |
|
||||
|----------|------------------------|
|
||||
| 16:00 → 16:00 | D-1 16:00 → D 16:00 |
|
||||
| 22:00 → 16:00 | D-1 22:00 → D 16:00 |
|
||||
| 08:00 → 16:00 | D 08:00 → D 16:00 |
|
||||
|
||||
### 3.3 回溯周期
|
||||
|
||||
| 选项 | 含义(完整收窗个数,约) |
|
||||
|------|------------------------|
|
||||
| 1 个月 | 约 30 个结算日 |
|
||||
| 2 个月 | 约 60 个结算日(默认推荐) |
|
||||
| 3 个月 | 约 90 个结算日 |
|
||||
| 半年 | 约 180 个结算日 |
|
||||
| 1 年 | 约 365 个结算日 |
|
||||
| 自定义 | 用户输入天数 N(`7`~`400`,可配置上下限) |
|
||||
|
||||
说明:
|
||||
|
||||
- 「月」按 **日历回溯 + 完整 16:00 收窗** 计数,不足整天的末日不入样
|
||||
- 仅纳入 **已结束** 的窗(`now >= D 16:00`);进行中的今天不入样
|
||||
|
||||
### 3.4 标的与价源(OKX)
|
||||
|
||||
| UI 下拉 | 价源(优先) | 降级(仅指数失败时) |
|
||||
|---------|------------|---------------------|
|
||||
| **ETH** | OKX **ETH-USD 指数** | OKX `ETH/USDT` 永续标记 |
|
||||
| **BTC** | OKX **BTC-USD 指数** | OKX `BTC/USDT` 永续标记 |
|
||||
|
||||
约束:
|
||||
|
||||
- **交易所固定 OKX**,UI 不提供其它所
|
||||
- 具体指数/合约符号以实现时 OKX 接口与 `hub_ohlcv` 对齐为准;结果与下载须标注 `exchange=okx` + 实际价源
|
||||
- K 线粒度:**1H**(与整点起止对齐,优先);同一作业内不得混用粒度.若后续要更细高低点,可升 5m/1m(P2)
|
||||
|
||||
---
|
||||
|
||||
## 4. 指标口径(点数,非百分比)
|
||||
|
||||
全部为 **绝对价格点数**(标的报价差;BTC/ETH 各自用自身价格刻度).
|
||||
|
||||
设窗内:
|
||||
|
||||
- `O` = 起点时刻价(或起点分钟 K 的 open)
|
||||
- `H` = 窗内最高
|
||||
- `L` = 窗内最低
|
||||
- `C` = 终点 16:00 价(或该分钟 close)
|
||||
|
||||
| 字段 | 算法 | 例(O=2000,H=2500,L=1800) |
|
||||
|------|------|---------------------------|
|
||||
| 开盘价 | `O` | 2000 |
|
||||
| 最高价 | `H` | 2500 |
|
||||
| 最低价 | `L` | 1800 |
|
||||
| 收盘/窗末价 | `C` | (另算) |
|
||||
| 开→高距离 | `H − O` | **500** |
|
||||
| 开→低距离 | `O − L` | **200** |
|
||||
| **振幅** | `(H−O)+(O−L)` = **`H−L`** | **700** |
|
||||
| 涨跌值 | `C − O`(可正负) | 可选列,首版建议保留 |
|
||||
|
||||
**必须统计(汇总层):**
|
||||
|
||||
- **最大振幅**(值 + 对应结算日)
|
||||
- **开→高距离**:最大、均值(建议)
|
||||
- **开→低距离**:最大、均值(建议)
|
||||
|
||||
可选汇总(首版建议带上,成本低):
|
||||
|
||||
- 振幅均值 / 中位数
|
||||
- 上涨窗占比(`C>O`)、下跌窗占比
|
||||
- 振幅 ≥ 用户阈值 X 点数的天数(X 可填,默认空=不算)
|
||||
|
||||
---
|
||||
|
||||
## 5. 界面(中控)
|
||||
|
||||
### 5.1 入口
|
||||
|
||||
- 顶栏新增导航项:**「振幅统计」**或 **「期权统计」**(最终文案实现时定一处;设置里可隐藏)
|
||||
- 手机端进「更多」
|
||||
|
||||
### 5.2 Tab
|
||||
|
||||
| Tab | 作用 |
|
||||
|-----|------|
|
||||
| **统计** | 配参数 → 计算 → 看日表+汇总 → 下载 / 存历史 |
|
||||
| **历史** | 过往作业列表;打开复看;再下载 |
|
||||
|
||||
### 5.3 「统计」页布局
|
||||
|
||||
1. **参数区**
|
||||
- **标的**:下拉 `ETH` / `BTC`(默认 ETH)
|
||||
- 数据源:只读展示 `OKX`
|
||||
- 起点整点:下拉 `00`~`23`(默认 `16`)
|
||||
- 终点:固定展示 `16:00`(不可改)
|
||||
- 周期:单选 `1月 / 2月 / 3月 / 半年 / 1年 / 自定义`
|
||||
- 自定义天数:仅自定义时显示
|
||||
- 按钮:`计算` · `保存到历史` · `下载`
|
||||
2. **日表明细**(分页,如每页 20 行;排序默认结算日倒序)
|
||||
3. **下方汇总区**(本次全样本,不是当前页)
|
||||
|
||||
### 5.4 「历史」页
|
||||
|
||||
每条记录至少:
|
||||
|
||||
- 创建时间、**标的**、起点整点、周期/天数、价源(OKX+指数/标记)、样本数
|
||||
- 最大振幅(+日期)
|
||||
- 操作:查看 / 下载 / 删除
|
||||
|
||||
**写入规则(建议):** 用户点击 **「保存到历史」** 才入库;仅点「计算」不自动灌历史(避免误点刷屏).若产品坚持「输入一次就算进历史」,可改为计算成功自动写入——实现前在本文改为冻结口径.
|
||||
|
||||
> 当前方案冻结倾向:**显式「保存到历史」**.
|
||||
|
||||
---
|
||||
|
||||
## 6. 下载
|
||||
|
||||
格式:优先 **CSV**(UTF-8 BOM,Excel 可开);或单文件双段.
|
||||
|
||||
必须包含:
|
||||
|
||||
1. **日表明细**(本次全部结算日,非当前页)
|
||||
2. **统计摘要**:标的、交易所 OKX、价源、最大振幅(+日)、开→高最大/均值、开→低最大/均值、样本数、起点整点、终点 16:00、周期、生成时间
|
||||
|
||||
文件名示例:`okx_eth_amp_22to16_60d_20260723.csv` / `okx_btc_amp_16to16_90d_20260723.csv`
|
||||
|
||||
---
|
||||
|
||||
## 7. 数据与实现要点
|
||||
|
||||
### 7.1 复用
|
||||
|
||||
- 优先复用中控 `hub_ohlcv` / `hub_kline_store`,按 `exchange_key=okx` + 标的对应指数/合约拉齐历史 K 线并本地缓存
|
||||
- 首次 1 年 × 1m 数据量较大:计算前检查缓存覆盖;缺口再增量拉取;UI 显示进度/耗时提示
|
||||
- BTC / ETH 缓存键分离
|
||||
|
||||
### 7.2 后端模块(建议)
|
||||
|
||||
| 路径 | 职责 |
|
||||
|------|------|
|
||||
| `lib/hub/amp_stats_lib.py` | 标的映射、切窗、算日行、汇总 |
|
||||
| `manual_trading_hub/` 路由 + 静态页 | UI / API |
|
||||
| `manual_trading_hub/amp_stats_history.json`(或 sqlite) | 历史作业 |
|
||||
|
||||
### 7.3 API 草稿
|
||||
|
||||
| 方法 | 路径 | 说明 |
|
||||
|------|------|------|
|
||||
| `POST` | `/api/amp-stats/compute` | body: `symbol`(eth\|btc), start_hour, period\|days → 日表+汇总 |
|
||||
| `GET` | `/api/amp-stats/history` | 历史列表(可按 symbol 筛选) |
|
||||
| `POST` | `/api/amp-stats/history` | 保存当前结果 |
|
||||
| `GET` | `/api/amp-stats/history/{id}` | 详情 |
|
||||
| `DELETE` | `/api/amp-stats/history/{id}` | 删除 |
|
||||
| `GET` | `/api/amp-stats/export` | query 或 history id → 文件下载 |
|
||||
|
||||
### 7.4 性能
|
||||
|
||||
- 2 个月 × 1m:可接受同步(数十秒级需有 loading)
|
||||
- 1 年:建议异步任务或分块拉齐后再算;首版可限制「自定义 > 180 天」需确认二次点击
|
||||
|
||||
---
|
||||
|
||||
## 8. 验收清单
|
||||
|
||||
- [ ] 标的下拉 ETH / BTC 可切换;数据源固定 OKX
|
||||
- [ ] 起点仅整点;终点 UI 固定 16:00
|
||||
- [ ] `22→16` / `16→16` / `08→16` 跨天规则与 §3.2 一致
|
||||
- [ ] 周期六档 + 自定义天数生效;默认 2 个月
|
||||
- [ ] 日表含:开高低收、开→高、开→低、振幅(点数)、涨跌值
|
||||
- [ ] 例:O=2000,H=2500,L=1800 → 开→高 500、开→低 200、振幅 700
|
||||
- [ ] 汇总含最大振幅(+日)、开→高/开→低统计
|
||||
- [ ] 分页只影响展示;汇总与下载用全样本
|
||||
- [ ] 未到 16:00 的当日不入样
|
||||
- [ ] 保存历史含标的字段 / 回看 / 删除
|
||||
- [ ] 下载含明细 + 统计摘要(含标的与 OKX)
|
||||
- [ ] 电脑与手机均可完成计算与下载(手机下载走系统分享/保存即可)
|
||||
|
||||
---
|
||||
|
||||
## 9. 分期
|
||||
|
||||
| 阶段 | 内容 |
|
||||
|------|------|
|
||||
| **P0** | 统计 Tab:标的下拉(ETH/BTC) + 参数 + 计算 + 日表分页 + 汇总 + 下载(不经历史) |
|
||||
| **P1** | 历史 Tab:保存 / 列表 / 回看 / 再下载 / 删除 |
|
||||
| **P2** | 缓存加速、长周期异步、振幅阈值天数、可选 % 参考列 |
|
||||
|
||||
---
|
||||
|
||||
## 10. 待冻结(实现前确认)
|
||||
|
||||
| # | 问题 | 当前倾向 |
|
||||
|---|------|----------|
|
||||
| 1 | 历史写入:自动 vs 点保存 | **点保存** |
|
||||
| 2 | 下载 CSV vs Excel | **CSV** |
|
||||
| 3 | 价源 | **OKX 指数优先**(ETH-USD / BTC-USD);失败再降级永续标记 |
|
||||
| 4 | K 线 1m vs 5m vs 1H | **1H**(整点窗) |
|
||||
| 5 | 导航文案 | **「振幅统计」** |
|
||||
|
||||
**已冻结(开工口径):** 点保存进历史 · CSV · OKX 指数优先 · **1H K 线**(整点对齐,降低拉取量;与整点窗一致) · 导航「振幅统计」.
|
||||
|
||||
确认后将本文状态改为 **方案冻结**,再开工实现.
|
||||
|
||||
---
|
||||
|
||||
## 11. 修订记录
|
||||
|
||||
| 日期 | 说明 |
|
||||
|------|------|
|
||||
| 2026-07-23 | 初稿:中控 ETH 时段振幅统计;点数口径;周期档位;16:00 固定收窗;历史+下载 |
|
||||
| 2026-07-23 | 支持 BTC/ETH 下拉;数据源固定 OKX 指数(可降级永续标记);模块/API 改名为 amp-stats |
|
||||
@@ -41,6 +41,7 @@
|
||||
|------|------|
|
||||
| 第 1 次用户主动平仓 | 默认 **4h** 冷静期 |
|
||||
| 第 2 次用户主动平仓(同一交易日) | **日冻结** |
|
||||
| 平仓亏损达 `RISK_DAILY_LOSS_LIMIT` 次(同一交易日) | **日冻结**(默认 2 次;`0`=不启用) |
|
||||
| 复盘勾选任意情绪标签 | **日冻结** |
|
||||
| 复盘:离场=手动平仓 且说明非空 | 将当前冷静期降为 **1h**(须处于 4h 档冷静期中) |
|
||||
|
||||
@@ -77,11 +78,15 @@ RISK_CONTROL_ENABLED=true
|
||||
RISK_COOLING_HOURS_MANUAL=4
|
||||
RISK_COOLING_HOURS_MANUAL_JOURNAL=1
|
||||
RISK_MANUAL_CLOSE_DAILY_LIMIT=2
|
||||
RISK_DAILY_LOSS_LIMIT=2
|
||||
RISK_MOOD_ISSUES_DAILY_FREEZE=true
|
||||
TRADING_DAY_RESET_HOUR=8
|
||||
APP_TIMEZONE=Asia/Shanghai
|
||||
```
|
||||
|
||||
- `RISK_DAILY_LOSS_LIMIT`:任意已平仓交易若盈亏 < 0 计 1 次(含止损/止盈后仍亏损等);达上限当日冻结开仓;`0` 表示不因亏损次数冻结.
|
||||
- `RISK_MANUAL_CLOSE_DAILY_LIMIT`:仅计**用户主动平仓**次数(与亏损次数独立).
|
||||
|
||||
`RISK_COOLING_HOURS_EXTERNAL` 已废弃(外部平仓不再触发风控).
|
||||
|
||||
## API 与 `risk_status` 字段
|
||||
@@ -102,6 +107,7 @@ APP_TIMEZONE=Asia/Shanghai
|
||||
| `can_trade` | 是否允许新开仓(仅风控维度) |
|
||||
| `reason` | 悬停提示文案 |
|
||||
| `active_count` / `max_active_positions` | 当前活跃持仓与 `.env` 中 `MAX_ACTIVE_POSITIONS` |
|
||||
| `daily_loss_count` / `daily_loss_limit` | 当日亏损笔数与上限(`0` 上限表示未启用) |
|
||||
| `cooloff_until_ms` | 1h/4h 冷静期结束时间戳(毫秒) |
|
||||
| `freeze_until_ms` | 倒计时结束时间戳(日冻结为下一交易日切点) |
|
||||
| `freeze_remaining_sec` | 服务端计算的剩余秒数(供调试) |
|
||||
@@ -123,7 +129,7 @@ APP_TIMEZONE=Asia/Shanghai
|
||||
|
||||
## 相关代码
|
||||
|
||||
- `account_risk_lib.py` — 状态机,`enrich_risk_status_countdown`,`apply_position_limit_risk`,`on_user_initiated_close`
|
||||
- `account_risk_lib.py` — 状态机,`enrich_risk_status_countdown`,`apply_position_limit_risk`,`on_user_initiated_close`,`on_closed_trade_pnl`
|
||||
- `hub_bridge.py` — `/api/hub/account-risk/user-close`
|
||||
- `manual_trading_hub/hub.py` — 中控平仓成功后调用 user-close
|
||||
- `strategy_trend_register.py` — `stop_trend_pullback` 结束计划时登记风控
|
||||
|
||||
@@ -131,6 +131,7 @@ AI 相关环境变量(`AI_PROVIDER`,`OPENAI_*`,`OLLAMA_*`,`AI_MODEL`,`AI_TIMEOUT
|
||||
| 手动平仓冷静(小时) | |
|
||||
| 复盘情绪冷静(小时) | |
|
||||
| 日手动平仓次数上限 | |
|
||||
| 日亏损次数上限 | 默认2;达限当日冻结开仓;0=不启用 |
|
||||
| 情绪标签日冻结 | |
|
||||
|
||||
详见 [account-risk-cooldown.md](./account-risk-cooldown.md).
|
||||
|
||||
@@ -4,6 +4,15 @@
|
||||
|
||||
「内照明心」页(`/archive`)用于 **复盘语录 + 交易记录回顾 + 按需 K 线**.左侧维护每日复盘语录(最多 100 条);右侧按日期区间列出开仓记录,展示区间统计,并可展开 K 线图表对照单笔交易.
|
||||
|
||||
顶栏有 **永续 / 期权** 品种切换:
|
||||
|
||||
| 品种 | 数据 | 说明 |
|
||||
|------|------|------|
|
||||
| **永续** | 三所 `trade_records` → `archive_trade_cache` | 含犯病标签、K 线 |
|
||||
| **期权** | OKX `options_review_trades` → `archive_options_trade_cache` | 独立 Tab;同步进中控库后离线可看;默认排除对冲腿 |
|
||||
|
||||
同步:「同步」按钮与后台 4h 任务会同时拉永续与期权(仅 `capabilities` 含 `options` 的账户).
|
||||
|
||||
与行情区 `hub_kline.db`(15 天滚动缓存)**完全独立**:档案库只增不删,从建档起永久保留.
|
||||
|
||||
## 页面布局
|
||||
|
||||
@@ -4,6 +4,9 @@
|
||||
|
||||
| 文档 | 实例 | 状态 |
|
||||
|------|------|------|
|
||||
| [交易执行手册-v2-期权与合约.md](../交易执行手册-v2-期权与合约.md) | 中控「策略说明」·执行手册v2 | **现行**:无对冲;1H→空间→结构→定损盈→期权/合约 |
|
||||
| [交易执行手册-期权与Gate.md](../交易执行手册-期权与Gate.md) | 中控「策略说明」·执行手册v1 | 含对冲;历史对照 |
|
||||
| [交易行为准则-开单三检.md](../交易行为准则-开单三检.md) | 中控「策略说明」·行为准则 | 开单前信号/流程/情绪三检 |
|
||||
| [binance-alt-trend-long.md](./binance-alt-trend-long.md) | 币安山寨·多头趋势 | v0.4 讨论稿 |
|
||||
| [okx-trend-both.md](./okx-trend-both.md) | OKX·多空趋势 | v0.4 讨论稿 |
|
||||
| [gate-intraday.md](./gate-intraday.md) | Gate·BTC 日内 | v0.2 |
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
{
|
||||
"exchange": "behavior",
|
||||
"title": "开单三检清单",
|
||||
"version": "v0.1",
|
||||
"groups": [
|
||||
{
|
||||
"title": "信号判断",
|
||||
"items": [
|
||||
"最核心、最明确的一个点位/结构确认已写清",
|
||||
"该确认本身足够清晰(不是靠一长串宏大叙事)",
|
||||
"已过主链条:1H方向 → 空间 → 结构 → 定损盈 → 选工具(期权/合约,无对冲);不够格则空仓"
|
||||
]
|
||||
},
|
||||
{
|
||||
"title": "流程确认",
|
||||
"items": [
|
||||
"账户资金与当日额度符合要求",
|
||||
"单笔风险 / 组合敞口在手册预算内",
|
||||
"无跳步;超限则暂停开单"
|
||||
]
|
||||
},
|
||||
{
|
||||
"title": "情绪自检",
|
||||
"items": [
|
||||
"心态是「符合系统所以做」,不是「证明自己」",
|
||||
"无怕踏空 → 否则放弃",
|
||||
"无回本 / 报复交易念头 → 否则放弃",
|
||||
"不需要再找更多开单理由"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
{
|
||||
"exchange": "playbook_v2",
|
||||
"title": "执行手册 v2 开仓清单(无对冲)",
|
||||
"version": "v0.1",
|
||||
"groups": [
|
||||
{
|
||||
"title": "主链条",
|
||||
"items": [
|
||||
"1H 方向清楚(含明显 N 字);跟的是 1H 波段",
|
||||
"空间足够(支撑/阻力;至少约 ≥2%)",
|
||||
"结构已出现且量级够(约 8h+ / 48 根 15m)",
|
||||
"止损按模型:结构突破=外沿;假突破=针尖;止盈与 RR 已接受",
|
||||
"工具只在「期权 / 合约」中选择;未开对冲"
|
||||
]
|
||||
},
|
||||
{
|
||||
"title": "账户与仓位",
|
||||
"items": [
|
||||
"只动 OKX 期权或 Gate 合约;其它账户零操作",
|
||||
"期权:约 10U、一次一仓;合约:止损约 5U、本位置次数未超两次",
|
||||
"合计最坏风险可接受(约 ≤20U 量级)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"title": "离场与心态",
|
||||
"items": [
|
||||
"期权离场只认规则止盈或到期;开仓后中间不手平",
|
||||
"不是「今天也要开点期权」;过检才开,不过则空仓",
|
||||
"已过开单三检(信号 / 流程 / 情绪)"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
# 交易执行手册 v2(期权 / 合约 · 无对冲)
|
||||
|
||||
> 个人开单纪律第二版(2026-07-24 起)。
|
||||
> **相对 v1:去掉期期对冲 / 偏置对冲;工具只留期权与合约。**
|
||||
> 目标:少而精、珍惜机会、样本干净;**不保证收益**。
|
||||
> 旧版(含对冲)见 [交易执行手册-期权与Gate.md](./交易执行手册-期权与Gate.md)。
|
||||
> **开单前先过** [交易行为准则-开单三检.md](./交易行为准则-开单三检.md);本手册管怎么做单。
|
||||
|
||||
---
|
||||
|
||||
## 1. 主链条(强制)
|
||||
|
||||
```
|
||||
1H 方向 → 空间 → 结构 → 定损盈 → 选工具(期权 / 合约)
|
||||
```
|
||||
|
||||
任一步不过 → **空仓等待**,不为开单找理由。
|
||||
|
||||
| 步骤 | 做什么 | 否决 |
|
||||
|------|--------|------|
|
||||
| **1H 方向** | 趋势周期以 **1H** 为准;1H 上要有明显 **N 字**。跟 1H 波段,不跟 4H 打架硬做。例:4H 多、1H 空 → 做 1H 空头波段 | 1H 方向不清、无 N 字 |
|
||||
| **空间** | 做空看下方支撑,做多看上方阻力;至少约 **≥2%** 才值得谈(常期望更大空间,如 ~5%) | 空间不够、贴着墙 |
|
||||
| **结构** | 方向与空间过关后,在 **15m / 5m** 等结构;结构量级至少约 **8h+**(约 **48 根 15m**)。形态:收敛 / 两段式回调 / 箱体 / 假突破等 | 结构未出现、磨不够就抢跑 |
|
||||
| **定损盈** | 结构出现后定义止损、止盈,算盈亏比。结构突破 → 止损在 **结构外沿**;假突破 → 止损在 **假突破针尖** | 损盈说不清、RR 不接受 |
|
||||
| **选工具** | 只在上四步都齐之后选:**期权** 或 **合约**。波段有足够时间考虑,不急着下手 | 用对冲、或「每天都要开点期权」 |
|
||||
|
||||
**丢掉对冲。** 对冲易带来「有保护就能多做」的幻觉;本版不做期期对冲、不做偏置对冲壳。
|
||||
|
||||
---
|
||||
|
||||
## 2. 总原则
|
||||
|
||||
1. **工具只有期权与合约**;同一时段尽量只让一边「说话」。
|
||||
2. **看不懂不做**;过滤比频率重要。日更不是目标,过检才是。
|
||||
3. 动手前先过 **开单三检**(信号 → 流程 → 情绪);不过 → 空仓。
|
||||
4. 玩法必须走完主链条;不够格 → 空仓。
|
||||
5. 期权离场只认:**系统/规则止盈** 与 **到期**;**开仓后中间不手动平仓**(紧急例外不进策略样本)。
|
||||
6. 过程可控、结果随缘:用规则管仓位与次数,不追求每天打满。
|
||||
|
||||
---
|
||||
|
||||
## 3. 账户与分工
|
||||
|
||||
| 账户 | 角色 | 说明 |
|
||||
|------|------|------|
|
||||
| OKX 期权 | **主业之一** | 方向单(虚值等);**不做对冲腿** |
|
||||
| Gate 合约 | **主业之一** | 结构清楚时的波段;与期权尽量错开 |
|
||||
| 其它 | 暂不做 | 减少分心与样本污染 |
|
||||
|
||||
**到期选择(期权)**
|
||||
|
||||
- 方向单默认 **一天期**。
|
||||
- 尽量在 **北京时间下午 4 点后** 开 **次日到期**,覆盖较完整的美盘 + 亚盘 + 欧盘窗口。
|
||||
- 更长故事优先考虑合约,不强行拉长期权。
|
||||
|
||||
---
|
||||
|
||||
## 4. 入场逻辑(两类工具)
|
||||
|
||||
开仓前先判断:当前是 **买方向的期权表达**,还是 **合约波段**。
|
||||
|
||||
### 4.1 方向明确 · 结构到位 → 期权
|
||||
|
||||
- **条件**:主链条全部过关;常用结构突破或假突破模型在 15m/5m 成立。
|
||||
- **工具**:**一天期期权方向单**(空间够时优先考虑 **虚值**:同止损口径下盈亏比往往更高)。
|
||||
- **离场**:规则止盈或到期;不手平。
|
||||
- **默认**:先只开期权,不上合约。
|
||||
|
||||
### 4.2 结构到位 · 更适合合约 → 合约
|
||||
|
||||
- **条件**:主链条过关;位置极明确;同一位置机会计数见 Gate 纪律。
|
||||
- **工具**:Gate 合约波段;止损挂在模型对应位置(外沿 / 针尖)。
|
||||
- **独立假突破**(没有先开突破期权时):优先 **只做合约** 或 **空仓**,勿与「突破期权后再加仓」混用同一套仓。
|
||||
|
||||
### 4.3 明确不做
|
||||
|
||||
- 横盘「买波动」的 **期期对冲**(Call+Put)。
|
||||
- 任何「对冲壳 + 偏置」伪装成单边。
|
||||
- 为了「今天也开点期权」而破主链条。
|
||||
|
||||
---
|
||||
|
||||
## 5. 仓位与风险预算
|
||||
|
||||
**总资金参考:约 800U。**
|
||||
|
||||
| 项目 | 规则 |
|
||||
|------|------|
|
||||
| 单笔期权 | 约 **10U** 权利金预算;**一次只持有一个期权仓位** |
|
||||
| Gate 合约 | 日内保证金约 **50U**、约 **10 倍**;有单才用,无单为 0 |
|
||||
| 合约止损 | 一般约 **5U**;单笔最大亏损不超过约 **10U** |
|
||||
| 日损失心理框 | 期权+合约若都错:合计大约 **≤20U**;都对时期望可到 **40U+**(理想情形,非每日目标) |
|
||||
|
||||
相对 800U:单笔约 **1.25%** 量级;全错一天约 **2.5%** 量级——防守优先。
|
||||
|
||||
**叠加红线**
|
||||
|
||||
- 期权一仓 + 合约同日存在时,按合计风险接受最坏约 20U,且尽量少「同向双开」。
|
||||
- 不为「好像有保护」放大仓位(本版已无对冲保护叙事)。
|
||||
|
||||
---
|
||||
|
||||
## 6. 合约日纪律(Gate)
|
||||
|
||||
1. 只做 **很明确的位置**;不明确基本不做。
|
||||
2. 动手前想清:**如何进场**(假突破 / 结构突破)。
|
||||
3. **同一位置最多两次机会**:结构突破、假突破。
|
||||
4. **两次都错 → 当日不再做单**(即使后面更「看起来清楚」也留到明天)。
|
||||
5. 止损约 **5U**;波段规则开仓前想清。
|
||||
6. 离场以结构止盈/止损为准。
|
||||
|
||||
---
|
||||
|
||||
## 7. 期权日纪律(OKX)
|
||||
|
||||
1. **不手动平仓**;只等规则止盈或到期(紧急手平标记为非策略样本)。
|
||||
2. 一次一仓;约 10U 权利金。
|
||||
3. **不做对冲**;不做「每天默认开期权」。
|
||||
4. 结构突破 / 假突破用期权表达时,损位跟模型:外沿 / 针尖。
|
||||
5. 默认一天期;优先完整会话窗口再开。
|
||||
|
||||
---
|
||||
|
||||
## 8. 开仓前自检清单
|
||||
|
||||
- [ ] 今天是否只动「期权 / 合约」,其它账户零操作?是否 **未开对冲**?
|
||||
- [ ] **1H 方向**是否清楚(含 N 字)?
|
||||
- [ ] **空间**是否足够(支撑/阻力,至少约 ≥2%)?
|
||||
- [ ] **结构**是否出现且量级够(约 8h+ / 48×15m)?
|
||||
- [ ] **止损 / 止盈**是否按模型定好(外沿或针尖)?RR 是否接受?
|
||||
- [ ] **工具**选的是期权还是合约?理由是否写清?
|
||||
- [ ] 期权:止盈条件与「接受到期」是否写清?
|
||||
- [ ] 合约:本位置第几次机会?止损约 5U 设好了吗?今日两次是否已用完?
|
||||
|
||||
---
|
||||
|
||||
## 9. 一句话版本
|
||||
|
||||
> **1H 定方向 → 量空间 → 等够级别的结构 → 按模型定损盈 → 只在期权与合约里选工具;不对冲;期权不手平;一位置两次,错完收工;珍惜机会,日更不是目标。**
|
||||
|
||||
---
|
||||
|
||||
## 10. 修订记录
|
||||
|
||||
| 日期 | 说明 |
|
||||
|------|------|
|
||||
| 2026-07-24 | v2 初版:去掉对冲;主链条 1H→空间→结构→定损盈→期权/合约;吸收假突破针尖 / 结构外沿止损口径 |
|
||||
@@ -0,0 +1,149 @@
|
||||
# 交易执行手册 v1(期权为主 · Gate 为辅 · 含对冲)
|
||||
|
||||
> 个人开单纪律与仓位规则(2026-07 起)。**本版保留对冲,仅作历史/对照。**
|
||||
> **现行主版本请用** [交易执行手册-v2-期权与合约.md](./交易执行手册-v2-期权与合约.md)(无对冲:1H→空间→结构→定损盈→期权/合约)。
|
||||
> 目标:少而精、可控回撤、样本干净;**不保证收益**。
|
||||
> 工具:OKX 期权(主)+ Gate 合约(辅);其它账户暂不做。
|
||||
> **开单前先过** [交易行为准则-开单三检.md](./交易行为准则-开单三检.md)(信号 / 流程 / 情绪);本手册管怎么做单。
|
||||
---
|
||||
|
||||
## 1. 总原则
|
||||
|
||||
1. **主做期权,合约为辅**;同一时段尽量只让一边「说话」。
|
||||
2. **看不懂不做**;过滤比频率重要。
|
||||
3. 动手前先过 **开单三检**(信号判断 → 流程确认 → 情绪自检);不过 → 空仓。详见 [行为准则](./交易行为准则-开单三检.md)。
|
||||
4. 开仓前再过玩法三关:**方向 → 空间 → 值不值得**。不够格 → 空仓。
|
||||
5. 期权离场只认:**止盈(规则触发)** 与 **到期**;**不手动平仓**(紧急例外单不算策略样本)。
|
||||
6. 过程可控、结果随缘:用规则管仓位与次数,不追求每天打满理想上限。
|
||||
|
||||
---
|
||||
|
||||
## 2. 账户与分工
|
||||
|
||||
| 账户 | 角色 | 说明 |
|
||||
|------|------|------|
|
||||
| OKX 期权 | **主业** | 横盘对冲 / 方向单 / 偏置对冲 |
|
||||
| Gate 合约 | **辅业** | 结构清楚时的波段;与期权尽量错开 |
|
||||
| 其它 | 暂不做 | 减少分心与样本污染 |
|
||||
|
||||
**到期选择(期权)**
|
||||
|
||||
- 方向单、对冲默认 **一天期**。
|
||||
- 尽量在 **北京时间下午 4 点后** 开 **次日到期**,覆盖较完整的美盘 + 亚盘 + 欧盘窗口。
|
||||
- Gate 波段样本里最长持仓约十余小时量级 → 一天期权通常够表达;更长故事优先考虑合约,不强行拉长期权。
|
||||
|
||||
---
|
||||
|
||||
## 3. 入场逻辑(三类)
|
||||
|
||||
开仓前先判断:当前是 **买波动** 还是 **买方向**。
|
||||
|
||||
### 3.1 横盘 → 期期对冲
|
||||
|
||||
- **条件**:横盘已持续较久(例如满约 12 小时),方向不明。
|
||||
- **工具**:一天期 Call + Put(对冲);总权利金预算见仓位章。
|
||||
- **意图**:买接下来的波动,不赌单边。
|
||||
- **期间**:一般 **不再开 Gate 方向单**(已在买波动,勿叠同一宏观暴露)。
|
||||
|
||||
### 3.2 方向明确 · 结构突破 → 期权
|
||||
|
||||
- **条件**:方向、空间、值不值得均过关;结构突破成立。
|
||||
- **工具**:**一天期期权方向单**(或明显顺势结构)。
|
||||
- **离场**:目标止盈或到期;不手平。
|
||||
- **默认**:先只开期权,不上合约。
|
||||
|
||||
### 3.3 结构突破后 · 反向假突破确认 → 可加合约
|
||||
|
||||
- **条件**:已有结构突破的期权表达;随后出现反向假突破且确认失败、续原方向。
|
||||
- **工具**:Gate 合约 **小仓加强**(止损纪律见下)。
|
||||
- **注意**:BTC 合约与 ETH 期权高度相关,属加重暴露,不是分散;仓位按「一笔故事」计风险。
|
||||
- **假突破定义**需事先写死(相对哪段结构、如何确认收回),避免临场随便加仓。
|
||||
|
||||
### 3.4 独立假突破(没有先开突破期权时)
|
||||
|
||||
- 按「假破专用」处理:优先 **只做合约** 或 **空仓**,勿与「突破后再假破加仓」混用同一套仓。
|
||||
|
||||
---
|
||||
|
||||
## 4. 对冲偏好(偏置对冲)
|
||||
|
||||
在「尽量用对冲」的前提下:
|
||||
|
||||
- 对冲内常带 **做多/做空比例**;若略偏多,则 **做多一侧比例更高**。
|
||||
- 顺势侧尽量用 **实值(或更实)**:
|
||||
- 方向对了:可能 **少赚一点**(相对纯单边);
|
||||
- 方向错了:争取 **不亏或少亏**(相对虚值双买两边磨光)。
|
||||
- **总权利金仍锁在对冲预算内**(见仓位);偏置只调张数/行权远近,不偷偷加预算。
|
||||
- **偏置有度**(例如勿极端到名存实亡的单边);完全没方向时更接近均分/近平值;方向非常明确时应走单边期权,不必硬套对冲壳。
|
||||
- 复盘建议区分:**中性对冲** vs **偏多/偏空对冲**,以便检验偏置是否真压低亏损。
|
||||
|
||||
---
|
||||
|
||||
## 5. 仓位与风险预算
|
||||
|
||||
**总资金参考:约 800U。**
|
||||
|
||||
| 项目 | 规则 |
|
||||
|------|------|
|
||||
| 单笔期权 | 约 **10U** 权利金预算;**一次只持有一个期权仓位** |
|
||||
| 期期对冲 | **合计约 10U**(两腿加总,不是各 10) |
|
||||
| Gate 合约 | 日内保证金约 **50U**、约 **10 倍**;有单才用,无单为 0 |
|
||||
| 合约止损 | 一般约 **5U**;单笔最大亏损不超过约 **10U** |
|
||||
| 日损失心理框 | 期权+合约若都错:合计大约 **≤20U**;都对时期望可到 **40U+**(理想情形,非每日目标) |
|
||||
|
||||
相对 800U:单笔约 **1.25%** 量级;全错一天约 **2.5%** 量级——防守优先。
|
||||
|
||||
**叠加红线**
|
||||
|
||||
- 期权一仓 + 合约加仓同日存在时,按合计风险接受最坏约 20U,且尽量少「同向双开」。
|
||||
- 不因「期权偏置可能少亏」而放大合约。
|
||||
|
||||
---
|
||||
|
||||
## 6. 合约日纪律(Gate)
|
||||
|
||||
1. 只做 **很明确的位置**;不明确基本不做。
|
||||
2. 动手前想清:**如何进场**。
|
||||
3. **同一位置最多两次机会**:结构突破、假突破。
|
||||
4. **两次都错 → 当日不再做单**(即使后面更「看起来清楚」也留到明天)。
|
||||
5. 止损约 **5U**;波段规则(含是否时间离场)开仓前想清。
|
||||
6. 已关闭「强制清仓」误伤策略意图时,离场以结构止盈/止损为准;历史里「强制清仓但盈利」按规则结果理解,复盘看盈亏与结构。
|
||||
|
||||
---
|
||||
|
||||
## 7. 期权日纪律(OKX)
|
||||
|
||||
1. **不手动平仓**;只等规则止盈或到期(紧急手平标记为非策略样本)。
|
||||
2. 一次一仓;对冲共 10U。
|
||||
3. 横盘对冲期间一般不开 Gate 方向单。
|
||||
4. 结构突破用期权表达;假破加强才考虑合约。
|
||||
5. 默认一天期;优先完整会话窗口再开。
|
||||
|
||||
---
|
||||
|
||||
## 8. 开仓前自检清单
|
||||
|
||||
- [ ] 今天是否只动「期权 / Gate」,其它账户零操作?
|
||||
- [ ] 买波动还是买方向?工具选对了吗?
|
||||
- [ ] 方向 / 空间 / 值不值得是否都过关?
|
||||
- [ ] 期权:止盈条件与「接受到期」是否写清?
|
||||
- [ ] 对冲:比例与实值偏置是否有度?总预算是否仍 ≤10U?
|
||||
- [ ] 合约:本位置第几次机会?止损约 5U 设好了吗?
|
||||
- [ ] 若加合约:是否已有突破期权且假破确认?是否当成一笔故事控总风险?
|
||||
- [ ] 今日合约两点机会是否已用完?(用完则收工)
|
||||
|
||||
---
|
||||
|
||||
## 9. 一句话版本
|
||||
|
||||
> **横盘对冲(可偏置实值);突破用一天期权;假破确认后小仓合约加强;先过方向/空间/值不值得;期权不手平;一位置两次,错完收工;单笔小亏、组合回撤可控。**
|
||||
|
||||
---
|
||||
|
||||
## 10. 修订记录
|
||||
|
||||
| 日期 | 说明 |
|
||||
|------|------|
|
||||
| 2026-07-21 | 初版:根据实盘讨论整理(期权为主、Gate 为辅、仓位与日停手规则) |
|
||||
| 2026-07-23 | 挂钩开单三检行为准则 |
|
||||
| 2026-07-24 | 标注为 v1(含对冲);现行纪律迁至执行手册 v2 |
|
||||
Binary file not shown.
@@ -0,0 +1,115 @@
|
||||
# 交易行为准则(开单三检)
|
||||
|
||||
> 个人强制思维动作 · 初级版(2026-07)。
|
||||
> **不是策略**,是开单前的「交易防火墙」:保证动作在可控轨道上,**不判断这笔会不会赚钱**。
|
||||
> 来源:中控 AI 复盘对话(2026-07-22)与本人归纳。
|
||||
> 仓位与玩法细则见 [交易执行手册-期权与Gate.md](./交易执行手册-期权与Gate.md)。
|
||||
|
||||
---
|
||||
|
||||
## 1. 一句话
|
||||
|
||||
> **信号够不够清晰?流程有没有跑通?情绪是不是在证明自己?三检不过 → 不开。**
|
||||
|
||||
复盘成败的第一标准:**三检是否完整完成**,而不是这笔盈亏。
|
||||
|
||||
---
|
||||
|
||||
## 2. 总循环
|
||||
|
||||
```
|
||||
信号判断 → 流程确认 → 情绪自检 → 全部通过
|
||||
→ 开仓 → 等待系统结果(止盈 / 止损 / 到期)
|
||||
→ 本次结束 → 复盘整环 → 等待下一个信号
|
||||
```
|
||||
|
||||
任一步否决 → **空仓离开**,不找补丁理由硬开。
|
||||
|
||||
---
|
||||
|
||||
## 3. 开单前:三秒停顿
|
||||
|
||||
手要动之前,强制停顿,把注意力从宏大叙事拉回内部三点:
|
||||
|
||||
1. 我的**核心信号**是什么?
|
||||
2. **安全流程**跑通了吗?
|
||||
3. 我现在是冷静执行,还是急着证明 / 怕踏空 / 想回本?
|
||||
|
||||
---
|
||||
|
||||
## 4. 三检细则
|
||||
|
||||
### 4.1 信号判断(Signal Judgment)
|
||||
|
||||
**问:** 这次入场,最核心、最明确的那一个点位 / 结构确认是什么?它本身够不够清晰?
|
||||
|
||||
| 通过 | 否决 |
|
||||
|------|------|
|
||||
| 能用一句话说清「唯一核心确认」 | 说不清、要靠一长串宏观故事才能自圆其说 |
|
||||
| 点位 / 结构本身已经够清楚 | 「好像有戏」但确认点模糊 |
|
||||
| 只描述事实与系统条件 | 堆细节证明自己分析很厉害 |
|
||||
|
||||
对照执行手册时:先过 **1H 方向 → 空间 → 结构 → 定损盈 → 选工具(期权/合约)**;不够格 → 空仓(见手册 v2)。
|
||||
|
||||
### 4.2 流程确认(Process Confirmation)
|
||||
|
||||
**问:** 决定执行前,有没有按设定步骤检查资金与风险敞口?内部安全流程跑通了吗?
|
||||
|
||||
| 通过 | 否决 / 暂停 |
|
||||
|------|-------------|
|
||||
| 账户资金与当日额度符合要求 | 资金或次数已触限 |
|
||||
| 单笔风险 / 组合敞口在手册预算内 | 单笔或日最坏超限 → **暂停开单** |
|
||||
| 该走的检查项没有跳步 | 「先开了再说」 |
|
||||
|
||||
细则数字以执行手册仓位章为准(单笔期权、对冲总权利金、Gate 止损与日停手等)。
|
||||
|
||||
### 4.3 情绪自检(Emotional Self-Check)
|
||||
|
||||
**问:** 看到复杂结构与逻辑时,内心是什么?是「必须证明分析是对的」,还是「符合系统要求,所以做」?
|
||||
|
||||
| 通过 | 否决(果断放弃) |
|
||||
|------|------------------|
|
||||
| 「符合系统信号 + 账户没问题 → 开」 | 「怕踏空」 |
|
||||
| 不需要再找更多开单理由 | 「上回亏了,这单要回本」 |
|
||||
| 旁观者视角、可接受空仓 | 「必须证明我是对的」 |
|
||||
|
||||
**原则:** 不为开单找理由;情绪红灯亮了,信号再好看也不开。
|
||||
|
||||
---
|
||||
|
||||
## 5. 开仓后纪律(与手册一致)
|
||||
|
||||
- 开仓后:**等待系统结果**(规则止盈 / 止损 / 到期),不靠情绪手平(紧急例外不算策略样本)。
|
||||
- 持仓期盯的是「程序与纪律是否正常」,不是浮盈浮亏数字本身。
|
||||
- 无信号时的空档也算训练:反复在脑子里空跑三检,比硬找单更重要。
|
||||
|
||||
---
|
||||
|
||||
## 6. 复盘只记什么
|
||||
|
||||
每次交易(含未开成的冲动)建议只记:
|
||||
|
||||
1. 信号判断:做了吗?核心确认写了什么?是否清晰?
|
||||
2. 流程确认:资金 / 敞口是否过关?有无跳步?
|
||||
3. 情绪自检:当时心态是哪一类?有无怕踏空 / 回本?
|
||||
4. 结果:止盈 / 止损 / 到期 / 未开 — **结果不推翻「三检是否完成」这一评分。**
|
||||
|
||||
---
|
||||
|
||||
## 7. 与执行手册的分工
|
||||
|
||||
| 文档 | 管什么 |
|
||||
|------|--------|
|
||||
| **本准则** | 能不能动手(防火墙 / 操作系统) |
|
||||
| **执行手册** | 怎么做单(期权 / Gate、仓位、离场) |
|
||||
|
||||
先过本准则三检,再谈手册里的玩法与仓位。
|
||||
|
||||
---
|
||||
|
||||
## 8. 修订记录
|
||||
|
||||
| 日期 | 说明 |
|
||||
|------|------|
|
||||
| 2026-07-23 | 初级版:三检 + 总循环 + 红线;对齐 AI 复盘与本人总结 |
|
||||
| 2026-07-24 | 信号检对齐执行手册 v2 主链条(1H→空间→结构→定损盈→期权/合约) |
|
||||
@@ -0,0 +1,68 @@
|
||||
# 仓库代码统计
|
||||
|
||||
> 统计时点:**2026-07-21 10:47(北京时间)**
|
||||
> 基准提交:`60ff45f`
|
||||
> 口径:仅统计 `git ls-files` **已跟踪**文件;不含未提交改动、`.venv`、本地数据库、日志等。
|
||||
|
||||
## 总览
|
||||
|
||||
| 项目 | 数量 |
|
||||
|------|------|
|
||||
| 已跟踪文件 | **626** |
|
||||
| 其中二进制(如图片/ico,不计入行数) | 53 |
|
||||
| 文本总行数(含空行) | **170,713** |
|
||||
| 非空行 | **152,453** |
|
||||
| 空行 | 18,260 |
|
||||
|
||||
## 源码规模(常用后缀)
|
||||
|
||||
以下按「源码向」后缀汇总:`.py` / `.js` / `.cjs` / `.css` / `.html` / `.sh` / `.sql` 等。
|
||||
|
||||
| 项目 | 数量 |
|
||||
|------|------|
|
||||
| 源码文件 | **472** |
|
||||
| 源码行数(含空行) | **157,585** |
|
||||
|
||||
更宽的「代码/配置向」后缀(再含 `.md` / `.json` / `.example` / `.mdc` 等)约 **547** 个文件、**169,493** 行。
|
||||
|
||||
## 按扩展名明细
|
||||
|
||||
| 扩展名 | 文件数 | 行数(含空行) | 非空行 |
|
||||
|--------|--------|----------------|--------|
|
||||
| `.py` | 328 | 96,645 | 86,552 |
|
||||
| `.js` | 44 | 30,131 | 28,073 |
|
||||
| `.css` | 8 | 18,082 | 16,225 |
|
||||
| `.md` | 71 | 11,712 | 8,173 |
|
||||
| `.html` | 60 | 9,849 | 9,536 |
|
||||
| `.sh` | 27 | 2,699 | 2,390 |
|
||||
| `.example` | 4 | 872 | 800 |
|
||||
| `.webmanifest` | 9 | 207 | 207 |
|
||||
| `.cjs` | 5 | 179 | 169 |
|
||||
| `.json` | 3 | 178 | 178 |
|
||||
| `.svg` | 9 | 87 | 87 |
|
||||
| 无扩展名 | 2 | 37 | 33 |
|
||||
| `.mdc` | 1 | 18 | 13 |
|
||||
| `.txt` | 2 | 17 | 17 |
|
||||
| `.png` | 45 | —(二进制) | — |
|
||||
| `.ico` | 8 | —(二进制) | — |
|
||||
|
||||
## 结构直觉
|
||||
|
||||
- **Python** 约占文本行数一半以上,是业务与交易所对接主体。
|
||||
- **前端静态**(`.js` + `.css` + `.html`)合计约 **5.8 万行**,实例页 / 中控 / 对冲与期权面板为主。
|
||||
- **文档** `.md` 约 **1.2 万行**,部署与策略说明较多。
|
||||
- 二进制资源以快捷图标 / 图示为主(`.png` / `.ico`),不参与行数统计。
|
||||
|
||||
## 复算方式
|
||||
|
||||
在仓库根目录可用:
|
||||
|
||||
```bash
|
||||
git ls-files | wc -l
|
||||
```
|
||||
|
||||
更细的按扩展名行数统计,可用本地脚本对 `git ls-files` 结果逐文件按 UTF-8/GBK 解码计行;含 `\0` 的文件视为二进制并跳过行数。
|
||||
|
||||
---
|
||||
|
||||
*本文件为快照说明;仓库继续演进后数字会变,需要时再重跑统计更新本文。*
|
||||
+24
-10
@@ -93,7 +93,14 @@
|
||||
|
||||
- **T 型报价链**(复用期权页 T 型样式/数据结构).
|
||||
- 用户选 **腿 A + 腿 B**(通常 Call + Put,或主方向 + 尾部).
|
||||
- 预算受 `OKX_OPTIONS_TRADE_BUDGET_USDC` 等既有约束;可拆预算到两腿.
|
||||
- 预算:`B = min(交易户 USDC × OKX_OPTIONS_BUDGET_BUFFER, OKX_OPTIONS_TRADE_BUDGET_USDC)`(默认 buffer=0.95).
|
||||
- 自动张数(选齐两腿后写入,可手改):
|
||||
- **同张数**(默认):最大 `n` 使 `n×(cost_A+cost_B) ≤ B`,两腿均填 `n`
|
||||
- **做多 / 做空**:须一 Call 一 Put;主:次默认 **7:3**(`HEDGE_PLAN_OO_BIAS_RATIO`,可改)
|
||||
- 做多:主腿=Call;做空:主腿=Put
|
||||
- 拆分口径 `HEDGE_PLAN_OO_BIAS_SPLIT_BY`:`budget`(默认,按权利金预算拆) / `sheets`(先按同张数得每腿 `n`,总张数 `2n` 再按比例拆到 Call/Put)
|
||||
- 另受各自卖一深度上限约束
|
||||
- 已移除页面「均分」;后端仍兼容旧 `split_budget` 入参(预算对半)
|
||||
|
||||
### 4.2 目标价
|
||||
|
||||
@@ -141,16 +148,17 @@
|
||||
|
||||
### 5.2 期期对冲
|
||||
|
||||
| 事件 | 盈利方 | 亏损方 | 计划是否结束 |
|
||||
|------|--------|--------|--------------|
|
||||
| **标的价到达用户目标价 S\*** | **自动平仓** | **不平**,持有至到期 | 平盈利腿后计划可标 `closing`;**全部腿终态后结束**(亏损腿到期后结账) |
|
||||
| **到期且整体无盈利** | — | 到期结算 | **算结束**;合计记 **总亏损**(通常 ≈ −全部权利金,或到期结算净值 < 0 的合计) |
|
||||
| 到期时组合合计仍盈利 | — | 到期结算 | **算结束**;按实际结算盈亏入账 |
|
||||
| 未达 S\* 至到期 | 两腿均到期 | | 同上,按结算合计结束 |
|
||||
| 事件 | 盈利方 | 另一腿(残腿) | 计划是否结束 |
|
||||
|------|--------|--------------|--------------|
|
||||
| **标的价到达目标 + 平仓模式=到期平** | **自动平仓** | **不平**,持有至到期(`hold_expiry`) | 平盈利腿后仍 `active`;残腿到期后结账 |
|
||||
| **标的价到达目标 + 平仓模式=全平**(默认) | **自动平仓** | **随即买一清残腿**(无 2×门控,失败则每轮重试) | 两腿都平完后 `closed` |
|
||||
| **到期且整体无盈利** | — | 到期结算 | **算结束**;合计记 **总亏损** |
|
||||
| **到期时组合合计仍盈利** | — | 到期结算 | **算结束**;按实际结算盈亏入账 |
|
||||
|
||||
判定「整体无盈利」:到期(或计划收口)时 `realized_pnl_total ≤ 0`(含双腿权利金全损).
|
||||
|
||||
盈利方判定规则仍按前文(触达 S\* 时按浮盈较大一侧平仓;皆亏则等到期).
|
||||
- 界面「平仓模式」仅控制**盈利腿已平之后**另一腿的处理;须 `HEDGE_PLAN_OO_CLOSE_MODE_ENABLED=true`(默认开)才显示,页面默认选 **全平**.
|
||||
- 关闭方案C开关时行为固定为 **到期平**.
|
||||
- 判定「整体无盈利」:到期(或计划收口)时 `realized_pnl_total ≤ 0`(含双腿权利金全损).
|
||||
- 盈利方判定:触达上破/下破时按浮盈较大一侧平仓;皆亏则等到期.
|
||||
|
||||
### 5.2.1 期权腿实盘平仓执行(与期权页共用)
|
||||
|
||||
@@ -553,11 +561,14 @@ realized_pnl_total = pnl_option_close - abs(pnl_perp_sl)
|
||||
| 变量 | 前端标签 | 默认 | 控件 | 热更新 | 说明 |
|
||||
|------|----------|------|------|--------|------|
|
||||
| `HEDGE_PLAN_ENABLED` | 启用对冲计划 | false | bool | 热更优先 | 总开关:导航 + API |
|
||||
| `HEDGE_PLAN_SHOW_PERP_OPTIONS` | 显示永期对冲 | true | bool | 热更 | 关则隐藏永期 Tab,不可测算/开仓 |
|
||||
| `HEDGE_PLAN_SHOW_OPTIONS_OPTIONS` | 显示期期对冲 | true | bool | 热更 | 关则隐藏期期 Tab,不可测算/开仓 |
|
||||
| `HEDGE_PLAN_LIVE_ORDER` | 允许对冲真实下单 | false | bool | 热更 | 关则只测算/草稿 |
|
||||
| `HEDGE_PLAN_OPEN_ORDER` | 永期开仓顺序 | options_first | select:`options_first`/`perp_first` | 热更 | 默认先期权后永续 |
|
||||
| `HEDGE_PLAN_ON_PERP_SL_CLOSE_OPTIONS` | 永期止损后强制平期权 | true | bool | 热更 | **保护机制,默认 true** |
|
||||
| `HEDGE_PLAN_ON_PERP_TP_CLOSE_OPTIONS` | 永期止盈后强制平期权 | false | bool | 热更 | **默认 false,保险腿不平** |
|
||||
| `HEDGE_PLAN_OO_CLOSE_WINNER_ONLY` | 期期只平盈利腿 | true | bool | 热更 | 达目标价只平盈利方 |
|
||||
| `HEDGE_PLAN_OO_CLOSE_MODE_ENABLED` | 期期平仓模式(方案C) | true | bool | 热更 | 开:页面可选到期平/全平;关:固定到期平 |
|
||||
| `MAX_ACTIVE_HEDGE_PLANS` | 最大同时活跃计划数 | 1 | number | 热更 | 建议保持 1 |
|
||||
| `HEDGE_PLAN_MONITOR_POLL_SECONDS` | 对冲监控轮询(秒) | 15 | number | 热更 | 侦测 TP/SL/目标价 |
|
||||
| `HEDGE_PLAN_PARTIAL_AUTO_CLOSE_OPTION` | 半腿失败时自动平期权 | true | bool | 热更 | 期权成、永续败时的补偿 |
|
||||
@@ -577,11 +588,14 @@ realized_pnl_total = pnl_option_close - abs(pnl_perp_sl)
|
||||
```env
|
||||
# --- 对冲计划(仅 OKX;前端 env「对冲计划」) ---
|
||||
HEDGE_PLAN_ENABLED=false
|
||||
HEDGE_PLAN_SHOW_PERP_OPTIONS=true
|
||||
HEDGE_PLAN_SHOW_OPTIONS_OPTIONS=true
|
||||
HEDGE_PLAN_LIVE_ORDER=false
|
||||
HEDGE_PLAN_OPEN_ORDER=options_first
|
||||
HEDGE_PLAN_ON_PERP_SL_CLOSE_OPTIONS=true
|
||||
HEDGE_PLAN_ON_PERP_TP_CLOSE_OPTIONS=false
|
||||
HEDGE_PLAN_OO_CLOSE_WINNER_ONLY=true
|
||||
HEDGE_PLAN_OO_CLOSE_MODE_ENABLED=true
|
||||
MAX_ACTIVE_HEDGE_PLANS=1
|
||||
HEDGE_PLAN_MONITOR_POLL_SECONDS=15
|
||||
HEDGE_PLAN_PARTIAL_AUTO_CLOSE_OPTION=true
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
# Git 快照标签
|
||||
|
||||
代码级快照用 annotated tag 打在 `main` 上,便于回看某日仓库状态(不含 `.env` / 数据库)。
|
||||
|
||||
## 当前快照
|
||||
|
||||
| 标签 | 指向提交 | 说明 |
|
||||
|------|----------|------|
|
||||
| `snapshot/20260727` | `f53f281` | 2026-07-27:实例手机壳(下单/关键位/期权)、著作权声明、托管合同(一用户一机)、服务说明与报价说明 |
|
||||
| `snapshot/20260726-2` | `4a79e01` | 2026-07-26 午:执行手册脑图(业务主题)、`.xmind` 按二进制入库、去掉缩略图避免 Gitea raw 换行损坏 |
|
||||
| `snapshot/20260726` | `a2075ba` | 2026-07-26:Gate划转币种大写修复、系统设置划转页签停留、自动划转账户/币种下拉默认、期权「按可用余额打满」=min(余额,单笔预算)及说明 |
|
||||
| `snapshot/20260724` | `890659f` | 2026-07-24:执行手册v2(无对冲)、监控/策略页签显隐、内照明心期权档案同步、期权开平仓微信必发、实例导航显隐关键位/实盘下单等 |
|
||||
| `snapshot/20260723-2` | `9e0591c` | 2026-07-23:策略对比页(合约/单期权/期期7:3)、监控与看板隐藏浮盈偏好、对比页卡片内边距等 |
|
||||
| `snapshot/20260723-pre-amp-stats` | `40be3a5` | 2026-07-23:振幅统计开发前;含执行手册进教练、日亏损冻结、手机监控 UI、振幅统计开发方案等 |
|
||||
| `snapshot/20260721-2` | `a721642` | 2026-07-21 晚:日亏损次数冻结、交易执行手册入中控策略说明、期权/Gate 执行手册文档等 |
|
||||
| `snapshot/20260721` | `1a163c0` | 2026-07-21:仓库代码统计文档、期权复盘亮色主题、对冲腿盈亏时区修复、本快照说明等 |
|
||||
|
||||
## 历史标签(节选)
|
||||
|
||||
| 标签 | 说明 |
|
||||
|------|------|
|
||||
| `snapshot/pre-strategy-mindmap-20260718` | 策略脑图相关改动前 |
|
||||
| `snapshot/pre-hub-order-popup` | 中控下单弹窗相关改动前 |
|
||||
| `snapshot/pre-hub-market-20260528` | 中控行情相关改动前 |
|
||||
| `pre-lib-modularization` | lib 模块化前 |
|
||||
| `pre-remove-gate-bot` | 移除 gate_bot 前 |
|
||||
|
||||
## 用法
|
||||
|
||||
```bash
|
||||
# 查看标签
|
||||
git tag -l 'snapshot/*'
|
||||
|
||||
# 检出快照(只读查看,勿在此分支直接开发)
|
||||
git checkout snapshot/20260727
|
||||
|
||||
# 回到主线
|
||||
git checkout main
|
||||
```
|
||||
|
||||
数据备份(SQLite / 中控 JSON)走中控备份或各所 `scripts/backup_data.sh`,**不要**把含密钥的 `.env` 与库文件提交进 Git。
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
# 振幅统计(中控)
|
||||
|
||||
中控只读工具:按自定义整点起点、**固定北京时间 16:00 收窗**,统计 OKX 上 ETH/BTC 的历史「点数振幅」档案,辅助一天期期权判断空间。
|
||||
|
||||
> 开发方案见 [ETH时段振幅统计-开发方案.md](./ETH时段振幅统计-开发方案.md)。
|
||||
> **不改下单链路**;不算 IV / 权利金。
|
||||
|
||||
---
|
||||
|
||||
## 入口
|
||||
|
||||
- 顶栏 **振幅统计**(`/amp-stats`)
|
||||
- 手机端:**更多 → 振幅统计**
|
||||
- 可在系统设置里隐藏该导航
|
||||
|
||||
---
|
||||
|
||||
## 怎么用
|
||||
|
||||
1. 打开 **统计** Tab
|
||||
2. 选择 **标的** ETH / BTC;数据源固定 **OKX**
|
||||
3. **起点整点**(00–23);终点固定 **16:00**
|
||||
4. **周期**:1 月 / 2 月 / 3 月 / 半年 / 1 年 / 自定义天数(默认 2 个月)
|
||||
5. 点 **计算** → 下方看汇总 + 分页日表
|
||||
6. 需要留存时点 **保存到历史**;**下载 CSV** 含摘要 + 全日明细
|
||||
|
||||
**跨天例子**
|
||||
|
||||
| 起点 | 含义(结算日 D) |
|
||||
|------|------------------|
|
||||
| 22:00 | 昨天 22:00 → 今天 16:00 |
|
||||
| 16:00 | 昨天 16:00 → 今天 16:00 |
|
||||
| 08:00 | 今天 08:00 → 今天 16:00 |
|
||||
|
||||
未到当日 16:00 的「今天」不入样本。
|
||||
|
||||
---
|
||||
|
||||
## 指标(点数)
|
||||
|
||||
设开盘 O、最高 H、最低 L、收盘 C:
|
||||
|
||||
| 字段 | 算法 |
|
||||
|------|------|
|
||||
| 开→高 | `H − O` |
|
||||
| 开→低 | `O − L` |
|
||||
| **振幅** | `H − L`(= 开→高 + 开→低) |
|
||||
| 涨跌值 | `C − O` |
|
||||
|
||||
例:O=2000,H=2500,L=1800 → 开→高 500,开→低 200,振幅 **700**。
|
||||
|
||||
汇总必含:最大振幅(及日期)、开→高/开→低的最大与均值等。
|
||||
|
||||
K 线粒度:**1H**(与整点对齐);价源优先 OKX 指数(ETH-USD / BTC-USD),失败再降级永续标记。
|
||||
近期 K 线接口约仅 **1440** 根(1H≈60 天);更长周期自动续拉 `history-index-candles` / `history-candles`。
|
||||
分页带间隔,遇 OKX **429** 会自动退避重试(长周期首次会慢一些)。
|
||||
|
||||
---
|
||||
|
||||
## 买跨对照(赌波动)
|
||||
|
||||
表单可填 **双边权利金(点)**,例如 `30`;旁边可填 **止盈点**(可空):
|
||||
|
||||
| 汇总项 | 口径 |
|
||||
|--------|------|
|
||||
| 开→高超过权利金 | `H−O > 权利金` 的天数与占比 |
|
||||
| 开→低超过权利金 | `O−L > 权利金` 的天数与占比 |
|
||||
| \|涨跌\|超过权利金 | `\|C−O\| > 权利金` 的天数与占比 |
|
||||
| 有效波动 | 若设止盈且 `开→高≥止盈` 或 `开→低≥止盈` → 用止盈点;否则用 `\|C−O\|` |
|
||||
| 买跨收益 | `有效波动 − 权利金`(日表「收益」列同口径) |
|
||||
|
||||
- 方向:**买跨**
|
||||
- 权利金越过:严格 **`>`**;止盈触达:**`≥`**
|
||||
- 止盈留空 / ≤0:有效波动一律按 `|涨跌|`
|
||||
- 已算出日表后,改权利金 / 止盈 / 周末筛选会**本地重算**(不重拉 K 线)
|
||||
|
||||
### 周末
|
||||
|
||||
- 下拉:**全部**(默认)/ **排除周末** / **仅周末**
|
||||
- 按 **结算日** 北京时间星期判断;表中六、日带标注并高亮
|
||||
|
||||
---
|
||||
|
||||
## 历史 Tab
|
||||
|
||||
- 仅 **保存到历史** 后出现(不会一算就自动入库)
|
||||
- 可查看、再下载、删除
|
||||
- 数据文件:`manual_trading_hub/amp_stats_history.json`(勿当密钥提交)
|
||||
|
||||
---
|
||||
|
||||
## 相关代码
|
||||
|
||||
| 路径 | 说明 |
|
||||
|------|------|
|
||||
| `lib/hub/amp_stats_lib.py` | 切窗、汇总、OKX 拉取、CSV |
|
||||
| `manual_trading_hub/amp_stats_routes.py` | API |
|
||||
| `manual_trading_hub/amp_stats_store.py` | 历史 JSON |
|
||||
| `manual_trading_hub/static/amp_stats.js` | 前端 |
|
||||
| `tests/test_amp_stats_lib.py` | 单元测试 |
|
||||
|
||||
---
|
||||
|
||||
## 修订
|
||||
|
||||
| 日期 | 说明 |
|
||||
|------|------|
|
||||
| 2026-07-23 | 首版上线说明 |
|
||||
| 2026-07-23 | 买跨对照:可设双边权利金、越过占比与收盘盈亏 |
|
||||
| 2026-07-23 | 周末筛选/标注、止盈点(≥)、日表收益列 |
|
||||
| 2026-07-23 | 长周期续拉 history K 线;收益列红绿着色 |
|
||||
@@ -4,6 +4,95 @@
|
||||
|
||||
---
|
||||
|
||||
## 2026-07-19 · 期权复盘详情改为对话框 + 截图显示修复
|
||||
|
||||
### 修改原因
|
||||
|
||||
复盘详情嵌在列表下方不便查看;截图缩略图易裁切/偶发加载失败。
|
||||
|
||||
### 修改的地方
|
||||
|
||||
| 文件 | 改动摘要 |
|
||||
|------|----------|
|
||||
| `options_review_panel.html` | 详情改为居中对话框;2×2 截图网格 |
|
||||
| `options_review.js` | 点复盘记录打开弹窗;截图 basename + onerror |
|
||||
| `options_review_register.py` | 截图静态路由不强制登录(防 iframe 401) |
|
||||
|
||||
### 交付之后的验收
|
||||
|
||||
点「复盘记录」行弹出对话框;5m/15m/1h/4h 截图完整可见(缺失显示提示);关闭/Esc/点遮罩可关。
|
||||
|
||||
---
|
||||
|
||||
## 2026-07-19 · 期期情景测算:盈亏配色 + 盈亏比(亏=全额保费)
|
||||
|
||||
### 修改原因
|
||||
|
||||
情景弹窗合计无红绿区分;需要一眼看盈亏,并按「最大亏损=权利金全亏」给出上破/下破盈亏比。
|
||||
|
||||
### 修改的地方
|
||||
|
||||
| 文件 | 改动摘要 |
|
||||
|------|----------|
|
||||
| `hedge_plan.js` | 合计/腿盈亏用 `hp-pnl-pos/neg`;摘要显示盈亏比 |
|
||||
| `hedge_plan_calc_lib.py` | summary 增加 `rr_at_up` / `rr_at_down` / `rr_risk_premium` |
|
||||
|
||||
### 交付之后的验收
|
||||
|
||||
正数为绿、负数为红;摘要可见「盈亏比 上破 x:1 / 下破 y:1(亏=全额保费)」。
|
||||
|
||||
---
|
||||
|
||||
## 2026-07-19 · 修复期期「按张数」拆分:用同张数总张数 2n
|
||||
|
||||
### 修改原因
|
||||
|
||||
`sheets` 口径误把同张数每腿 `n` 当总张数拆,规模偏小;应对齐「先算完同张数两侧合计总张数 `2n`,再按比例拆」。
|
||||
|
||||
### 修改的地方
|
||||
|
||||
| 文件 | 改动摘要 |
|
||||
|------|----------|
|
||||
| `hedge_plan_calc_lib.py` / `hedge_plan.js` | `total = n_same * 2` 再拆 |
|
||||
| 相关 docs / env 文案 | 口径说明改为总张数 `2n` |
|
||||
|
||||
### 交付之后的验收
|
||||
|
||||
同张数 `n=5` 时,`sheets`+做空(0.7) → Put 7 / Call 3(合计 10)。
|
||||
|
||||
---
|
||||
|
||||
## 2026-07-19 · 期期张数:做多/做空替代均分 + env 拆分口径
|
||||
|
||||
### 修改原因
|
||||
|
||||
期期「均分」与方向偏好无关;需要按 Call/Put 7:3(可配)做偏多/偏空自动张数,并可用 env 在「预算金额 / 张数」两种拆法间切换。
|
||||
|
||||
### 修改的地方
|
||||
|
||||
| 文件 | 改动摘要 |
|
||||
|------|----------|
|
||||
| `lib/hedge_plan/hedge_plan_calc_lib.py` | `long_bias`/`short_bias`;`budget`/`sheets` + `bias_ratio` |
|
||||
| `lib/hedge_plan/hedge_plan_register.py` | gates 下发 `oo_bias_split_by` / `oo_bias_ratio` |
|
||||
| `lib/hedge_plan/templates/hedge_plan_panel.html` | 张数段:同张数 / 做多 / 做空 |
|
||||
| `lib/common/static/hedge_plan.js` | 前端建议张数与 env 同步 |
|
||||
| `crypto_monitor_okx/.env.example` + env UI/schema | `HEDGE_PLAN_OO_BIAS_SPLIT_BY`、`HEDGE_PLAN_OO_BIAS_RATIO` |
|
||||
| `docs/系统说明.md` 等 | 同步操作与配置说明 |
|
||||
|
||||
### 达成的目标
|
||||
|
||||
1. 默认仍为同张数。
|
||||
2. 做多=Call 主占比、做空=Put 主占比;默认比例 0.7,口径默认预算金额。
|
||||
3. `sheets` 口径:先算同张数每腿 `n`,总张数 `2n` 再拆(见上一条修正)。
|
||||
|
||||
### 交付之后的验收
|
||||
|
||||
1. 期期页可见「同张数 / 做多 / 做空」,无「均分」。
|
||||
2. env 配置可改口径与比例;生产 OKX `.env` 已补齐键。
|
||||
3. 选一 Call 一 Put 后自动张数符合比例;非 C+P 时提示。
|
||||
|
||||
---
|
||||
|
||||
## 2026-07-17 · 修复 pip>=26 部署依赖安装失败
|
||||
|
||||
### 修改原因
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
# 服务说明与报价说明
|
||||
|
||||
> 本文说明本系统的定位、适用对象、托管方式与参考报价。
|
||||
> 配套文件:`著作权声明.md`、`软件使用授权合同-模板.md`(托管服务与软件使用合同)。
|
||||
> **本系统以著作权人自用为主**;对外托管属个案合作,并非标准化「卖工具」业务。
|
||||
|
||||
---
|
||||
|
||||
## 1. 这是什么
|
||||
|
||||
`crypto_monitor`(加密货币交易监控与中控系统)由著作权人 **马建军** 历时约三个月持续开发,用于自身实盘交易中的:
|
||||
|
||||
- 多交易所实例监控与下单辅助
|
||||
- 风控与纪律约束(如日亏冻结、执行规则落地到系统)
|
||||
- 复盘、关键位、期权/合约相关流程(以实际开通功能为准)
|
||||
- 中控统一查看与管理
|
||||
|
||||
开发目的首先是:**把交易习惯钉进系统,减少情绪单与随意操作**,而不是面向市场量产销售的通用软件商品。
|
||||
|
||||
---
|
||||
|
||||
## 2. 定位与适用对象
|
||||
|
||||
### 2.1 定位
|
||||
|
||||
| 是 | 不是 |
|
||||
|----|------|
|
||||
| 全职(或准全职)交易者的执行与纪律系统 | 兼职「玩玩」的下单插件 |
|
||||
| 规则、限制、复盘一起用的工作台 | 帮你加杠杆、追涨杀跌的「发财工具」 |
|
||||
| 著作权人自用为主;对外仅少量托管 | 开源产品或标准化 SaaS 大卖场 |
|
||||
|
||||
### 2.2 适合
|
||||
|
||||
- 以交易为主要工作、愿意按规则执行的人
|
||||
- 认同执行手册与系统内限制(含开仓限制、冻结等)
|
||||
- 接受「一户一机、不交付源码、按期付费」的托管方式
|
||||
- 账户规模与付费意愿匹配(服务费不应明显高于可承受的交易成本)
|
||||
|
||||
### 2.3 不适合(一般不承接)
|
||||
|
||||
- 兼职、偶尔开几单的小散
|
||||
- 只想要更快开仓、更高杠杆,不愿接受纪律约束
|
||||
- 要求交付源码、私有仓库权限或「买断随便改」
|
||||
- 希望多人共用一台服务器以压低费用
|
||||
|
||||
**说明:** 不适合不等于否定任何人,而是产品与服务形态不匹配;强行上线往往浪费双方时间。
|
||||
|
||||
---
|
||||
|
||||
## 3. 对外怎么提供(若合作)
|
||||
|
||||
默认且唯一推荐的方式:
|
||||
|
||||
1. **著作权人提供专属服务器**(一用户一服务器,不与其他客户共用)
|
||||
2. **部署中控与实例**,配置域名 / HTTPS
|
||||
3. 客户仅获得 **访问地址 + 登录账号**
|
||||
4. **不交付源代码**、不开放 Git、不移交服务器 root(由甲方代持运维)
|
||||
|
||||
合作前建议:先阅读相关执行/行为说明,确认认同纪律设计,再谈部署与费用。
|
||||
|
||||
正式合作须签署《托管服务与软件使用合同》(见合同模板)。
|
||||
|
||||
---
|
||||
|
||||
## 4. 费用构成
|
||||
|
||||
费用分四项,建议在报价单中分列,避免被理解成「只卖服务器」:
|
||||
|
||||
| 费用 | 含义 | 通常周期 |
|
||||
|------|------|----------|
|
||||
| 服务器费用 | 该客户专属云主机、带宽、磁盘等 | 月 / 年 |
|
||||
| 域名费用 | 域名注册或续费(代持或客户自带域名) | 年 |
|
||||
| 部署费用 | 首次装机、证书、上线、基础培训 | 一次性 |
|
||||
| 程序使用费 | 软件托管使用权、基础更新与运维响应 | 月 / 年 |
|
||||
|
||||
续费年一般不再收部署费(大改版或迁移可另议)。
|
||||
|
||||
---
|
||||
|
||||
## 5. 参考报价(非标价,可协商)
|
||||
|
||||
以下为**面向全职交易者、个案托管**的参考区间(人民币)。
|
||||
因以自用为主、名额有限,实际以当时口头/书面报价为准,可高于下列下限。
|
||||
|
||||
### 5.1 分项参考
|
||||
|
||||
| 项目 | 参考区间 | 备注 |
|
||||
|------|----------|------|
|
||||
| 服务器费用 | **200–400 元/月** | 按机型实报或固定档;专属机,不共用 |
|
||||
| 域名费用 | **60–120 元/年** | 实报实销;客户自带域名可减免 |
|
||||
| 部署费用 | **2,000–5,000 元** | 一次性;含上线与基础使用说明 |
|
||||
| 程序使用费 | **1,000–2,500 元/月** 或 **10,000–25,000 元/年** | 年付可相当于少收 1~2 个月 |
|
||||
|
||||
### 5.2 首年打包示意(便于沟通)
|
||||
|
||||
| 档位 | 首年大约量级 | 思路 |
|
||||
|------|--------------|------|
|
||||
| 协作档 | 约 **1.5–2.5 万** | 部署中档 + 服务器 + 使用费中低 |
|
||||
| 标准档 | 约 **2–4 万** | 部署与使用费取中高,含优先响应 |
|
||||
|
||||
**不提供:** 低价引流套餐、兼职小资金特惠、源码买断(若极少数个案谈源码,须另签合同且价格远高于年使用费,默认不做)。
|
||||
|
||||
### 5.3 付款与停服
|
||||
|
||||
- 部署费 + 首周期费用:签约后约定日内支付,到账后排期部署
|
||||
- 续费:到期前支付;逾期可暂停访问,严重逾期可停服并释放专属服务器
|
||||
- 细节以合同条款为准
|
||||
|
||||
---
|
||||
|
||||
## 6. 服务边界(简要)
|
||||
|
||||
**甲方(马建军)合理范围内可提供:**
|
||||
|
||||
- 专属机上的首次部署与基础运维
|
||||
- 程序常规更新、进程异常处理
|
||||
- 约定范围内的使用说明
|
||||
|
||||
**一般不包含(除非另议):**
|
||||
|
||||
- 代客交易、代管资金、投资建议
|
||||
- 保证盈利或胜率
|
||||
- 7×24 即时响应当成「专职客服」
|
||||
- 按客户要求无限改需求而不另计定制费
|
||||
|
||||
交易盈亏由客户自行承担;系统为辅助与纪律工具。
|
||||
|
||||
---
|
||||
|
||||
## 7. 知识产权
|
||||
|
||||
- 软件与文档著作权归 **马建军** 所有,见 `著作权声明.md`
|
||||
- 托管仅授权约定范围内的使用权,**不转移著作权、不交付源码**
|
||||
- 仓库为私有保存;私有不影响著作权主张
|
||||
|
||||
---
|
||||
|
||||
## 8. 联系
|
||||
|
||||
- 著作权人 / 服务提供方:马建军
|
||||
- 电话:18364911125
|
||||
|
||||
意向合作请说明:交易经验与是否全职、大致账户规模(可不精确)、希望开通的交易所、是否接受系统纪律限制。
|
||||
**谢绝:** 仅询源码价格、要求多人共用一台服务器、明确表示不接受任何交易限制的需求。
|
||||
|
||||
---
|
||||
|
||||
*文档版本:与仓库同步维护;报价为参考,最终以双方确认的报价单与合同为准。*
|
||||
@@ -83,6 +83,7 @@
|
||||
5. **无市价强平**:盘口真空时系统**不会**市价砸盘,仓位可能留到到期.
|
||||
6. **目标位只看指数**:触达后仍受买一/2×门控约束,可能「到价却平不掉」.
|
||||
7. **对冲计划腿**:期权腿退出规则见对冲方案;独立期权页平仓勿与计划状态脱节.
|
||||
8. **期期自动张数**:对冲计划页为「同张数 / 做多 / 做空」(已无均分);做多/做空按 Call·Put 比例拆,口径与比例见 env `HEDGE_PLAN_OO_BIAS_SPLIT_BY`、`HEDGE_PLAN_OO_BIAS_RATIO`.
|
||||
|
||||
---
|
||||
|
||||
@@ -91,3 +92,4 @@
|
||||
- [期权用法.md](./期权用法.md) — 资金兑划与页面操作
|
||||
- [期权方案.md](./期权方案.md) — env 与架构
|
||||
- [对冲计划开发方案.md](./对冲计划开发方案.md) — 永期/期期与期权腿
|
||||
- [系统说明.md](./系统说明.md) — 实例操作与门禁总手册
|
||||
|
||||
+21
-4
@@ -74,20 +74,35 @@ OKX_OPTIONS_API_PASSPHRASE=...
|
||||
|
||||
## 5. 微信提醒
|
||||
|
||||
当某笔持仓 **未实现盈亏 ≥ 已付权利金的 100%**(翻倍)时,会发 **一条** 企业微信提醒(同一笔只提醒一次).
|
||||
|
||||
需已配置 `WECHAT_WEBHOOK`.
|
||||
|
||||
## 6. 与永续的关系
|
||||
| 场景 | 标题 | 说明 |
|
||||
|------|------|------|
|
||||
| **开仓** | 【OKX期权·开仓】 | 下单成功并写入本地后必发(幂等) |
|
||||
| **平仓** | 【OKX期权·平仓】 | 手动全平 / 目标位全平 / 到期或交易所平仓同步后必发(幂等) |
|
||||
| 浮盈翻倍 | 【OKX期权·翻倍提醒】 | 未实现盈亏 ≥ 已付权利金约 100%,同一笔只提醒一次 |
|
||||
| 挂单超时撤销 | 【OKX期权·挂单超时撤销】 | 平仓挂单超时被系统撤销 |
|
||||
|
||||
## 6. 与永续 / 对冲计划的关系
|
||||
|
||||
| | 永续(子账户) | 期权(主账户) |
|
||||
|--|----------------|----------------|
|
||||
| API | `OKX_API_*` | `OKX_OPTIONS_API_*` |
|
||||
| 页面 | 实盘下单 / 关键位 | 期权 |
|
||||
| 页面 | 实盘下单 / 关键位 | 期权 · 对冲计划 |
|
||||
| 资金顶栏 | USDT 资金户+交易户 | 期权页单独显示 USDC 等 |
|
||||
|
||||
两套资金 **不合并** 显示.
|
||||
|
||||
**期期对冲张数**(对冲计划页,与单独开期权共用预算算法):
|
||||
|
||||
| 模式 | 说明 |
|
||||
|------|------|
|
||||
| 同张数(默认) | 两腿同 `n`,总权利金 ≤ 预算 |
|
||||
| 做多 | Call:Put 按主腿占比(默认 7:3) |
|
||||
| 做空 | Put:Call 按主腿占比(默认 7:3) |
|
||||
|
||||
拆分口径与比例见 env:`HEDGE_PLAN_OO_BIAS_SPLIT_BY`(`budget` 默认 / `sheets`=先算同张数总张数 `2n` 再拆)、`HEDGE_PLAN_OO_BIAS_RATIO`(默认 `0.7`)。细则见 [对冲计划开发方案.md](./对冲计划开发方案.md) §4.1、[系统说明.md](./系统说明.md)。
|
||||
|
||||
## 7. 配置说明
|
||||
|
||||
| 变量 | 默认 | 含义 |
|
||||
@@ -97,6 +112,8 @@ OKX_OPTIONS_API_PASSPHRASE=...
|
||||
| `OKX_OPTIONS_MAX_DTE_DAYS` | 2 | 最多选几天内到期 |
|
||||
| `OKX_OPTIONS_ITM_MAX_DIST_USD` | 30 | 轻度实值:价内不超过多少 USD |
|
||||
| `OKX_OPTIONS_PROFIT_ALERT_RATIO` | 1.0 | 浮盈/权利金 ≥ 此值推送 |
|
||||
| `HEDGE_PLAN_OO_BIAS_SPLIT_BY` | budget | 期期做多/做空:按预算或按张数拆 |
|
||||
| `HEDGE_PLAN_OO_BIAS_RATIO` | 0.7 | 期期做多/做空主腿占比 |
|
||||
|
||||
## 8. 期权复盘(含对冲)
|
||||
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
# 策略对比说明
|
||||
|
||||
中控独立页 **策略对比**(`/compare`):在同一风险额 `R` 下,对比三种工具的止盈能力与止损/踏空路径。
|
||||
|
||||
## 用途
|
||||
|
||||
回答两件事:
|
||||
|
||||
1. **盈利时谁更厉害**:干净止盈路径下各赚多少 U
|
||||
2. **谁更易亏 / 更易踏空**:合约止损后踏空;期权/对冲最坏亏满权利金,但踏空路径下常仍可持有到目标
|
||||
|
||||
不是精确概率模型。到期「小盈/小亏」与 4 点收盘相关,**未纳入主表与推荐**。
|
||||
|
||||
## 入口
|
||||
|
||||
- 顶栏「策略对比」;设置 → 显示与导航可隐藏(`show_nav_compare`)
|
||||
- API:`POST /api/compare/calc`(页面即时调用,价格均为手填)
|
||||
|
||||
## 输入
|
||||
|
||||
| 区块 | 字段 |
|
||||
|------|------|
|
||||
| 公共 | 标的 ETH/BTC、方向、入场价、风险 R、统一止损、止盈 |
|
||||
| 单期权 | Call/Put、行权价、卖一(每币)、可选目标价 |
|
||||
| 期期 | 主腿/次腿 各自行权与卖一;预算固定 **7:3** |
|
||||
|
||||
卖一口径与对冲计划一致:`单张成本 = 卖一 × ct_mult`(默认 `ct_mult=0.01`)。
|
||||
|
||||
## 仓位
|
||||
|
||||
- **合约**:`张数 = floor(R / (|入场−止损| × 面值))`,默认面值 0.01
|
||||
- **单期权**:`张数 = floor(R / 单张成本)`
|
||||
- **期期**:主预算 `0.7R`、次预算 `0.3R`,各自 `floor(预算/单张成本)`
|
||||
|
||||
## 主情景(A/B/C)
|
||||
|
||||
| 路径 | 合约 | 单期权 / 期期 |
|
||||
|------|------|----------------|
|
||||
| A 干净止盈 | 入场→止盈盈亏 | 目标价内在价值 − 已付权利金(近似) |
|
||||
| B 打止损 | −实际止损额(≈R) | 止损价处内在−权利金;并注最坏 −权利金 |
|
||||
| C 先止损再去止盈 | **本单仍为止损亏损**;旁注踏空未拿到的原止盈空间 | **仍持有**至目标价,结果同 A(抗踏空对照) |
|
||||
|
||||
期权止盈按**内在价值近似**,不是盘口卖出价。
|
||||
|
||||
## 推荐规则(可解释)
|
||||
|
||||
1. 比较三者 A / R
|
||||
2. 若合约止盈明显高于另两者(≥1.15×)→ 倾向合约,并提示踏空
|
||||
3. 否则若存在踏空对照(合约亏、期权类 C 仍为正)→ 倾向单期权或期期(期期与单腿接近时优先期期)
|
||||
4. 平局:抗踏空优先期权类,赔付碾压则合约
|
||||
|
||||
## 手测示例
|
||||
|
||||
`ETH` 做多,入场 3500,止损 3400,止盈 3700,R=10;单 Call 行权 3600 卖一 50;对冲主 Call 3600/50、次 Put 3400/30:
|
||||
|
||||
- 合约约 10 张,止损 −10U,止盈约 +20U,踏空未拿到约 +20U
|
||||
- 单期权约 20 张,权利金 10U,止盈约 +10U,最坏 −10U
|
||||
- 期期主 14 / 次 10 张
|
||||
|
||||
## 不做
|
||||
|
||||
实盘下单、拉交易所卖一(二期可选)、历史回测入库。
|
||||
+362
@@ -0,0 +1,362 @@
|
||||
# 系统说明(实例操作与逻辑手册)
|
||||
|
||||
本文是实例侧的**详细说明书**:既写「点哪里、先做什么」,也写「为什么这样设计、钱怎么算、门禁如何拦」。
|
||||
默认不在顶栏显示;需要时到 **系统设置 → 导航显示** 打开「系统说明」。
|
||||
|
||||
覆盖:**总览 · 期权 · 对冲计划 · 实盘下单 · 策略交易 · 关键位监控**。复盘/统计字段级细则与风控参数表仍以对应专页为准。
|
||||
|
||||
---
|
||||
|
||||
## 一、总览:账户、资金与一天怎么用
|
||||
|
||||
### 1.1 两套账户(OKX)
|
||||
|
||||
| 账户 | 典型用途 | 界面相关 |
|
||||
|------|----------|----------|
|
||||
| **合约账户** | 永续开仓、止盈止损 | 实盘下单、策略、关键位自动单、永期对冲的永续腿 |
|
||||
| **期权账户** | 买期权、期期双腿、权利金结算(多为 USDC) | 期权页、对冲计划期权腿 |
|
||||
|
||||
逻辑要点:对冲计划里「永续腿 → 合约账户」「期权腿 → 期权账户」。资金不够时,要先划转,再开仓。Binance / Gate 实例主要是合约侧永续能力(无期权/对冲 Tab 时忽略期权相关章节即可)。
|
||||
|
||||
### 1.2 资金流(操作顺序)
|
||||
|
||||
1. 确认合约可用 USDT(及 OKX 期权交易账户 USDC)是否够用。
|
||||
2. 期期 / 单独开期权:常在期权页或期期卡片做 **资金 ↔ 交易** USDC 划转。
|
||||
3. 永期:合约侧按全仓建议张数;期权侧再买保险腿。
|
||||
4. 实盘 / 策略 / 关键位自动单:只动合约账户,按计仓模式算张数。
|
||||
5. 开仓后到对应页看持仓与监控状态;结束后看复盘 / 统计 / 策略记录。
|
||||
|
||||
### 1.3 推荐使用节奏
|
||||
|
||||
| 场景 | 建议路径 |
|
||||
|------|----------|
|
||||
| 人工永续单 + 监控 | **实盘下单** |
|
||||
| 趋势分档 / 在已有仓上滚仓 | **策略交易** |
|
||||
| 位到提醒或自动开仓 | **关键位监控** |
|
||||
| 只做方向 + 保险 | **对冲计划 → 永期**(测算 → 启动) |
|
||||
| 只做上下突破双买 | **对冲计划 → 期期** |
|
||||
| 单独买一张期权并挂目标 | **期权** 页开仓 + 目标监控 |
|
||||
| 看说明 / 改开关 | **系统说明** / **env 配置** / **系统设置** |
|
||||
|
||||
### 1.4 互斥与门禁(总原则)
|
||||
|
||||
- **实盘 ↔ 趋势**:有活跃下单监控或运行中趋势计划时,另一侧不能再开(预览/执行会被挡)。
|
||||
- **滚仓 ↔ 趋势**:有运行中趋势计划时,顺势加仓不可用。
|
||||
- **计仓模式**:`risk`(以损定仓)才允许趋势与多数关键位自动单;`full_margin`(全仓)适合永期对冲与部分触价单,**禁止**趋势/滚仓。切换计仓须无仓后改 env 并重启。
|
||||
- **对冲与期权互斥门控**(默认开):有进行中对冲计划时,不能再「单独开期权」;账户里已有「纯期权」持仓时,不能启动对冲计划。
|
||||
- **半腿失败改手动补开**(默认开):对冲启动一腿成功、一腿失败 → 不自动平已成腿,挂「半腿待补」后在「进行中」补开。
|
||||
- **顶栏可开仓状态**:实盘开关、持仓上限、单日开仓硬上限、冷静期/日冻结、切点前禁开等取交集;细则见 **风控说明**。
|
||||
|
||||
---
|
||||
|
||||
## 二、期权模块
|
||||
|
||||
### 2.1 这块干什么
|
||||
|
||||
在期权账户上:**选合约 → 按卖一限价买入 → 持仓监控 → 买一平仓 / 目标到位平仓**。
|
||||
也是对冲计划期权腿的共用能力。
|
||||
|
||||
### 2.2 操作:开仓
|
||||
|
||||
1. 打开 **期权**,选标的(ETH/BTC)、到期日、Call/Put。
|
||||
2. 看清 **卖一价与深度**:无真实卖一深度时系统禁止开仓(链上带 `~` 的是参考估算,不能当真开仓价)。
|
||||
3. 选张数 / 预算模式后下单。
|
||||
4. 可选填写 **目标指数位**:到位后由目标监控按买一挂平(与对冲计划托管的目标不是同一套执行器)。
|
||||
|
||||
### 2.3 操作:平仓与目标
|
||||
|
||||
- **买一平仓**:按当前买一深度估算可回收金额与净盈亏;注意买卖价差,权利金一侧常见较大滑点。
|
||||
- **目标监控**:手动委托的目标写在期权目标表;**期期对冲**的目标由对冲监控执行,持仓卡上会显示「由对冲计划监控」。
|
||||
- 门控示例:可回收 < 权利金×2 时,目标平仓门控可能未过(保护「太亏别乱平」类规则,以页面提示为准)。
|
||||
|
||||
### 2.4 逻辑:持仓来源
|
||||
|
||||
持仓卡上的 **持仓来源** 表示这条仓和哪类计划绑定:
|
||||
|
||||
| 来源 | 含义 |
|
||||
|------|------|
|
||||
| 纯期权 | 未挂在进行中对冲计划腿上(含手动开、或计划已结束仍留着的仓) |
|
||||
| 永期对冲 #N | 属于进行中永期计划的保险腿 |
|
||||
| 期期对冲 #N | 属于进行中期期计划的腿 |
|
||||
|
||||
判定依据:数据库里进行中计划的 `open` 腿合约 ID。来源会影响互斥门控(「纯期权」会挡住新对冲启动)。
|
||||
|
||||
### 2.5 逻辑:盈亏怎么看
|
||||
|
||||
- **权利金**:买入成本(USDC)。
|
||||
- **按买盘回收**:按当前买一深度卖掉大约能拿回多少。
|
||||
- **净盈亏 ≈ 回收 − 权利金**(页面以买一回收为准,不是单纯看标记价浮动)。
|
||||
- **到期平衡 / 平掉回本**:帮助判断「拿到到期」与「现在平掉」的盈亏分界,属于情景参考。
|
||||
|
||||
### 2.6 更多细则
|
||||
|
||||
期权开平仓字段级说明仍可打开独立页:[期权开平仓与监控说明](/options/guide)。
|
||||
|
||||
---
|
||||
|
||||
## 三、对冲计划
|
||||
|
||||
### 3.1 这块干什么
|
||||
|
||||
把「永续 + 期权」或「期权 + 期权」做成**可测算、可下单、可监控**的计划,与普通交易记录分开。
|
||||
|
||||
| 类型 | 组成 | 核心逻辑 |
|
||||
|------|------|----------|
|
||||
| **永期** | 合约账户永续 + 期权账户保险腿 | 全仓做方向;止盈/止损按规则处理期权 |
|
||||
| **期期** | 期权账户两腿买方 | 上破/下破目标;盈利腿先平,残腿按模式处理 |
|
||||
|
||||
### 3.2 操作:永期
|
||||
|
||||
1. 选 ETH/BTC、做多/做空;看标记价与全仓建议张数。
|
||||
2. 填开仓价、止盈、止损、张数;右侧选期权腿(列表)。
|
||||
3. 点 **计算** → 弹窗看情景测算 → **启动计划** 或取消。
|
||||
4. 启动后在 **进行中的计划** 看状态;细节可点「成交细节」。
|
||||
|
||||
逻辑摘要:
|
||||
|
||||
- 永期开仓通常要求 **全仓计仓** + 实盘与对冲真实下单门禁。
|
||||
- 止盈后是否强平期权、止损后是否强平期权,由 env 开关控制(止损强平默认开,止盈强平默认关)。
|
||||
- 统计口径:止盈多为「永续盈利 − 权利金」;止损多为「期权盈亏 + 永续盈亏」有符号相加(以系统结案字段为准)。
|
||||
- 启动前会校验:合约侧不宜再有「额外」永续仓与永期腿冲突(以页面提示为准)。
|
||||
|
||||
### 3.3 操作:期期
|
||||
|
||||
1. 填上破 / 下破目标;指数价作参考。
|
||||
2. 张数模式:**同张数**(默认)、**做多**、**做空**;平仓模式:**全平**(默认)或 **到期平**(若 env 打开方案 C)。
|
||||
3. T 型报价选用两腿(做多/做空须一 Call 一 Put);可先划转 USDC。
|
||||
4. **计算** → 情景测算 → **启动计划**。
|
||||
|
||||
逻辑摘要:
|
||||
|
||||
- **同张数**:最大 `n` 使两腿各 `n` 张且总权利金 ≤ 预算。
|
||||
- **做多 / 做空**:主腿与次腿按 env 比例(默认 7:3)分配;做多主腿=Call,做空主腿=Put。拆分口径由 `HEDGE_PLAN_OO_BIAS_SPLIT_BY` 决定:`budget`(默认,按权利金预算拆)或 `sheets`(先按同张数算出每腿 `n`,总张数 `2n` 再按比例拆到 Call/Put)。
|
||||
- 达目标价:通常只平盈利腿。
|
||||
- **全平**:盈利腿平掉后立刻尝试清另一腿(无 2× 权利金门控,失败会重试)。
|
||||
- **到期平**:残腿持有至到期再结。
|
||||
- 旧计划若无平仓模式字段,按「到期平」更安全的口径处理。
|
||||
|
||||
### 3.4 半腿失败与手动补开
|
||||
|
||||
启动时两腿要连续下单。若一腿成功、一腿失败:
|
||||
|
||||
| 配置 | 行为 |
|
||||
|------|------|
|
||||
| **半腿失败改手动补开 = 开**(默认) | 已成腿留下;计划状态 **半腿待补**;「进行中」出现 **补开永续 / 补开腿B / 补开期权**;**不会**自动买一平已成腿 |
|
||||
| 手动补开 = 关,且自动平 = 开 | 尝试自动平掉已成期权腿(会吃买卖价差,几乎必亏一笔) |
|
||||
|
||||
操作建议:半腿出现后,先看失败原因(深度、余额、权限),再点补开;确认补开会真实下单。
|
||||
|
||||
### 3.5 情景测算弹窗
|
||||
|
||||
测算不再占页面下方大块区域:点 **计算** 弹出结果,底部 **启动计划 / 取消**。
|
||||
取消只关窗;启动按当前参数真实下单(仍受门禁约束)。
|
||||
期期弹窗:合计盈亏绿/红配色;摘要显示盈亏比(盈利÷全额保费,亏损按权利金全亏计)。
|
||||
|
||||
### 3.6 进行中 / 历史 / 统计
|
||||
|
||||
- **进行中**:含 `opening` / `active` / `partial`。半腿待补可补开。
|
||||
- **历史**:已结束计划与成交细节。
|
||||
- **统计**:按永期 / 期期分别看胜率、盈亏比、最大盈亏与回撤等(按结束时间累积)。
|
||||
- 对冲成交 **不进** 普通「交易记录与复盘」/「策略交易记录」。
|
||||
|
||||
---
|
||||
|
||||
## 四、实盘下单
|
||||
|
||||
### 4.1 这块干什么
|
||||
|
||||
合约账户上的 **人工永续开仓 + 下单监控**:提交后进入监控列表,轮询标记价与交易所止盈止损,支持改委托、手动平仓、移动保本、时间平等;平仓后进 **交易记录与复盘**。
|
||||
|
||||
### 4.2 操作
|
||||
|
||||
1. 打开 **实盘下单**,选币种、方向。
|
||||
2. 选止盈止损模式(固定盈亏比 / 价格 / 百分比等,以页面选项为准)。
|
||||
3. 趋势类账户可再选开仓类型(反转 / 顺势 / 波段等);Gate 日内类账户选项更窄,且可能无移动保本 / 时间平。
|
||||
4. 填止损与止盈(或 RR),看 **预估盈亏比** 与计划预览。
|
||||
5. 确认开仓(按钮文案随「是否实盘」变化;关实盘时不会发交易所单)。
|
||||
6. 右侧 **实时持仓**:看浮盈亏、交易所 TP/SL;用 **委托** 改止盈止损,或 **平仓** 全平。
|
||||
7. 需要时点 **放大 K 线**;若交易所已有仓但本地无监控,可用 **恢复监控**(孤儿仓恢复)。
|
||||
8. 结束后到 **交易记录与复盘** / **统计分析** 查看。
|
||||
|
||||
### 4.3 逻辑与门禁
|
||||
|
||||
| 项 | 说明 |
|
||||
|----|------|
|
||||
| `LIVE_TRADING_ENABLED` | 关则不发真单,仅本地流程 |
|
||||
| `MANUAL_MIN_PLANNED_RR` | 人工开仓计划 RR 下限(表单 + 服务端) |
|
||||
| `POSITION_SIZING_MODE` | `risk` 以损定仓 / `full_margin` 全仓;须无仓切换并重启 |
|
||||
| `can_trade` 交集 | 持仓上限、单日开仓硬上限、冷静期、切点前禁开等 |
|
||||
| 方向 / 币种白名单 | 账户策略限制时,不符合的单会被拒 |
|
||||
|
||||
三所核心流程一致;折叠区「开仓规则说明」文案按交易所模板略有不同。
|
||||
|
||||
### 4.4 与策略 / 期权 / 对冲的关系
|
||||
|
||||
- 与 **趋势回调** 互斥(见 1.4);**顺势加仓** 必须先有本页同向活跃监控单。
|
||||
- 期权 / 对冲互斥门控 **不拦** 本页永续单。
|
||||
- 永期计划 active 时,合约侧不宜再挂「额外」永续仓(启动对冲前会校验)。
|
||||
- 关键位自动开仓成交后,也会进入同一套 **下单监控**。
|
||||
|
||||
### 4.5 常见问题
|
||||
|
||||
**Q:预估 RR 已经够绿,仍开不了?**
|
||||
A:看顶栏 / 返回文案:满仓、日上限、冷静期、方向白名单、实盘关、服务端 RR 口径等。
|
||||
|
||||
**Q:交易所有仓,本页没有监控?**
|
||||
A:用孤儿仓 **恢复监控**;不要另开一笔同向重复仓。
|
||||
|
||||
---
|
||||
|
||||
## 五、策略交易
|
||||
|
||||
### 5.1 这块干什么
|
||||
|
||||
自动化永续策略页:**趋势回调**(预览 → 分档补仓计划)与 **顺势加仓**(在已有同向监控持仓上滚仓)。执行历史在 **策略交易记录**。
|
||||
部分「日内纪律」类账户整 Tab 隐藏,以导航是否出现为准。
|
||||
|
||||
### 5.2 操作:趋势回调
|
||||
|
||||
1. 填币种、方向、杠杆、风险%、止损、补仓边界(多=上沿 / 空=下沿)、止盈。
|
||||
2. **生成预览**(有短时效;用快照余额算张数)。
|
||||
3. 核对预览表后 **确认执行(实盘)**。
|
||||
4. 运行中可看补仓档与浮盈亏;可 **手动保本**,或 **保本移交下单监控**(计划结束,仓交给实盘监控继续管)。
|
||||
5. **结束计划** 或止盈止损自动结束后,写入策略记录与交易记录(类型「趋势回调」)。
|
||||
|
||||
### 5.3 操作:顺势加仓
|
||||
|
||||
1. 先在 **实盘下单** 有一条 **同向** 活跃监控单。
|
||||
2. 选持仓、加仓模式(市价 / 斐波 / 突破等)、新止损 → **执行滚仓**(无预览步;同时通常只允许一条监控中滚仓腿)。
|
||||
3. 注意次数上限(如做多/做空各最多若干次已成交腿)与首仓 TP 锁定规则,以页面提示为准。
|
||||
|
||||
### 5.4 逻辑与门禁
|
||||
|
||||
| 项 | 说明 |
|
||||
|----|------|
|
||||
| 实盘 + 计仓 | 须 `LIVE_TRADING_ENABLED=true` 且 `POSITION_SIZING_MODE=risk`;全仓模式禁止趋势与滚仓 |
|
||||
| 与下单监控互斥 | 有活跃监控单或运行中趋势时,不能开另一侧预览/执行 |
|
||||
| 与滚仓互斥 | 运行中趋势时滚仓按钮禁用 |
|
||||
| 余额漂移 | 预览后余额变化过大(约 5%)须重新预览 |
|
||||
| 单日开仓上限 | 与人工开仓共用计数,同样可拦预览/执行 |
|
||||
|
||||
### 5.5 与期权 / 对冲
|
||||
|
||||
独立模块:不走对冲计划状态机;记录进策略库 / 普通交易记录,**不进** 对冲历史与对冲统计。
|
||||
OKX 上可与期权/对冲并存,但仍须遵守合约侧「永期不得另挂额外永续仓」等规则。
|
||||
|
||||
### 5.6 常见问题
|
||||
|
||||
**Q:触价到了却没补仓?**
|
||||
A:看页面 `block_reason`:实盘关、余额漂移、最小张数减档、日上限等。
|
||||
|
||||
**Q:中控「策略说明」是不是本页手册?**
|
||||
A:不是。中控策略说明是玩法 playbook;本说明书讲本系统如何操作与门禁。
|
||||
|
||||
---
|
||||
|
||||
## 六、关键位监控
|
||||
|
||||
### 6.1 这块干什么
|
||||
|
||||
配置 **关键价位**(常见 5m 门控):支撑/阻力可 **微信提醒**;箱体/收敛/触价等类型可在开关打开后 **程序自动开仓**,成交后进入 **实盘下单监控**。
|
||||
|
||||
### 6.2 操作
|
||||
|
||||
1. 打开 **关键位监控**,选类型、币种、方向,填上下沿 / 触价 / E·SL·TP 等。
|
||||
2. 箱体类可选 SL/TP 方案、移动保本、时间平等(以类型是否支持为准)。
|
||||
3. **添加** 后在列表看现价、距沿距离、**门控** 状态;不需要则 **删除**。
|
||||
4. 右侧 **关键位历史** 看失效 / 成交 / 提醒完成等原因。
|
||||
5. 可用 **放大 K 线** 辅助画位。
|
||||
|
||||
### 6.3 类型与开关(逻辑)
|
||||
|
||||
| 类型(概括) | 关键位自动单开关 | 全仓模式 |
|
||||
|--------------|------------------|----------|
|
||||
| 关键支撑阻力 | 不需要(仅提醒) | 可用 |
|
||||
| 箱体 / 收敛 / 斐波 / 假突破等 | 需要开启,且一般为 `risk` 计仓 | **不可用**(添加会拒;已有位在全仓下可能被撤销并通知) |
|
||||
| 回调 / 突破触价开仓 | 需要开启 | **可用**(全仓下常见的自动单路径) |
|
||||
|
||||
其它要点:
|
||||
|
||||
- `KEY_AUTO_MIN_PLANNED_RR`:自动单计划 RR 须严格大于该值(默认约 1.5)。
|
||||
- 箱体类门控常含双 K 确认、突破幅度、量能、24h 成交额排名等(阈值见 env,改后多需重启)。
|
||||
- 自动成交计入 **单日开仓次数**,并受 `can_trade`、持仓上限、冷静期约束。
|
||||
- 假突破等类型可能仅限 BTC/ETH,且同币种条数有限,以页面校验为准。
|
||||
|
||||
### 6.4 与期权 / 对冲
|
||||
|
||||
无直接耦合。自动开仓写入下单监控后,与期权/对冲并行存在;若同时做永期,注意合约侧持仓冲突。
|
||||
|
||||
### 6.5 常见问题
|
||||
|
||||
**Q:开了「关键位自动单」仍只有支撑阻力可选?**
|
||||
A:检查是否 **全仓模式**,或自动单开关实际未生效(改后是否重启)。
|
||||
|
||||
**Q:微信提醒有了却没开仓?**
|
||||
A:可能是仅提醒类型、门控未过、RR 不足、满仓/日上限,或实盘/可开仓状态未过。
|
||||
|
||||
---
|
||||
|
||||
## 七、env 与系统设置(和说明书相关的部分)
|
||||
|
||||
### 7.1 系统设置 → 导航显示
|
||||
|
||||
控制顶栏是否出现各板块。「系统说明」默认关闭,打开后顶栏才显示入口。
|
||||
|
||||
### 7.2 env → 交易与关键位(常用)
|
||||
|
||||
| 开关 | 作用 |
|
||||
|------|------|
|
||||
| 实盘交易 | 关则人工/策略/自动单都不发真单(对冲另有「允许真实下单」) |
|
||||
| 计仓模式 | `risk` / `full_margin`;决定策略与多数关键位自动单能否用 |
|
||||
| 人工最小计划 RR | 实盘下单 RR 下限 |
|
||||
| 关键位自动单 | 关则箱体等不自动开仓;支撑阻力提醒仍可用 |
|
||||
| 关键位自动单最小 RR | 自动开仓 RR 下限 |
|
||||
|
||||
### 7.3 env → 对冲计划(常用)
|
||||
|
||||
| 开关 | 作用 |
|
||||
|------|------|
|
||||
| 启用对冲计划 | 总开关;关则导航隐藏且不可开仓 |
|
||||
| 显示永期 / 期期 | 单独隐藏某一 Tab |
|
||||
| 允许对冲真实下单 | 与实盘开关一起才可启动永期 |
|
||||
| 对冲与期权互斥门控 | 见 1.4 |
|
||||
| 半腿失败改手动补开 | 见 3.4 |
|
||||
| 半腿失败时自动平期权 | 手动补开开启时强制无效 |
|
||||
| 期期平仓模式(方案 C) | 页面是否出现「全平 / 到期平」 |
|
||||
| 期期做多做空拆分口径 | `budget` 预算金额(默认)/ `sheets` 张数 |
|
||||
| 期期做多做空主腿占比 | 默认 `0.7`(即 7:3) |
|
||||
|
||||
含「需重启」标记的项保存后要用「保存并重启」;对冲多数开关可热更,以页面标注为准。
|
||||
|
||||
---
|
||||
|
||||
## 八、常见问题
|
||||
|
||||
**Q:为什么有对冲计划时单独开不了期权?**
|
||||
A:互斥门控默认开启,避免计划仓与手开仓搅在一起。可在 env 关闭互斥。
|
||||
|
||||
**Q:为什么有一张「纯期权」就启动不了对冲?**
|
||||
A:同上。先平掉或确认来源;若其实是对冲腿,看持仓来源是否显示计划编号。
|
||||
|
||||
**Q:半腿后为什么不自动平?**
|
||||
A:默认改手动补开,避免买一平仓吃掉 ≥10% 量级价差。到「进行中」补开即可。
|
||||
|
||||
**Q:测算能过但启动按钮灰?**
|
||||
A:看顶部门禁行:全仓、实盘、真实下单、活跃计划数、互斥、Tab 是否隐藏等。
|
||||
|
||||
**Q:为什么策略页不能预览 / 滚仓灰掉?**
|
||||
A:常见原因:全仓模式、实盘关、已有活跃下单监控或运行中趋势、日上限。见第四、五章。
|
||||
|
||||
**Q:关键位只提醒不开仓?**
|
||||
A:支撑阻力本就只提醒;其它类型看自动单开关、计仓模式、门控与 RR。见第六章。
|
||||
|
||||
**Q:说明书和「风控说明」什么关系?**
|
||||
A:风控说明仍是独立页(冷却、当日次数等细则)。本说明书讲板块逻辑与操作;风控细则以风控说明 + env 为准。
|
||||
|
||||
---
|
||||
|
||||
## 九、版本与维护
|
||||
|
||||
- 文档路径:`docs/系统说明.md`
|
||||
- 功能变更后应同步改本章(尤其门禁、半腿、互斥、计仓、关键位自动单、平仓模式)。
|
||||
- 更偏开发/方案的材料仍在 `docs/对冲计划*.md`、`docs/期权对冲方案分析.md`、策略专项 md 等,不必与本说明书一一粘贴。
|
||||
@@ -0,0 +1,50 @@
|
||||
# 著作权声明
|
||||
|
||||
## 作品信息
|
||||
|
||||
| 项 | 内容 |
|
||||
|----|------|
|
||||
| 作品名称 | crypto_monitor(加密货币交易监控与中控系统) |
|
||||
| 作品形式 | 计算机软件及相关技术文档 |
|
||||
| 著作权人 | 马建军 |
|
||||
| 联系电话 | 18364911125 |
|
||||
| 权利主张起始 | 2026 年(以本仓库首次提交及后续持续开发为准) |
|
||||
|
||||
## 权利声明
|
||||
|
||||
本仓库所含下列内容之著作权归 **马建军** 所有:
|
||||
|
||||
1. 源代码、脚本、配置模板与部署相关文件;
|
||||
2. 界面文案、说明文档、执行手册、策略与设计类文档;
|
||||
3. 由著作权人创作并纳入本仓库的图表、脑图及其他配套材料。
|
||||
|
||||
**Copyright © 2026 马建军. 保留所有权利。**
|
||||
|
||||
未经著作权人书面许可,任何单位或个人不得擅自:
|
||||
|
||||
- 复制、传播、公开披露本仓库全部或部分内容;
|
||||
- 出售、出租、赠与或以任何方式向第三方提供本软件或其衍生版本;
|
||||
- 删除或篡改本声明及表明著作权归属的标识。
|
||||
|
||||
本仓库计划以私有方式保存;私有并不影响著作权人对本作品享有的权利。
|
||||
|
||||
## 证明与版本痕迹
|
||||
|
||||
本作品的创作过程以 Git 提交历史、远程私有仓库记录及快照标签(如 `snapshot/*`)为时间线依据。著作权主张以本声明与上述开发痕迹为准。
|
||||
|
||||
## 免责(与著作权并列说明)
|
||||
|
||||
本软件及相关文档仅供著作权人授权范围内的交易辅助与内部使用。市场有风险,交易决策与盈亏由使用者自行承担;本声明不构成任何投资建议。
|
||||
|
||||
## 对外提供方式
|
||||
|
||||
著作权人对外提供本软件的**默认方式**为:由著作权人为每位客户提供**专属服务器**(一用户一服务器,不与其他客户共用同一台机器)与部署,客户通过访问地址与账号使用,并缴纳服务器费、域名费、部署费及程序使用费;**不交付源代码**。
|
||||
|
||||
对外托管或授权使用时,请签署《托管服务与软件使用合同》(模板见同目录 `软件使用授权合同-模板.md`)。服务定位、适用对象与参考报价见 `服务说明与报价说明.md`。未签署有效合同的,除著作权人本人外,任何人均无权使用、复制或传播本软件。
|
||||
|
||||
## 联系
|
||||
|
||||
- 著作权人:马建军
|
||||
- 电话:18364911125
|
||||
|
||||
本声明随仓库版本一并维护;如有更新,以仓库中最新文本为准。
|
||||
@@ -0,0 +1,192 @@
|
||||
# 托管服务与软件使用合同(模板)
|
||||
|
||||
> 说明:本文为**合同模板**,适用于甲方(马建军)提供**专属服务器**与部署、乙方通过网页/账号使用软件、**不交付源码**的托管模式。
|
||||
> **一用户一服务器**:每位客户单独一台(套)服务器,不与其他客户共用同一台服务器。
|
||||
> 与仓库内《著作权声明》配套:声明主张权利;本合同约定服务范围、费用与使用边界。
|
||||
> 签署前请双方核对条款;金额较大或长期合作,建议再请律师审阅。
|
||||
|
||||
---
|
||||
|
||||
**合同编号:** ________________
|
||||
**签订日期:** ______ 年 ____ 月 ____ 日
|
||||
**签订地点:** ________________
|
||||
|
||||
## 甲方(服务提供方 / 著作权人)
|
||||
|
||||
| 项 | 内容 |
|
||||
|----|------|
|
||||
| 姓名 | 马建军 |
|
||||
| 联系电话 | 18364911125 |
|
||||
| 身份证件号码 | ________________(签署时填写) |
|
||||
| 住址 | ________________(签署时填写,选填) |
|
||||
|
||||
## 乙方(客户 / 使用方)
|
||||
|
||||
| 项 | 内容 |
|
||||
|----|------|
|
||||
| 姓名 / 名称 | ________________ |
|
||||
| 证件类型及号码 | ________________ |
|
||||
| 联系电话 | ________________ |
|
||||
| 住址 / 住所地 | ________________(选填) |
|
||||
|
||||
甲乙双方就甲方在其控制的服务器上部署、运维 `crypto_monitor`(加密货币交易监控与中控系统,以下称「本软件」),并向乙方提供**托管使用服务**,经协商一致,订立本合同。
|
||||
|
||||
---
|
||||
|
||||
## 第一条 服务内容与交付方式
|
||||
|
||||
1.1 **服务模式**:甲方为乙方提供**专属**云服务器(或等价专属托管环境)、域名解析(或子域名)、程序部署与运行维护;乙方通过甲方提供的 **访问地址与账号** 使用本软件,**不交付、不提供** 源代码、私有仓库权限、部署脚本全集或可用于独立重建系统的技术资料。
|
||||
|
||||
1.2 **一用户一服务器**:本合同项下服务器**仅供乙方使用**,不与其他客户共用同一台服务器、同一操作系统实例或同一套生产部署环境。甲方不得将其他客户的程序、数据或账号部署于本合同约定的专属服务器上。
|
||||
|
||||
1.3 **交付物**(勾选实际提供项):
|
||||
- [ ] 专属服务器标识 / 实例 ID(选填):________________
|
||||
- [ ] 中控访问地址:________________
|
||||
- [ ] 实例访问地址(交易所):________________ / ________________ / ________________
|
||||
- [ ] 登录账号:________________(或另行发放)
|
||||
- [ ] 使用说明 / 培训(____ 次,每次 ____ 分钟,选填)
|
||||
|
||||
1.4 **不包含**(除非另签书面补充协议并另付费):源码转让、源码只读权限、独立私有化部署包、二次开发源代码交付、数据库完整镜像导出用于迁移至第三方系统、服务器 root/控制台账号移交(服务器由甲方代持运维)。
|
||||
|
||||
1.5 本软件著作权及部署架构归甲方所有。专属服务器的云账号/机器所有权或租赁关系由甲方管理,乙方取得的是**该服务器上本软件的有限使用权**,不转让著作权、商标权、服务器所有权及其他知识产权。
|
||||
|
||||
---
|
||||
|
||||
## 第二条 授权范围与使用限制
|
||||
|
||||
2.1 **授权性质**:普通、非独占、不可再许可;仅限本合同约定的**专属服务器**及域名/访问地址范围内使用。
|
||||
|
||||
2.2 **使用主体**:仅限乙方本人及经甲方书面确认的 ______ 名操作人员;账号不得转借、共享给合同外第三方。
|
||||
|
||||
2.3 **使用目的**:仅限乙方自身交易辅助、内部监控与运营;不得将本软件或实质相同的功能作为产品/服务向不特定公众或第三方收费提供。
|
||||
|
||||
2.4 **服务期限**:
|
||||
- 自 ______ 年 ____ 月 ____ 日起,至 ______ 年 ____ 月 ____ 日止;
|
||||
- 期满前 ______ 日双方可协商续签;期满未续费且未书面延期的,甲方有权停服并回收该专属服务器资源。
|
||||
|
||||
2.5 乙方不得实施下列行为:
|
||||
1. 要求或试图获取源码、Git 仓库、服务器 root/云控制台权限(合同另有约定的除外);
|
||||
2. 复制、传播、截图外传足以重建系统的架构说明、配置全集或程序文件;
|
||||
3. 对系统进行反向工程、抓包重建、或委托他人仿制同类托管产品对外经营;
|
||||
4. 将访问账号、域名、API 密钥用于合同约定外的用途或转售;
|
||||
5. 攻击、扫描本合同专属服务器或甲方其他基础设施。
|
||||
|
||||
---
|
||||
|
||||
## 第三条 费用与支付
|
||||
|
||||
3.1 乙方按下列项目向甲方支付费用(勾选并填写金额;可打包为「标准套餐价」并在备注中列明分项):
|
||||
|
||||
| 费用项目 | 说明 | 金额(元) | 计费周期 |
|
||||
|----------|------|------------|----------|
|
||||
| 服务器费用 | **乙方专属**云主机、带宽、磁盘等(不与其他客户分摊同一台机器) | ¥ ______ | □月付 □年付 |
|
||||
| 域名费用 | 域名注册/续费(域名归属:□甲方代持 □乙方自有,解析由甲方配置) | ¥ ______ | □年付 |
|
||||
| 部署费用 | 在专属服务器上首次环境搭建、证书、实例与中控上线(一次性) | ¥ ______ | 一次性 |
|
||||
| 程序使用费 | 本软件托管使用权、日常更新与基础运维 | ¥ ______ | □月付 □年付 |
|
||||
|
||||
3.2 **合计**(首年 / 首月应付):人民币(大写)________________ 元整(¥ ________)。
|
||||
|
||||
3.3 **支付方式与时间**:________________(如:签约后 ____ 日内付部署费+首周期费用;之后每 ____ 提前 ____ 日支付续费)。
|
||||
|
||||
3.4 **续费**:服务期满前,乙方按 3.1 约定支付下一周期费用;逾期超过 ______ 日未付的,甲方有权暂停服务;逾期超过 ______ 日仍未付的,甲方有权解除合同并停服,已付未消费部分按实际服务天数抵扣后退还(部署费是否退还:□不退 □按约定 ________________)。
|
||||
|
||||
3.5 **价格调整**:续签时,因云厂商涨价、域名涨价或功能范围扩大,甲方可提前 ______ 日书面通知调整后续周期价格;乙方不同意调整的,可在当前周期结束后不再续签。
|
||||
|
||||
3.6 [ ] 本次为试用 / 友情托管:期限至 ______,费用减免 ________________,乙方仍须遵守第二条全部限制。
|
||||
|
||||
---
|
||||
|
||||
## 第四条 部署、运维与更新
|
||||
|
||||
4.1 **甲方责任**(合理范围内):
|
||||
- 按约定完成首次部署并使乙方可以登录使用;
|
||||
- 程序版本更新、安全补丁、PM2/进程异常重启等**基础运维**(具体 SLA:________________,如「工作日 24 小时内响应」);
|
||||
- 因交易所 API 变更导致的**常规适配**(重大重构另议)。
|
||||
|
||||
4.2 **乙方责任**:
|
||||
- 提供合法有效的交易所 API 等密钥信息,并保证账户使用合规;
|
||||
- 妥善保管登录密码;因乙方泄露导致的损失由乙方承担;
|
||||
- 按约定及时支付各项费用。
|
||||
|
||||
4.3 **数据**:乙方在系统中的交易记录、配置等业务数据归属乙方,并存放于本合同专属服务器;甲方为运维可接触相关数据,但不得用于合同约定外的目的,亦不得将乙方数据混存于其他客户服务器。合同终止后,乙方可申请导出**业务数据**(格式:________________,费用:________________);**不包含**源码与部署环境镜像。
|
||||
|
||||
4.4 **停服与备份**:甲方在停服前 ______ 日通知乙方(因乙方欠费紧急停服除外);停服后该专属服务器上的数据保留 ______ 日,逾期可删除并释放服务器资源。
|
||||
|
||||
---
|
||||
|
||||
## 第五条 保密
|
||||
|
||||
5.1 乙方对知悉的本软件存在、界面逻辑、非公开功能、报价及甲方技术方案负有保密义务。
|
||||
|
||||
5.2 甲方对乙方的 API 密钥、账户信息负有保密义务,除运维必需与法律要求外不得向第三方披露。
|
||||
|
||||
5.3 保密期限:合同存续期间及终止后 ______ 年(未填则视为 5 年)。
|
||||
|
||||
---
|
||||
|
||||
## 第六条 免责与风险提示
|
||||
|
||||
6.1 本软件为交易辅助工具,不构成投资建议。市场有风险,乙方交易决策与盈亏自行承担。
|
||||
|
||||
6.2 因行情、交易所接口变更、网络故障、云厂商故障、乙方误操作等导致的交易或间接损失,在法律允许范围内甲方不承担责任;因甲方故意或重大过失造成的服务长时间不可用除外(可约定:连续不可用超过 ____ 小时按比例退还当期程序使用费)。
|
||||
|
||||
6.3 甲方保证其有权提供本托管服务并享有本软件著作权;乙方保证身份信息及资金账户来源合法。
|
||||
|
||||
---
|
||||
|
||||
## 第七条 违约责任
|
||||
|
||||
7.1 乙方欠费、外传账号、试图获取源码或违反第二条的,甲方有权**暂停或立即终止服务**,并要求:
|
||||
1. 停止违约行为;
|
||||
2. 支付欠费及违约金人民币 ________ 元(或按实际损失);
|
||||
3. 赔偿甲方维权合理费用。
|
||||
|
||||
7.2 甲方无正当理由逾期未完成首次部署超过 ______ 日,或恶意长期停服且无合理解释的,乙方有权解除合同并要求退还已付未消费部分(部署费处理按 3.4 约定)。
|
||||
|
||||
---
|
||||
|
||||
## 第八条 合同解除与终止
|
||||
|
||||
8.1 协商一致可书面解除。
|
||||
|
||||
8.2 一方严重违约,守约方书面通知后 ______ 日内仍未改正的,守约方可解除。
|
||||
|
||||
8.3 终止后:乙方停止使用;甲方关闭访问权限;双方按第四条、第五条履行数据与保密义务。
|
||||
|
||||
---
|
||||
|
||||
## 第九条 争议解决
|
||||
|
||||
因本合同引起的争议,双方协商解决;协商不成的,提交甲方住所地有管辖权的人民法院诉讼解决(或:提交 ________ 仲裁委员会仲裁)。
|
||||
|
||||
---
|
||||
|
||||
## 第十条 其他
|
||||
|
||||
10.1 未尽事宜可签订补充协议。
|
||||
|
||||
10.2 本合同一式贰份,甲乙双方各执壹份,具有同等法律效力。
|
||||
|
||||
10.3 附件(如有):□《著作权声明》副本 □《服务说明与报价说明》 □ 服务清单 / 报价单 □ 域名与实例列表 □ 其他:________
|
||||
|
||||
---
|
||||
|
||||
## 签署栏
|
||||
|
||||
**甲方(服务提供方 / 著作权人):**
|
||||
|
||||
签名:________________ 日期:______ 年 ____ 月 ____ 日
|
||||
|
||||
**乙方(客户):**
|
||||
|
||||
签名 / 盖章:________________ 日期:______ 年 ____ 月 ____ 日
|
||||
|
||||
---
|
||||
|
||||
## 填写提示(签署前可删本段)
|
||||
|
||||
1. **标准商业路径**:专属服务器费 + 域名费 + 部署费(首单)+ 程序使用费(按月/年)— 四项建议在报价单里写清,合同 3.1 表格与报价一致。
|
||||
2. **一用户一服务器**:新客户开新机器;不要把多名客户塞进同一台 VPS。
|
||||
3. **源码**:默认一律不交付;若客户坚持私有化,应另签高价「源码许可/买断」合同,与本托管模板分开。
|
||||
4. **自用**:著作权人本人使用无需签本合同,见《著作权声明》。
|
||||
5. **不要**在仓库添加开源 `LICENSE`(MIT 等),与「保留所有权利 + 托管授权」冲突。
|
||||
@@ -0,0 +1,148 @@
|
||||
/**
|
||||
* 全局防浏览器自动填充登录账号/密码进业务输入框.
|
||||
* 跳过真正的登录/改密字段;对划转数量等易中招框用 readonly 到聚焦.
|
||||
*/
|
||||
(function () {
|
||||
"use strict";
|
||||
|
||||
var GUARD_ATTRS = {
|
||||
autocomplete: "off",
|
||||
autocorrect: "off",
|
||||
autocapitalize: "off",
|
||||
spellcheck: "false",
|
||||
"data-lpignore": "true",
|
||||
"data-1p-ignore": "true",
|
||||
"data-bwignore": "true",
|
||||
"data-form-type": "other",
|
||||
};
|
||||
|
||||
function looksLikeUsername(v) {
|
||||
return /^[a-z][a-z0-9._-]{1,31}$/i.test(String(v || "").trim());
|
||||
}
|
||||
|
||||
function isAuthField(el) {
|
||||
if (!el || !el.getAttribute) return true;
|
||||
var t = String(el.type || "").toLowerCase();
|
||||
if (t === "hidden" || t === "checkbox" || t === "radio" || t === "file" || t === "submit" || t === "button") {
|
||||
return true;
|
||||
}
|
||||
if (el.getAttribute("aria-hidden") === "true") return true;
|
||||
if (el.tabIndex === -1 && String(el.getAttribute("autocomplete") || "").toLowerCase() === "username") {
|
||||
return true; // 诱饵账号框
|
||||
}
|
||||
var idName = String(el.id || "") + " " + String(el.name || "");
|
||||
if (/^(pwd-|hub-pwd-|login-)/i.test(String(el.id || ""))) return true;
|
||||
if (el.closest) {
|
||||
if (el.closest(".login-form, #login-form, form.login-form, .password-settings, [data-password-settings]")) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
// env API Key 等 type=password 仍要防登录密码灌入,不在此跳过
|
||||
if (t === "password" && /^(username|password)$/i.test(String(el.name || ""))) {
|
||||
if (el.closest && el.closest("form[method='post'], form[method='POST']")) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function isAmountLike(el) {
|
||||
var key = String(el.id || "") + " " + String(el.name || "") + " " + String(el.placeholder || "");
|
||||
return /amount|xfer|transfer|划转|数量|金额/i.test(key);
|
||||
}
|
||||
|
||||
function wipeBad(el) {
|
||||
if (!el || isAuthField(el)) return;
|
||||
var v = String(el.value || "").trim();
|
||||
if (!looksLikeUsername(v)) return;
|
||||
var t = String(el.type || "text").toLowerCase();
|
||||
if (t === "number" || isAmountLike(el) || /price|sheets|qty|sl|tp|target|entry|strike/i.test(String(el.id || "") + String(el.name || ""))) {
|
||||
el.value = "";
|
||||
}
|
||||
}
|
||||
|
||||
function harden(el) {
|
||||
if (!el || el.nodeType !== 1) return;
|
||||
if (isAuthField(el)) return;
|
||||
if (el.getAttribute("aria-hidden") === "true") return;
|
||||
if (el.dataset && el.dataset.autofillGuarded === "1") {
|
||||
wipeBad(el);
|
||||
return;
|
||||
}
|
||||
if (el.dataset) el.dataset.autofillGuarded = "1";
|
||||
|
||||
Object.keys(GUARD_ATTRS).forEach(function (k) {
|
||||
var cur = el.getAttribute(k);
|
||||
if (k === "autocomplete" && cur && /^(username|current-password)/i.test(cur)) {
|
||||
return;
|
||||
}
|
||||
// env 密钥框用 new-password 更抗登录密码灌入
|
||||
if (k === "autocomplete" && String(el.type || "").toLowerCase() === "password") {
|
||||
el.setAttribute(k, "new-password");
|
||||
return;
|
||||
}
|
||||
if (!cur || cur === "on") el.setAttribute(k, GUARD_ATTRS[k]);
|
||||
});
|
||||
|
||||
if (String(el.type || "").toLowerCase() === "password" || isAmountLike(el)) {
|
||||
el.setAttribute("readonly", "readonly");
|
||||
el.addEventListener("focus", function () {
|
||||
el.removeAttribute("readonly");
|
||||
});
|
||||
el.addEventListener("blur", function () {
|
||||
if (!el.value) el.setAttribute("readonly", "readonly");
|
||||
});
|
||||
}
|
||||
|
||||
wipeBad(el);
|
||||
setTimeout(function () {
|
||||
wipeBad(el);
|
||||
}, 250);
|
||||
setTimeout(function () {
|
||||
wipeBad(el);
|
||||
}, 900);
|
||||
setTimeout(function () {
|
||||
wipeBad(el);
|
||||
}, 2000);
|
||||
}
|
||||
|
||||
function scan(root) {
|
||||
var scope = root && root.querySelectorAll ? root : document;
|
||||
var list = scope.querySelectorAll(
|
||||
'input[type="text"], input[type="number"], input[type="search"], input[type="url"], input[type="email"], input[type="tel"], input[type="password"], input:not([type]), textarea'
|
||||
);
|
||||
for (var i = 0; i < list.length; i++) harden(list[i]);
|
||||
}
|
||||
|
||||
function boot() {
|
||||
scan(document);
|
||||
if (typeof MutationObserver === "undefined") return;
|
||||
var obs = new MutationObserver(function (mutations) {
|
||||
for (var i = 0; i < mutations.length; i++) {
|
||||
var m = mutations[i];
|
||||
if (m.type === "childList") {
|
||||
for (var j = 0; j < m.addedNodes.length; j++) {
|
||||
var n = m.addedNodes[j];
|
||||
if (!n || n.nodeType !== 1) continue;
|
||||
if (n.matches && n.matches("input, textarea")) harden(n);
|
||||
else if (n.querySelectorAll) scan(n);
|
||||
}
|
||||
} else if (m.type === "attributes" && m.target) {
|
||||
harden(m.target);
|
||||
}
|
||||
}
|
||||
});
|
||||
obs.observe(document.documentElement, {
|
||||
childList: true,
|
||||
subtree: true,
|
||||
attributes: true,
|
||||
attributeFilter: ["value"],
|
||||
});
|
||||
}
|
||||
|
||||
if (document.readyState === "loading") {
|
||||
document.addEventListener("DOMContentLoaded", boot);
|
||||
} else {
|
||||
boot();
|
||||
}
|
||||
|
||||
window.cmAutofillGuardScan = scan;
|
||||
})();
|
||||
+721
-115
File diff suppressed because it is too large
Load Diff
@@ -15,6 +15,7 @@
|
||||
records: "/records",
|
||||
stats: "/stats",
|
||||
risk_policy: "/risk_policy",
|
||||
system_guide: "/system_guide",
|
||||
env_config: "/env_config",
|
||||
settings: "/settings",
|
||||
};
|
||||
@@ -60,6 +61,11 @@
|
||||
document.querySelectorAll(".embed-top-nav [data-embed-tab]").forEach((a) => {
|
||||
a.classList.toggle("active", a.getAttribute("data-embed-tab") === tab);
|
||||
});
|
||||
if (global.InstanceMobileNav && typeof global.InstanceMobileNav.onTabChange === "function") {
|
||||
global.InstanceMobileNav.onTabChange(tab);
|
||||
} else if (global.InstanceMobileNav && typeof global.InstanceMobileNav.syncTabActive === "function") {
|
||||
global.InstanceMobileNav.syncTabActive(tab);
|
||||
}
|
||||
}
|
||||
|
||||
function pageNavAllowed(tab) {
|
||||
@@ -234,9 +240,57 @@
|
||||
const parts = [];
|
||||
if (qs) parts.push(qs);
|
||||
parts.push("embed=1");
|
||||
if (tab === "settings") {
|
||||
try {
|
||||
const st = new URLSearchParams(location.search).get("settings_tab");
|
||||
if (st) parts.push("settings_tab=" + encodeURIComponent(st));
|
||||
} catch (_) {}
|
||||
}
|
||||
return url + "?" + parts.join("&");
|
||||
}
|
||||
|
||||
function setSettingsSubTabInUrl(key) {
|
||||
if (!key) return;
|
||||
try {
|
||||
const q = new URLSearchParams(location.search);
|
||||
q.set("tab", "settings");
|
||||
q.set("settings_tab", key);
|
||||
q.set("embed", "1");
|
||||
history.replaceState(null, "", "/embed?" + q.toString());
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
function activateSettingsSubTab(key) {
|
||||
if (!key) return;
|
||||
setSettingsSubTabInUrl(key);
|
||||
const pane = tabPanes.get("settings") || document;
|
||||
const radio = pane.querySelector(
|
||||
'input.env-tab-radio[data-settings-tab="' + key + '"]'
|
||||
);
|
||||
if (radio) radio.checked = true;
|
||||
}
|
||||
|
||||
function formActionPath(form) {
|
||||
try {
|
||||
return new URL(form.action || "", location.href).pathname.replace(/\/$/, "") || "/";
|
||||
} catch (_) {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
function maybeKeepSettingsSubTabAfterForm(form) {
|
||||
const path = formActionPath(form);
|
||||
if (path === "/manual_transfer") {
|
||||
setSettingsSubTabInUrl("transfer");
|
||||
return "transfer";
|
||||
}
|
||||
if (path.indexOf("/api/options/transfer") >= 0 || path.indexOf("/api/options/cross-transfer") >= 0) {
|
||||
setSettingsSubTabInUrl("options_transfer");
|
||||
return "options_transfer";
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
async function fetchTabHtml(tab) {
|
||||
const r = await fetch(embedPageUrl(tab), {
|
||||
credentials: "same-origin",
|
||||
@@ -296,7 +350,8 @@
|
||||
}
|
||||
|
||||
function syncShellChrome(tab) {
|
||||
const hideTopBar = tab === "settings" || tab === "risk_policy" || tab === "env_config";
|
||||
const hideTopBar =
|
||||
tab === "settings" || tab === "risk_policy" || tab === "system_guide" || tab === "env_config";
|
||||
document.querySelectorAll(".instance-top-bar").forEach((el) => {
|
||||
el.hidden = hideTopBar;
|
||||
});
|
||||
@@ -398,14 +453,15 @@
|
||||
}
|
||||
}
|
||||
const fd = new FormData(form);
|
||||
const keepSub = maybeKeepSettingsSubTabAfterForm(form);
|
||||
return fetch(form.action, {
|
||||
method: form.method || "POST",
|
||||
body: fd,
|
||||
credentials: "same-origin",
|
||||
redirect: "manual",
|
||||
})
|
||||
.then(() => reloadCurrentTab())
|
||||
.catch(() => reloadCurrentTab());
|
||||
.then(() => reloadCurrentTab().then(() => activateSettingsSubTab(keepSub)))
|
||||
.catch(() => reloadCurrentTab().then(() => activateSettingsSubTab(keepSub)));
|
||||
}
|
||||
|
||||
function patchApplyListWindow() {
|
||||
@@ -464,14 +520,15 @@
|
||||
if (CUSTOM_SUBMIT_FORM_IDS.has(form.id)) return;
|
||||
ev.preventDefault();
|
||||
const fd = new FormData(form);
|
||||
const keepSub = maybeKeepSettingsSubTabAfterForm(form);
|
||||
fetch(form.action, {
|
||||
method: form.method || "POST",
|
||||
body: fd,
|
||||
credentials: "same-origin",
|
||||
redirect: "manual",
|
||||
})
|
||||
.then(() => reloadCurrentTab())
|
||||
.catch(() => reloadCurrentTab());
|
||||
.then(() => reloadCurrentTab().then(() => activateSettingsSubTab(keepSub)))
|
||||
.catch(() => reloadCurrentTab().then(() => activateSettingsSubTab(keepSub)));
|
||||
},
|
||||
true
|
||||
);
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
/**
|
||||
* 实例手机壳: ≤720px 底栏 +「更多」,与 embed soft-nav 同步.
|
||||
*/
|
||||
(function (global) {
|
||||
const PRIMARY = { trade: 1, key_monitor: 1, options: 1 };
|
||||
const MQ = "(max-width: 720px)";
|
||||
|
||||
function isEmbedShell() {
|
||||
return document.body && document.body.getAttribute("data-embed-shell") === "1";
|
||||
}
|
||||
|
||||
function isMobileLayout() {
|
||||
return window.matchMedia(MQ).matches;
|
||||
}
|
||||
|
||||
function syncPhoneClass() {
|
||||
if (!document.body) return;
|
||||
document.body.classList.toggle("inst-phone", isMobileLayout());
|
||||
}
|
||||
|
||||
function currentTab() {
|
||||
if (global.InstanceEmbed && typeof global.InstanceEmbed.getTab === "function") {
|
||||
return global.InstanceEmbed.getTab();
|
||||
}
|
||||
try {
|
||||
const t = new URLSearchParams(location.search).get("tab");
|
||||
if (t) return t;
|
||||
} catch (_) {}
|
||||
return (document.body && document.body.getAttribute("data-page")) || "trade";
|
||||
}
|
||||
|
||||
function closeMore() {
|
||||
document.body.classList.remove("inst-mobile-more-open");
|
||||
const more = document.getElementById("inst-mobile-more");
|
||||
const btn = document.getElementById("inst-m-tab-more");
|
||||
if (more) more.setAttribute("aria-hidden", "true");
|
||||
if (btn) btn.setAttribute("aria-expanded", "false");
|
||||
syncTabActive(currentTab());
|
||||
}
|
||||
|
||||
function openMore() {
|
||||
if (!isMobileLayout()) return;
|
||||
document.body.classList.add("inst-mobile-more-open");
|
||||
const more = document.getElementById("inst-mobile-more");
|
||||
const btn = document.getElementById("inst-m-tab-more");
|
||||
if (more) more.setAttribute("aria-hidden", "false");
|
||||
if (btn) btn.setAttribute("aria-expanded", "true");
|
||||
syncTabActive(currentTab());
|
||||
}
|
||||
|
||||
function toggleMore() {
|
||||
if (document.body.classList.contains("inst-mobile-more-open")) closeMore();
|
||||
else openMore();
|
||||
}
|
||||
|
||||
function syncTabActive(tab) {
|
||||
const page = tab || currentTab();
|
||||
const primary = !!PRIMARY[page];
|
||||
const moreOpen = document.body.classList.contains("inst-mobile-more-open");
|
||||
document.querySelectorAll("#inst-mobile-tabbar .inst-m-tab").forEach((el) => {
|
||||
const t = el.getAttribute("data-embed-tab") || "";
|
||||
let on = false;
|
||||
if (t === "more") on = moreOpen || !primary;
|
||||
else on = !moreOpen && t === page;
|
||||
el.classList.toggle("active", on);
|
||||
});
|
||||
document.querySelectorAll("#inst-mobile-more .inst-mobile-more-nav [data-embed-tab]").forEach((a) => {
|
||||
a.classList.toggle("active", a.getAttribute("data-embed-tab") === page);
|
||||
});
|
||||
}
|
||||
|
||||
/** embed 切页时关闭「更多」并同步高亮 */
|
||||
function onTabChange(tab) {
|
||||
document.body.classList.remove("inst-mobile-more-open");
|
||||
const more = document.getElementById("inst-mobile-more");
|
||||
const btn = document.getElementById("inst-m-tab-more");
|
||||
if (more) more.setAttribute("aria-hidden", "true");
|
||||
if (btn) btn.setAttribute("aria-expanded", "false");
|
||||
syncTabActive(tab);
|
||||
}
|
||||
|
||||
function goTab(tab) {
|
||||
if (!tab || tab === "more") return;
|
||||
closeMore();
|
||||
if (global.InstanceEmbed && typeof global.InstanceEmbed.loadTab === "function") {
|
||||
if (tab === currentTab()) {
|
||||
syncTabActive(tab);
|
||||
return;
|
||||
}
|
||||
void global.InstanceEmbed.loadTab(tab);
|
||||
return;
|
||||
}
|
||||
const pathMap = {
|
||||
dashboard: "/dashboard",
|
||||
key_monitor: "/key_monitor",
|
||||
trade: "/trade",
|
||||
strategy: "/strategy",
|
||||
strategy_records: "/strategy/records",
|
||||
options: "/options",
|
||||
options_review: "/options/review",
|
||||
hedge_plan: "/hedge-plan",
|
||||
records: "/records",
|
||||
stats: "/stats",
|
||||
risk_policy: "/risk_policy",
|
||||
system_guide: "/system_guide",
|
||||
env_config: "/env_config",
|
||||
settings: "/settings",
|
||||
};
|
||||
location.href = pathMap[tab] || "/trade";
|
||||
}
|
||||
|
||||
function bindChrome() {
|
||||
const moreBtn = document.getElementById("inst-m-tab-more");
|
||||
const backdrop = document.getElementById("inst-mobile-more-backdrop");
|
||||
const closeBtn = document.getElementById("inst-mobile-more-close");
|
||||
if (moreBtn) {
|
||||
moreBtn.addEventListener("click", (ev) => {
|
||||
ev.preventDefault();
|
||||
toggleMore();
|
||||
});
|
||||
}
|
||||
if (backdrop) backdrop.addEventListener("click", closeMore);
|
||||
if (closeBtn) closeBtn.addEventListener("click", closeMore);
|
||||
document.addEventListener("keydown", (ev) => {
|
||||
if (ev.key === "Escape" && document.body.classList.contains("inst-mobile-more-open")) {
|
||||
closeMore();
|
||||
}
|
||||
});
|
||||
|
||||
document.querySelectorAll("#inst-mobile-tabbar .inst-m-tab[data-embed-tab]").forEach((el) => {
|
||||
if (el.getAttribute("data-embed-tab") === "more") return;
|
||||
el.addEventListener("click", (ev) => {
|
||||
if (ev.ctrlKey || ev.metaKey || ev.shiftKey || ev.altKey) return;
|
||||
ev.preventDefault();
|
||||
goTab(el.getAttribute("data-embed-tab"));
|
||||
});
|
||||
});
|
||||
document.querySelectorAll("#inst-mobile-more .inst-mobile-more-nav [data-embed-tab]").forEach((a) => {
|
||||
a.addEventListener("click", (ev) => {
|
||||
if (ev.ctrlKey || ev.metaKey || ev.shiftKey || ev.altKey) return;
|
||||
ev.preventDefault();
|
||||
goTab(a.getAttribute("data-embed-tab"));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function boot() {
|
||||
if (!isEmbedShell()) return;
|
||||
if (!document.getElementById("inst-mobile-tabbar")) return;
|
||||
syncPhoneClass();
|
||||
bindChrome();
|
||||
syncTabActive(currentTab());
|
||||
let resizeTimer = null;
|
||||
window.addEventListener("resize", () => {
|
||||
clearTimeout(resizeTimer);
|
||||
resizeTimer = setTimeout(() => {
|
||||
const was = document.body.classList.contains("inst-phone");
|
||||
syncPhoneClass();
|
||||
if (!isMobileLayout()) closeMore();
|
||||
else if (!was) syncTabActive(currentTab());
|
||||
}, 120);
|
||||
});
|
||||
}
|
||||
|
||||
global.InstanceMobileNav = {
|
||||
syncTabActive,
|
||||
onTabChange,
|
||||
closeMore,
|
||||
isMobileLayout,
|
||||
};
|
||||
|
||||
if (document.readyState === "loading") {
|
||||
document.addEventListener("DOMContentLoaded", boot);
|
||||
} else {
|
||||
boot();
|
||||
}
|
||||
})(typeof window !== "undefined" ? window : globalThis);
|
||||
@@ -88,7 +88,7 @@
|
||||
.mood-grid{display:flex;gap:10px;flex-wrap:wrap;font-size:.82rem;color:#d7d7ea}
|
||||
.mood-grid label{display:flex;align-items:center;gap:3px}
|
||||
.screenshot{width:100px;border-radius:6px;cursor:pointer;margin-top:6px}
|
||||
.modal{display:none;position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,.78);justify-content:center;align-items:center;z-index:1210}
|
||||
.modal{display:none;position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,.78);justify-content:center;align-items:center;z-index:2100}
|
||||
.modal img{max-width:90%;max-height:90%;border-radius:8px}
|
||||
.detail-modal{display:none;position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,.78);justify-content:center;align-items:center;z-index:1200;padding:20px}
|
||||
.detail-modal .panel{width:min(92vw,980px);max-height:88vh;overflow:auto;background:#121726;border:1px solid #2a3150;border-radius:10px;padding:14px}
|
||||
|
||||
@@ -20,7 +20,7 @@
|
||||
}
|
||||
|
||||
/** 默认关闭的导航开关:缺失时按 false,不能用 !== false */
|
||||
const NAV_DEFAULT_OFF = { show_nav_dashboard: true };
|
||||
const NAV_DEFAULT_OFF = { show_nav_dashboard: true, show_nav_system_guide: true };
|
||||
|
||||
function navPrefShow(display, key) {
|
||||
if (!key) return true;
|
||||
@@ -31,6 +31,8 @@
|
||||
function applyDisplayToNav(display) {
|
||||
const map = {
|
||||
dashboard: "show_nav_dashboard",
|
||||
key_monitor: "show_nav_key_monitor",
|
||||
trade: "show_nav_trade",
|
||||
strategy: "show_nav_strategy",
|
||||
strategy_records: "show_nav_strategy_records",
|
||||
records: "show_nav_records",
|
||||
@@ -41,16 +43,22 @@
|
||||
"hedge-plan": "show_nav_hedge_plan",
|
||||
hedge_plan: "show_nav_hedge_plan",
|
||||
risk_policy: "show_nav_risk_policy",
|
||||
system_guide: "show_nav_system_guide",
|
||||
env_config: "show_nav_env_config",
|
||||
};
|
||||
document.querySelectorAll(".embed-top-nav [data-embed-tab], .top-nav a[href^='/']").forEach((a) => {
|
||||
const tab = a.getAttribute("data-embed-tab") || (a.getAttribute("href") || "").replace(/^\//, "").split("?")[0];
|
||||
const key = map[tab];
|
||||
if (!key) return;
|
||||
const show = navPrefShow(display, key);
|
||||
a.classList.toggle("nav-hidden", !show);
|
||||
a.style.display = show ? "" : "none";
|
||||
});
|
||||
document
|
||||
.querySelectorAll(
|
||||
".embed-top-nav [data-embed-tab], .top-nav a[href^='/'], #inst-mobile-tabbar [data-embed-tab], #inst-mobile-more [data-embed-tab]"
|
||||
)
|
||||
.forEach((a) => {
|
||||
const tab = a.getAttribute("data-embed-tab") || (a.getAttribute("href") || "").replace(/^\//, "").split("?")[0];
|
||||
if (tab === "more") return;
|
||||
const key = map[tab];
|
||||
if (!key) return;
|
||||
const show = navPrefShow(display, key);
|
||||
a.classList.toggle("nav-hidden", !show);
|
||||
a.style.display = show ? "" : "none";
|
||||
});
|
||||
global.__INSTANCE_DISPLAY__ = display;
|
||||
}
|
||||
|
||||
@@ -58,6 +66,8 @@
|
||||
const d = DISPLAY();
|
||||
const map = {
|
||||
dashboard: "show_nav_dashboard",
|
||||
key_monitor: "show_nav_key_monitor",
|
||||
trade: "show_nav_trade",
|
||||
strategy: "show_nav_strategy",
|
||||
strategy_records: "show_nav_strategy_records",
|
||||
records: "show_nav_records",
|
||||
@@ -68,6 +78,7 @@
|
||||
"hedge-plan": "show_nav_hedge_plan",
|
||||
hedge_plan: "show_nav_hedge_plan",
|
||||
risk_policy: "show_nav_risk_policy",
|
||||
system_guide: "show_nav_system_guide",
|
||||
env_config: "show_nav_env_config",
|
||||
};
|
||||
const key = map[tab];
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -93,8 +93,16 @@
|
||||
});
|
||||
}
|
||||
|
||||
function isOptionsReviewSlot(input) {
|
||||
if (!input) return false;
|
||||
if (input.classList && input.classList.contains("or-upload-input")) return true;
|
||||
return !!(input.closest && input.closest("#or-upload-slots, #options-review-root"));
|
||||
}
|
||||
|
||||
function bindInput(input) {
|
||||
if (!input || input.dataset.journalSlotBound === "1") return;
|
||||
// 期权复盘槽位由 options_review.js 处理,勿被合约复盘上传抢走
|
||||
if (isOptionsReviewSlot(input)) return;
|
||||
input.dataset.journalSlotBound = "1";
|
||||
input.addEventListener("change", function () {
|
||||
var file = input.files && input.files[0];
|
||||
|
||||
@@ -14,6 +14,13 @@
|
||||
moneyFilter: "all",
|
||||
chainView: "list",
|
||||
strikeExpandAll: false,
|
||||
/** 环境 OKX_OPTIONS_CHAIN_ASK_LIQ_FILTER_ENABLED;链接口可热更新 */
|
||||
askLiqFilter: root.dataset.askLiqFilter !== "0",
|
||||
budgetBuffer: (function () {
|
||||
const raw = root.dataset.budgetBuffer;
|
||||
const n = raw != null && raw !== "" ? Number(raw) : NaN;
|
||||
return !Number.isNaN(n) && n > 0 ? n : 0.95;
|
||||
})(),
|
||||
chain: panelCache.chain || null,
|
||||
selectedInst: null,
|
||||
orderQuote: null,
|
||||
@@ -91,16 +98,17 @@
|
||||
}
|
||||
|
||||
function parkOrderPanel() {
|
||||
stopPendingOrdersPoll();
|
||||
const panel = orderPanel();
|
||||
const host = orderPanelHost();
|
||||
// 把整块 host(含面板)移回原位,再删行内 tr,避免 tbody 重绘销毁下单 DOM
|
||||
if (host && orderPanelHome && host.parentElement !== orderPanelHome) {
|
||||
orderPanelHome.appendChild(host);
|
||||
} else if (panel && host && panel.parentElement !== host) {
|
||||
host.appendChild(panel);
|
||||
// 弹窗挂到 body;关闭后收回原位,绝不插入期权链表格
|
||||
if (panel && host && panel.parentElement !== host) host.appendChild(panel);
|
||||
if (host) {
|
||||
host.hidden = true;
|
||||
host.setAttribute("aria-hidden", "true");
|
||||
if (orderPanelHome && host.parentElement !== orderPanelHome) {
|
||||
orderPanelHome.appendChild(host);
|
||||
}
|
||||
}
|
||||
if (host) host.hidden = true;
|
||||
if (panel) panel.style.display = "none";
|
||||
const inline = document.querySelector(".opt-order-inline-row");
|
||||
if (inline) inline.remove();
|
||||
@@ -121,32 +129,27 @@
|
||||
document.querySelector('#opt-strike-tbody tr.opt-strike-row[data-inst="' + CSS.escape(instId) + '"]') ||
|
||||
document.querySelector('#opt-strike-tbody tr.opt-strike-row[data-call-inst="' + CSS.escape(instId) + '"]') ||
|
||||
document.querySelector('#opt-strike-tbody tr.opt-strike-row[data-put-inst="' + CSS.escape(instId) + '"]');
|
||||
if (!row) {
|
||||
syncPickButtons(null);
|
||||
return false;
|
||||
}
|
||||
document.querySelectorAll(".opt-strike-row").forEach(function (r) {
|
||||
r.classList.toggle("opt-row-selected", r === row);
|
||||
r.classList.toggle("opt-row-selected", !!row && r === row);
|
||||
});
|
||||
syncPickButtons(instId);
|
||||
const oldInline = document.querySelector(".opt-order-inline-row");
|
||||
if (oldInline) oldInline.remove();
|
||||
if (panel.parentElement !== host) host.appendChild(panel);
|
||||
const tr = document.createElement("tr");
|
||||
tr.className = "opt-order-inline-row";
|
||||
const td = document.createElement("td");
|
||||
td.colSpan = strikeTableColspan();
|
||||
td.appendChild(host);
|
||||
tr.appendChild(td);
|
||||
row.after(tr);
|
||||
// 挂到 body,避免被卡片 overflow 裁成「行内展开」
|
||||
if (host.parentElement !== document.body) document.body.appendChild(host);
|
||||
host.hidden = false;
|
||||
host.setAttribute("aria-hidden", "false");
|
||||
panel.style.display = "";
|
||||
tr.scrollIntoView({ behavior: "smooth", block: "nearest" });
|
||||
refreshPendingOrders();
|
||||
startPendingOrdersPoll();
|
||||
return true;
|
||||
}
|
||||
|
||||
function closeOrderDialog() {
|
||||
state.selectedInst = null;
|
||||
state.orderQuote = null;
|
||||
parkOrderPanel();
|
||||
}
|
||||
|
||||
function fmtPendingAge(sec) {
|
||||
if (sec == null || Number.isNaN(Number(sec))) return "—";
|
||||
let s = Math.max(0, Math.round(Number(sec)));
|
||||
@@ -277,8 +280,51 @@
|
||||
const mode = currentSizeMode();
|
||||
const sheetsEl = document.getElementById("opt-sheets-amount");
|
||||
const ethEl = document.getElementById("opt-eth-amount");
|
||||
const hint = document.getElementById("opt-budget-full-hint");
|
||||
const capEl = document.getElementById("opt-budget-full-cap");
|
||||
if (sheetsEl) sheetsEl.style.display = mode === "sheets" ? "" : "none";
|
||||
if (ethEl) ethEl.style.display = mode === "eth_amount" ? "" : "none";
|
||||
if (hint) hint.style.display = mode === "budget_full" ? "" : "none";
|
||||
if (capEl && root && root.dataset.tradeBudget) {
|
||||
const n = Number(root.dataset.tradeBudget);
|
||||
if (Number.isFinite(n) && n > 0) capEl.textContent = n.toFixed(2);
|
||||
}
|
||||
document.querySelectorAll(".opt-size-mode-chip").forEach(function (chip) {
|
||||
const radio = chip.querySelector('input[name="opt-size-mode"]');
|
||||
chip.classList.toggle("is-selected", !!(radio && radio.checked));
|
||||
chip.classList.toggle("active", !!(radio && radio.checked));
|
||||
});
|
||||
}
|
||||
|
||||
function hardenOrderAutofill() {
|
||||
function looksLikeUsername(v) {
|
||||
return /^[a-z][a-z0-9._-]{1,31}$/i.test(String(v || "").trim());
|
||||
}
|
||||
function harden(el) {
|
||||
if (!el) return;
|
||||
function wipe() {
|
||||
if (looksLikeUsername(el.value)) el.value = "";
|
||||
}
|
||||
wipe();
|
||||
el.addEventListener("focus", function () {
|
||||
el.removeAttribute("readonly");
|
||||
});
|
||||
el.addEventListener("blur", function () {
|
||||
if (!el.value) el.setAttribute("readonly", "readonly");
|
||||
});
|
||||
setTimeout(wipe, 200);
|
||||
setTimeout(wipe, 800);
|
||||
setTimeout(wipe, 2000);
|
||||
}
|
||||
const note = document.getElementById("opt-signal-note");
|
||||
harden(note);
|
||||
[
|
||||
"opt-sheets-amount",
|
||||
"opt-eth-amount",
|
||||
"opt-target-idx",
|
||||
].forEach(function (id) {
|
||||
harden(document.getElementById(id));
|
||||
});
|
||||
}
|
||||
|
||||
function quoteUrl(instId) {
|
||||
@@ -341,21 +387,41 @@
|
||||
return "";
|
||||
}
|
||||
|
||||
function askLiqFilterOn() {
|
||||
return !!state.askLiqFilter;
|
||||
}
|
||||
|
||||
function hasAskLiquidity(c) {
|
||||
if (!c) return false;
|
||||
if (c.ask_estimated) return false;
|
||||
const a = Number(c.ask);
|
||||
const s = Number(c.ask_sz);
|
||||
return Number.isFinite(a) && a > 0 && Number.isFinite(s) && s >= 1;
|
||||
}
|
||||
|
||||
function syncAskLiqFilterFromChain(d) {
|
||||
if (!d || d.ask_liq_filter_enabled == null) return;
|
||||
state.askLiqFilter = !!d.ask_liq_filter_enabled;
|
||||
root.dataset.askLiqFilter = state.askLiqFilter ? "1" : "0";
|
||||
}
|
||||
|
||||
function countContractsForType(contracts) {
|
||||
if (state.chainView === "t") {
|
||||
return countStraddleStrikes(contracts);
|
||||
}
|
||||
return (contracts || []).filter(function (c) {
|
||||
return c.opt_type === state.optType;
|
||||
if (c.opt_type !== state.optType) return false;
|
||||
if (askLiqFilterOn() && !hasAskLiquidity(c)) return false;
|
||||
return true;
|
||||
}).length;
|
||||
}
|
||||
|
||||
function countStraddleStrikes(contracts) {
|
||||
const strikes = new Set();
|
||||
(contracts || []).forEach(function (c) {
|
||||
if (c.strike != null) strikes.add(String(c.strike));
|
||||
const rows = buildStraddleRows(contracts).filter(function (row) {
|
||||
if (!askLiqFilterOn()) return true;
|
||||
return hasAskLiquidity(row.call) || hasAskLiquidity(row.put);
|
||||
});
|
||||
return strikes.size;
|
||||
return rows.length;
|
||||
}
|
||||
|
||||
function buildStraddleRows(contracts) {
|
||||
@@ -398,7 +464,11 @@
|
||||
function filterStraddleRows(rows, indexPx) {
|
||||
const atmStrike = findAtmStrike(rows, indexPx);
|
||||
return rows.filter(function (row) {
|
||||
return matchesStrikeRowFilter(row.strike, indexPx, atmStrike);
|
||||
if (!matchesStrikeRowFilter(row.strike, indexPx, atmStrike)) return false;
|
||||
if (askLiqFilterOn() && !hasAskLiquidity(row.call) && !hasAskLiquidity(row.put)) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
@@ -459,7 +529,10 @@
|
||||
|
||||
function filterChainContracts(contracts) {
|
||||
return (contracts || []).filter(function (c) {
|
||||
return c.opt_type === state.optType && matchesMoneyFilter(c.moneyness);
|
||||
if (c.opt_type !== state.optType) return false;
|
||||
if (!matchesMoneyFilter(c.moneyness)) return false;
|
||||
if (askLiqFilterOn() && !hasAskLiquidity(c)) return false;
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
@@ -473,6 +546,28 @@
|
||||
return (t || "").toUpperCase() === "P" ? "看跌 Put" : "看涨 Call";
|
||||
}
|
||||
|
||||
function sourceText(p) {
|
||||
const lab = (p && p.source_label) || "纯期权";
|
||||
const src = (p && p.source) || "option";
|
||||
let pid = p && p.source_plan_id;
|
||||
if (pid == null && p && p.hedge_plan_target && p.hedge_plan_target.plan_id != null) {
|
||||
pid = p.hedge_plan_target.plan_id;
|
||||
}
|
||||
if (src !== "option" && pid != null && pid !== "") return lab + " #" + pid;
|
||||
return lab;
|
||||
}
|
||||
|
||||
function sourceBadgeHtml(p) {
|
||||
const src = (p && p.source) || "option";
|
||||
const cls =
|
||||
src === "options_options"
|
||||
? "opt-source-badge opt-source-badge--oo"
|
||||
: src === "perp_options"
|
||||
? "opt-source-badge opt-source-badge--po"
|
||||
: "opt-source-badge opt-source-badge--plain";
|
||||
return '<span class="' + cls + '" title="持仓来源">' + sourceText(p) + "</span>";
|
||||
}
|
||||
|
||||
function expLabel(ms) {
|
||||
try {
|
||||
const dt = new Date(Number(ms));
|
||||
@@ -485,6 +580,15 @@
|
||||
}
|
||||
}
|
||||
|
||||
function applyBudgetBuffer(raw) {
|
||||
if (raw == null || raw === "") return;
|
||||
const buf = Number(raw);
|
||||
if (Number.isNaN(buf) || buf <= 0) return;
|
||||
state.budgetBuffer = buf;
|
||||
const el = document.getElementById("opt-budget-buf");
|
||||
if (el) el.textContent = fmt(buf, 2);
|
||||
}
|
||||
|
||||
function renderIndexLine() {
|
||||
const idx = state.chain && state.chain.index_px;
|
||||
const dte = state.chain && state.chain.chain_max_dte_days;
|
||||
@@ -492,13 +596,37 @@
|
||||
const el = document.getElementById("opt-chain-dte");
|
||||
if (el) el.textContent = String(Math.round(dte));
|
||||
}
|
||||
if (state.chain && state.chain.budget_buffer != null) {
|
||||
applyBudgetBuffer(state.chain.budget_buffer);
|
||||
}
|
||||
const line = document.getElementById("opt-index-line");
|
||||
if (line) {
|
||||
const liqHint = askLiqFilterOn() ? "仅显示卖一深度≥1张" : "显示全部卖一(含估算~)";
|
||||
line.textContent =
|
||||
"指数 " + state.underlying + " ≈ " + fmt(idx, 2) + " · 默认显示全部 · 实值含平值 · 虚值=价外";
|
||||
"指数 " + state.underlying + " ≈ " + fmt(idx, 2) +
|
||||
" · 默认最近一期 · " + liqHint + " · 实值含平值 · 虚值=价外";
|
||||
}
|
||||
}
|
||||
|
||||
function pickNearestExpiry(exps) {
|
||||
if (!exps || !exps.length) return "";
|
||||
const now = Date.now();
|
||||
let best = null;
|
||||
let bestDelta = Infinity;
|
||||
exps.forEach(function (e) {
|
||||
const t = Number(e.exp_time);
|
||||
if (!Number.isFinite(t)) return;
|
||||
const delta = t - now;
|
||||
if (delta < -60000) return;
|
||||
if (delta < bestDelta) {
|
||||
bestDelta = delta;
|
||||
best = e;
|
||||
}
|
||||
});
|
||||
if (best) return String(best.exp_time);
|
||||
return String(exps[0].exp_time);
|
||||
}
|
||||
|
||||
function renderExpiryOptions(preserveSelection) {
|
||||
const sel = document.getElementById("opt-exp-select");
|
||||
if (!sel) return;
|
||||
@@ -513,6 +641,8 @@
|
||||
});
|
||||
if (prev && exps.some(function (e) { return String(e.exp_time) === String(prev); })) {
|
||||
sel.value = prev;
|
||||
} else if (exps.length) {
|
||||
sel.value = pickNearestExpiry(exps);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -810,7 +940,8 @@
|
||||
if (!list.length) {
|
||||
const label = moneyFilterLabel();
|
||||
const suffix = label ? label : optTypeLabel(state.optType);
|
||||
tbody.innerHTML = '<tr><td colspan="' + cols + '" class="muted">该到期日暂无' + suffix + "合约</td></tr>";
|
||||
const liqTip = askLiqFilterOn() ? "(卖一深度≥1 时才显示,可在环境配置关闭筛选)" : "";
|
||||
tbody.innerHTML = '<tr><td colspan="' + cols + '" class="muted">该到期日暂无' + suffix + "合约" + liqTip + "</td></tr>";
|
||||
state.selectedInst = null;
|
||||
return;
|
||||
}
|
||||
@@ -869,8 +1000,10 @@
|
||||
const atmStrike = findAtmStrike(rows, indexPx);
|
||||
let matchedSelected = false;
|
||||
rows.forEach(function (row) {
|
||||
const call = row.call;
|
||||
const put = row.put;
|
||||
const callRaw = row.call;
|
||||
const putRaw = row.put;
|
||||
const call = callRaw && (!askLiqFilterOn() || hasAskLiquidity(callRaw)) ? callRaw : null;
|
||||
const put = putRaw && (!askLiqFilterOn() || hasAskLiquidity(putRaw)) ? putRaw : null;
|
||||
const combined = straddleAskPerUnit(call && call.ask, put && put.ask);
|
||||
const tr = document.createElement("tr");
|
||||
tr.className = "opt-strike-row opt-strike-row-t";
|
||||
@@ -1048,6 +1181,7 @@
|
||||
panelCache.chain = d;
|
||||
panelCache.underlying = uly;
|
||||
panelCache.optType = state.optType;
|
||||
syncAskLiqFilterFromChain(d);
|
||||
if (!soft) {
|
||||
state.selectedInst = null;
|
||||
resetMoneyFilterToAll();
|
||||
@@ -1084,16 +1218,16 @@
|
||||
async function openPosition() {
|
||||
if (!state.selectedInst) {
|
||||
alert("请先选择合约");
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
const q = state.orderQuote;
|
||||
if (!q || !q.ok || !q.can_open) {
|
||||
alert((q && (q.msg || q.open_block_msg)) || "暂无卖一深度,无法按卖一开仓");
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
if (q.sizing && q.sizing.ok === false) {
|
||||
alert(q.sizing.msg || "张数无效");
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
const btn = document.getElementById("opt-open-btn");
|
||||
btn.disabled = true;
|
||||
@@ -1114,7 +1248,7 @@
|
||||
const tgt = parseFloat(tgtRaw);
|
||||
if (!Number.isFinite(tgt) || tgt <= 0) {
|
||||
alert("目标位无效");
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
body.target_index = tgt;
|
||||
}
|
||||
@@ -1124,16 +1258,19 @@
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
const msgEl = document.getElementById("opt-order-msg");
|
||||
msgEl.textContent = d.ok ? "下单已提交,右侧可查看/撤销未成交委托" : (d.msg || "失败");
|
||||
msgEl.textContent = d.ok ? "下单已提交,可在「当前委托」查看/撤销" : (d.msg || "失败");
|
||||
msgEl.classList.toggle("opt-error", !d.ok);
|
||||
if (d.ok) {
|
||||
refreshPendingOrders();
|
||||
startPendingOrdersPoll();
|
||||
refreshAllPositions();
|
||||
if (typeof refreshAccountSnapshot === "function") refreshAccountSnapshot();
|
||||
} else {
|
||||
alert(d.msg || "下单失败");
|
||||
closeOrderDialog();
|
||||
setOptionsPosTab("pending");
|
||||
return true;
|
||||
}
|
||||
alert(d.msg || "下单失败");
|
||||
return false;
|
||||
} finally {
|
||||
const latest = state.orderQuote;
|
||||
btn.disabled = !(latest && latest.ok && latest.can_open && !(latest.sizing && latest.sizing.ok === false));
|
||||
@@ -1158,11 +1295,14 @@
|
||||
return (
|
||||
'<div class="pos-card-head">' +
|
||||
'<div class="pos-card-symbol"><strong>' + (p.inst_id || "") + '</strong>' +
|
||||
'<span class="pos-side-badge ' + sideCls + '">' + optTypeLabel(p.opt_type) + "</span></div>" +
|
||||
'<span class="pos-side-badge ' + sideCls + '">' + optTypeLabel(p.opt_type) + "</span>" +
|
||||
sourceBadgeHtml(p) +
|
||||
"</div>" +
|
||||
'<div class="pos-head-actions">' +
|
||||
'<button type="button" class="btn-primary opt-close-btn" data-inst="' + p.inst_id + '" data-sheets="' + closeSheets + '">买一平仓</button>' +
|
||||
"</div></div>" +
|
||||
'<div class="pos-meta">' +
|
||||
'<span class="pos-meta-item">持仓来源: ' + sourceText(p) + "</span>" +
|
||||
'<span class="pos-meta-item">行权价: ' + fmt(p.strike, 0) + "</span>" +
|
||||
'<span class="pos-meta-item">张数: ' + fmt(p.pos, 0) + " · 币量 " + fmt(p.eth_amount, 4) + "</span>" +
|
||||
(expAttr
|
||||
@@ -1320,6 +1460,7 @@
|
||||
'<span class="opt-pos-bar-id-group">' +
|
||||
'<strong class="opt-pos-bar-title" title="' + inst + '">' + inst + "</strong>" +
|
||||
'<span class="pos-side-badge ' + sideCls + '">' + optTypeLabel(p.opt_type) + "</span>" +
|
||||
sourceBadgeHtml(p) +
|
||||
"</span>" +
|
||||
'<span class="opt-pos-bar-meta">行权 ' + fmt(p.strike, 0) + " · " + fmt(p.pos, 0) + "张</span>" +
|
||||
"</span>" +
|
||||
@@ -1561,6 +1702,10 @@
|
||||
if (tab === "live" && window.OptionsExpiryCountdown && OptionsExpiryCountdown.ensureTimer) {
|
||||
OptionsExpiryCountdown.ensureTimer();
|
||||
}
|
||||
if (tab === "pending") {
|
||||
refreshPendingOrders();
|
||||
startPendingOrdersPoll();
|
||||
}
|
||||
}
|
||||
|
||||
function bindOptionsPosTabs() {
|
||||
@@ -1934,6 +2079,7 @@
|
||||
}
|
||||
|
||||
function bootOptionsPanel() {
|
||||
applyBudgetBuffer(state.budgetBuffer);
|
||||
updateSizeInputs();
|
||||
syncMoneyFilterButtons();
|
||||
syncChainViewUI();
|
||||
@@ -2021,6 +2167,7 @@
|
||||
});
|
||||
}
|
||||
bindOptionsPosTabs();
|
||||
hardenOrderAutofill();
|
||||
|
||||
document.querySelectorAll('input[name="opt-size-mode"]').forEach(function (r) {
|
||||
r.addEventListener("change", function () {
|
||||
@@ -2029,6 +2176,25 @@
|
||||
});
|
||||
});
|
||||
|
||||
function bindOrderDialogChrome() {
|
||||
const host = orderPanelHost();
|
||||
const closeBtn = document.getElementById("opt-order-close-btn");
|
||||
const cancelBtn = document.getElementById("opt-order-cancel-btn");
|
||||
if (closeBtn) closeBtn.addEventListener("click", closeOrderDialog);
|
||||
if (cancelBtn) cancelBtn.addEventListener("click", closeOrderDialog);
|
||||
if (host) {
|
||||
host.addEventListener("click", function (ev) {
|
||||
if (ev.target === host) closeOrderDialog();
|
||||
});
|
||||
}
|
||||
document.addEventListener("keydown", function (ev) {
|
||||
if (ev.key !== "Escape") return;
|
||||
const h = orderPanelHost();
|
||||
if (h && !h.hidden) closeOrderDialog();
|
||||
});
|
||||
}
|
||||
bindOrderDialogChrome();
|
||||
|
||||
["opt-sheets-amount", "opt-eth-amount", "opt-target-idx"].forEach(function (id) {
|
||||
const el = document.getElementById(id);
|
||||
if (!el) return;
|
||||
|
||||
@@ -38,6 +38,28 @@
|
||||
return (t || "").toUpperCase() === "P" ? "看跌 Put" : "看涨 Call";
|
||||
}
|
||||
|
||||
function sourceText(p) {
|
||||
const lab = (p && p.source_label) || "纯期权";
|
||||
const src = (p && p.source) || "option";
|
||||
let pid = p && p.source_plan_id;
|
||||
if (pid == null && p && p.hedge_plan_target && p.hedge_plan_target.plan_id != null) {
|
||||
pid = p.hedge_plan_target.plan_id;
|
||||
}
|
||||
if (src !== "option" && pid != null && pid !== "") return lab + " #" + pid;
|
||||
return lab;
|
||||
}
|
||||
|
||||
function sourceBadgeHtml(p) {
|
||||
const src = (p && p.source) || "option";
|
||||
const cls =
|
||||
src === "options_options"
|
||||
? "opt-source-badge opt-source-badge--oo"
|
||||
: src === "perp_options"
|
||||
? "opt-source-badge opt-source-badge--po"
|
||||
: "opt-source-badge opt-source-badge--plain";
|
||||
return '<span class="' + cls + '" title="持仓来源">' + sourceText(p) + "</span>";
|
||||
}
|
||||
|
||||
function pnlCls(upl, hub) {
|
||||
if (upl > 0) return hub ? "pnl-pos" : "pos-pnl-profit";
|
||||
if (upl < 0) return hub ? "pnl-neg" : "pos-pnl-loss";
|
||||
@@ -125,9 +147,10 @@
|
||||
opts = opts || {};
|
||||
const hub = !!opts.hub;
|
||||
const readOnly = !!opts.readOnly;
|
||||
const net = netPnlFromPos(p);
|
||||
const roi = netRoiFromPos(p, net);
|
||||
const uplCls = pnlCls(net, hub);
|
||||
const hidePnl = !!opts.hidePnl;
|
||||
const net = hidePnl ? null : netPnlFromPos(p);
|
||||
const roi = hidePnl ? null : netRoiFromPos(p, net);
|
||||
const uplCls = hidePnl ? "" : pnlCls(net, hub);
|
||||
const sideCls = (p.opt_type || "").toUpperCase() === "P" ? "pos-side-short" : "pos-side-long";
|
||||
const expMs = p.exp_time_ms != null ? p.exp_time_ms : p.exp_time;
|
||||
const expAttr = expMs != null && expMs !== "" ? String(expMs) : "";
|
||||
@@ -144,13 +167,22 @@
|
||||
'<button type="button" class="btn-primary opt-close-btn" data-inst="' + (p.inst_id || "") + '" data-sheets="' + closeSheets + '">买一平仓</button>' +
|
||||
"</div>";
|
||||
}
|
||||
const pnlCells = hidePnl
|
||||
? ""
|
||||
: '<div class="pos-cell"><span class="pos-label">净盈亏</span><span class="pos-value ' + uplCls + '">' +
|
||||
(closePreview.bid_invalid || net == null ? "—" : fmt(net, 2)) + "</span></div>" +
|
||||
'<div class="pos-cell"><span class="pos-label">收益率</span><span class="pos-value ' + uplCls + '">' +
|
||||
(closePreview.bid_invalid || roi == null ? "—" : fmt(roi, 2) + "%") + "</span></div>";
|
||||
return (
|
||||
'<div class="pos-card-head">' +
|
||||
'<div class="pos-card-symbol"><strong>' + (p.inst_id || "") + "</strong>" +
|
||||
'<span class="pos-side-badge ' + sideCls + '">' + optTypeLabel(p.opt_type) + "</span></div>" +
|
||||
'<span class="pos-side-badge ' + sideCls + '">' + optTypeLabel(p.opt_type) + "</span>" +
|
||||
sourceBadgeHtml(p) +
|
||||
"</div>" +
|
||||
headActions +
|
||||
"</div>" +
|
||||
'<div class="pos-meta">' +
|
||||
'<span class="pos-meta-item">持仓来源: ' + sourceText(p) + "</span>" +
|
||||
'<span class="pos-meta-item">行权价: ' + fmt(p.strike, 0) + "</span>" +
|
||||
'<span class="pos-meta-item">张数: ' + fmt(p.pos, 0) + " · 币量 " + fmt(p.eth_amount, 4) + "</span>" +
|
||||
(expAttr
|
||||
@@ -164,15 +196,12 @@
|
||||
'<div class="pos-cell"><span class="pos-label">指数价</span><span class="pos-value">' + fmt(p.idx_px, 0) + "</span></div>" +
|
||||
'<div class="pos-cell"><span class="pos-label">到期平衡</span><span class="pos-value">' + fmt(p.expiry_be_px, 0) + "</span></div>" +
|
||||
'<div class="pos-cell"><span class="pos-label">平掉回本</span><span class="pos-value">' + fmt(p.close_be_px, 0) + "</span></div>" +
|
||||
'<div class="pos-cell"><span class="pos-label">净盈亏</span><span class="pos-value ' + uplCls + '">' +
|
||||
(closePreview.bid_invalid || net == null ? "—" : fmt(net, 2)) + "</span></div>" +
|
||||
'<div class="pos-cell"><span class="pos-label">收益率</span><span class="pos-value ' + uplCls + '">' +
|
||||
(closePreview.bid_invalid || roi == null ? "—" : fmt(roi, 2) + "%") + "</span></div>" +
|
||||
pnlCells +
|
||||
'<div class="pos-cell opt-pos-cell--depth"><span class="pos-label">买盘深度</span><span class="pos-value opt-bid-plain">' + fmtCloseLevels(closePreview, tickSz) + "</span></div>" +
|
||||
'<div class="pos-cell opt-pos-cell--close"><span class="pos-label">按买盘回收</span><span class="pos-value">' +
|
||||
(closePreview.bid_invalid
|
||||
? '<span class="muted">暂无有效买盘</span>'
|
||||
: fmtClosePreview(closePreview, p.premium_paid, hub)) + "</span></div>" +
|
||||
: fmtClosePreview(closePreview, hidePnl ? null : p.premium_paid, hub)) + "</span></div>" +
|
||||
"</div>" +
|
||||
(function () {
|
||||
const hint = closeGateHint(closePreview);
|
||||
@@ -192,19 +221,22 @@
|
||||
const intrinsic = o === "C" ? Math.max(0, tgt - strike) : o === "P" ? Math.max(0, strike - tgt) : null;
|
||||
if (intrinsic != null) {
|
||||
value = Math.round(intrinsic * eth * 100) / 100;
|
||||
if (Number.isFinite(prem)) profit = Math.round((value - prem) * 100) / 100;
|
||||
if (!hidePnl && Number.isFinite(prem)) profit = Math.round((value - prem) * 100) / 100;
|
||||
}
|
||||
}
|
||||
const profitTxt = profit == null ? "—" : ((profit > 0 ? "+" : "") + fmtUsdc(profit) + " USDC");
|
||||
const profitCls = profit > 0 ? " pnl-pos" : profit < 0 ? " pnl-neg" : "";
|
||||
const hedgeTarget = p.hedge_plan_target || null;
|
||||
const managed = hedgeTarget && hedgeTarget.managed_by === "hedge_plan";
|
||||
const profitSpan = hidePnl
|
||||
? ""
|
||||
: '<span class="pos-value' + profitCls + '">预估盈利 ' + profitTxt + "</span>";
|
||||
return (
|
||||
'<div class="opt-target-row opt-target-row--ro' + (managed ? " opt-target-row--managed" : "") + '">' +
|
||||
'<span class="opt-target-row-label">' + (managed ? "对冲计划 #" + hedgeTarget.plan_id : "委托") + "</span>" +
|
||||
'<span class="pos-value">目标 ' + fmt(p.target_index, 1) + "</span>" +
|
||||
'<span class="pos-value">价值 ' + (value == null ? "—" : fmtUsdc(value) + " USDC") + "</span>" +
|
||||
'<span class="pos-value' + profitCls + '">预估盈利 ' + profitTxt + "</span>" +
|
||||
profitSpan +
|
||||
'<span class="muted opt-target-row-hint">' +
|
||||
(managed ? "进行中 · 由对冲计划监控,到位后仅平盈利腿" : "监控中 · 到位按买一限价平") +
|
||||
"</span></div>"
|
||||
|
||||
@@ -67,23 +67,74 @@
|
||||
return s;
|
||||
}
|
||||
|
||||
function closeReasonLabel(r) {
|
||||
var map = {
|
||||
perp_tp: "永续止盈",
|
||||
perp_sl: "永续止损",
|
||||
oo_expiry_loss: "期期到期亏损",
|
||||
oo_expiry_win: "期期到期盈利",
|
||||
target_win_leg: "期期平盈利腿",
|
||||
target_up_win_leg: "期期上破·平盈利腿",
|
||||
target_down_win_leg: "期期下破·平盈利腿",
|
||||
oo_rest_closing: "期期全平·清残腿中",
|
||||
oo_rest_closed: "期期全平·两腿已平",
|
||||
orphaned_after_tp: "止盈后持有至到期",
|
||||
orphaned_option_expiry: "残腿到期",
|
||||
hold_to_expiry: "持有至到期",
|
||||
expiry: "到期",
|
||||
manual: "人工结束",
|
||||
partial_fail: "半腿失败",
|
||||
cancelled: "已取消",
|
||||
tp: "止盈",
|
||||
sl: "止损",
|
||||
};
|
||||
var key = String(r || "").trim();
|
||||
if (!key) return "—";
|
||||
return map[key] || key;
|
||||
}
|
||||
|
||||
function legRoleLabel(role) {
|
||||
var map = {
|
||||
perp: "永续腿",
|
||||
option_hedge: "保险期权",
|
||||
option_a: "期期腿A",
|
||||
option_b: "期期腿B",
|
||||
};
|
||||
var key = String(role || "").trim();
|
||||
if (!key) return "—";
|
||||
return map[key] || key;
|
||||
}
|
||||
|
||||
function tradeTitle(t) {
|
||||
if (!t) return "—";
|
||||
if (t.source_type === "option_spot") return t.inst_id || "—";
|
||||
return (
|
||||
(t.underlying || "") +
|
||||
(t.direction ? " " + t.direction : "") +
|
||||
(t.plan_close_reason ? " · " + t.plan_close_reason : "")
|
||||
(t.plan_close_reason ? " · " + closeReasonLabel(t.plan_close_reason) : "")
|
||||
);
|
||||
}
|
||||
|
||||
function pnlStyle(v) {
|
||||
function pnlClass(v) {
|
||||
var n = Number(v);
|
||||
if (n > 0) return "color:#3dd68c";
|
||||
if (n < 0) return "color:#f07178";
|
||||
if (n > 0) return "pos-pnl-profit";
|
||||
if (n < 0) return "pos-pnl-loss";
|
||||
return "";
|
||||
}
|
||||
|
||||
function resultClass(tag) {
|
||||
var t = String(tag || "").trim();
|
||||
if (t === "盈利") return "pos-pnl-profit";
|
||||
if (t === "亏损") return "pos-pnl-loss";
|
||||
return "";
|
||||
}
|
||||
|
||||
function tradeContractLabel(t) {
|
||||
if (!t) return "—";
|
||||
if (t.source_type === "option_spot") return t.inst_id || t.underlying || "—";
|
||||
return t.underlying || "—";
|
||||
}
|
||||
|
||||
function newDraftId() {
|
||||
if (global.crypto && typeof global.crypto.randomUUID === "function") {
|
||||
return global.crypto.randomUUID().replace(/-/g, "");
|
||||
@@ -98,12 +149,12 @@
|
||||
p.set("source_type", activeSource);
|
||||
var uly = ($("or-filter-uly") || {}).value || "";
|
||||
var opt = ($("or-filter-opt") || {}).value || "";
|
||||
var strategy = (($("or-filter-strategy") || {}).value || "").trim();
|
||||
var q = (($("or-filter-q") || $("or-filter-strategy") || {}).value || "").trim();
|
||||
var from = ($("or-filter-from") || {}).value || "";
|
||||
var to = ($("or-filter-to") || {}).value || "";
|
||||
if (uly) p.set("underlying", uly);
|
||||
if (opt) p.set("opt_type", opt);
|
||||
if (strategy) p.set("strategy_tag", strategy);
|
||||
if (q) p.set("q", q);
|
||||
if (from) p.set("closed_from", from.replace("T", " ") + ":00");
|
||||
if (to) p.set("closed_to", to.replace("T", " ") + ":00");
|
||||
if (($("or-include-hedge-legs") || {}).checked) p.set("include_hedge_legs", "1");
|
||||
@@ -285,10 +336,10 @@
|
||||
if (!tbody) return;
|
||||
var wrap = beginListLoad("or-trades-wrap", soft);
|
||||
if (!soft) {
|
||||
tbody.innerHTML = '<tr><td colspan="6" class="muted">加载中…</td></tr>';
|
||||
tbody.innerHTML = '<tr><td colspan="7" class="muted">加载中…</td></tr>';
|
||||
}
|
||||
var p = baseQs();
|
||||
p.set("reviewed", "0");
|
||||
// 交易记录保留已复盘条目,不再只显示待复盘
|
||||
p.set("limit", String(PAGE_SIZE));
|
||||
p.set("offset", String(tradesPage * PAGE_SIZE));
|
||||
if (!doSync) p.set("sync", "0");
|
||||
@@ -299,7 +350,7 @@
|
||||
.then(function (data) {
|
||||
if (doSync) setSyncStatus("本地记录已加载");
|
||||
if (!data.ok) {
|
||||
tbody.innerHTML = '<tr><td colspan="6" class="muted">加载失败</td></tr>';
|
||||
tbody.innerHTML = '<tr><td colspan="7" class="muted">加载失败</td></tr>';
|
||||
endListLoad(wrap);
|
||||
return;
|
||||
}
|
||||
@@ -311,7 +362,7 @@
|
||||
tradesCache = {};
|
||||
if (!rows.length) {
|
||||
tbody.innerHTML =
|
||||
'<tr><td colspan="6" class="muted">暂无待复盘记录</td></tr>';
|
||||
'<tr><td colspan="7" class="muted">暂无交易记录</td></tr>';
|
||||
endListLoad(wrap);
|
||||
return;
|
||||
}
|
||||
@@ -319,6 +370,17 @@
|
||||
.map(function (t) {
|
||||
tradesCache[t.id] = t;
|
||||
var active = currentTradeId === t.id ? " or-row-active" : "";
|
||||
var reviewed = !!t.reviewed;
|
||||
var actionBtn = reviewed
|
||||
? '<button type="button" class="btn or-review-btn" data-id="' +
|
||||
t.id +
|
||||
'" style="font-size:.72rem;padding:2px 8px">编辑</button>'
|
||||
: '<button type="button" class="btn or-review-btn" data-id="' +
|
||||
t.id +
|
||||
'" style="font-size:.72rem;padding:2px 8px">复盘</button>';
|
||||
var badgeExtra = reviewed
|
||||
? ' <span class="or-badge" style="background:rgba(61,214,140,.2)">已复盘</span>'
|
||||
: "";
|
||||
return (
|
||||
'<tr class="or-trade-row' +
|
||||
active +
|
||||
@@ -327,26 +389,29 @@
|
||||
'">' +
|
||||
"<td><span class=\"or-badge\">" +
|
||||
escapeHtml(t.source_label || t.source_type) +
|
||||
"</span></td>" +
|
||||
"</span>" +
|
||||
badgeExtra +
|
||||
"</td>" +
|
||||
"<td>" +
|
||||
escapeHtml(tradeTitle(t)) +
|
||||
"</td>" +
|
||||
'<td style="' +
|
||||
pnlStyle(t.realized_pnl_total) +
|
||||
'<td class="' +
|
||||
pnlClass(t.realized_pnl_total) +
|
||||
'">' +
|
||||
fmtPnl(t.realized_pnl_total) +
|
||||
"</td>" +
|
||||
'<td class="muted" style="font-size:12px">' +
|
||||
'<td class="muted" style="font-size:12px;white-space:nowrap">' +
|
||||
escapeHtml(t.opened_at || "—") +
|
||||
"<br>" +
|
||||
"</td>" +
|
||||
'<td class="muted" style="font-size:12px;white-space:nowrap">' +
|
||||
escapeHtml(t.closed_at || "—") +
|
||||
"</td>" +
|
||||
"<td>" +
|
||||
fmtHold(t.hold_seconds) +
|
||||
"</td>" +
|
||||
'<td><button type="button" class="btn or-review-btn" data-id="' +
|
||||
t.id +
|
||||
'" style="font-size:.72rem;padding:2px 8px">复盘</button> ' +
|
||||
"<td>" +
|
||||
actionBtn +
|
||||
" " +
|
||||
'<button type="button" class="btn-secondary or-hide-btn" data-id="' +
|
||||
t.id +
|
||||
'" style="font-size:.72rem;padding:2px 8px">删除</button></td>' +
|
||||
@@ -371,7 +436,7 @@
|
||||
endListLoad(wrap);
|
||||
})
|
||||
.catch(function () {
|
||||
tbody.innerHTML = '<tr><td colspan="6" class="muted">加载失败</td></tr>';
|
||||
tbody.innerHTML = '<tr><td colspan="7" class="muted">加载失败</td></tr>';
|
||||
endListLoad(wrap);
|
||||
});
|
||||
}
|
||||
@@ -384,7 +449,7 @@
|
||||
if (!tbody) return;
|
||||
var wrap = beginListLoad("or-reviewed-wrap", soft);
|
||||
if (!soft) {
|
||||
tbody.innerHTML = '<tr><td colspan="6" class="muted">加载中…</td></tr>';
|
||||
tbody.innerHTML = '<tr><td colspan="11" class="muted">加载中…</td></tr>';
|
||||
}
|
||||
var p = baseQs();
|
||||
p.set("reviewed", "1");
|
||||
@@ -397,7 +462,7 @@
|
||||
})
|
||||
.then(function (data) {
|
||||
if (!data.ok) {
|
||||
tbody.innerHTML = '<tr><td colspan="6" class="muted">加载失败</td></tr>';
|
||||
tbody.innerHTML = '<tr><td colspan="11" class="muted">加载失败</td></tr>';
|
||||
endListLoad(wrap);
|
||||
return;
|
||||
}
|
||||
@@ -408,13 +473,16 @@
|
||||
var rows = data.trades || [];
|
||||
reviewedCache = {};
|
||||
if (!rows.length) {
|
||||
tbody.innerHTML = '<tr><td colspan="6" class="muted">暂无复盘记录</td></tr>';
|
||||
tbody.innerHTML = '<tr><td colspan="11" class="muted">暂无复盘记录</td></tr>';
|
||||
endListLoad(wrap);
|
||||
return;
|
||||
}
|
||||
tbody.innerHTML = rows
|
||||
.map(function (t) {
|
||||
reviewedCache[t.id] = t;
|
||||
var entry = t.entry || {};
|
||||
var direction = t.direction_view || entry.direction_view || "";
|
||||
var entryLogic = t.entry_logic || entry.entry_logic || "";
|
||||
return (
|
||||
'<tr class="or-reviewed-row" data-id="' +
|
||||
t.id +
|
||||
@@ -423,20 +491,37 @@
|
||||
escapeHtml(t.source_label || t.source_type) +
|
||||
"</span></td>" +
|
||||
"<td>" +
|
||||
escapeHtml(tradeTitle(t)) +
|
||||
escapeHtml(tradeContractLabel(t)) +
|
||||
"</td>" +
|
||||
'<td style="' +
|
||||
pnlStyle(t.realized_pnl_total) +
|
||||
"<td>" +
|
||||
escapeHtml(direction || "—") +
|
||||
"</td>" +
|
||||
'<td class="' +
|
||||
pnlClass(t.realized_pnl_total) +
|
||||
'">' +
|
||||
fmtPnl(t.realized_pnl_total) +
|
||||
"</td>" +
|
||||
'<td class="muted" style="font-size:12px;white-space:nowrap">' +
|
||||
escapeHtml(t.opened_at || "—") +
|
||||
"</td>" +
|
||||
'<td class="muted" style="font-size:12px;white-space:nowrap">' +
|
||||
escapeHtml(t.closed_at || "—") +
|
||||
"</td>" +
|
||||
"<td>" +
|
||||
escapeHtml(fmtHold(t.hold_seconds)) +
|
||||
"</td>" +
|
||||
"<td>" +
|
||||
escapeHtml(t.strategy_tag || "—") +
|
||||
"</td>" +
|
||||
"<td>" +
|
||||
escapeHtml(entryLogic || "—") +
|
||||
"</td>" +
|
||||
'<td class="' +
|
||||
resultClass(t.result_tag) +
|
||||
'">' +
|
||||
escapeHtml(t.result_tag || "—") +
|
||||
"</td>" +
|
||||
'<td class="muted" style="font-size:12px">' +
|
||||
'<td class="muted" style="font-size:12px;white-space:nowrap">' +
|
||||
escapeHtml(t.reviewed_at || "—") +
|
||||
"</td>" +
|
||||
"</tr>"
|
||||
@@ -451,25 +536,51 @@
|
||||
endListLoad(wrap);
|
||||
})
|
||||
.catch(function () {
|
||||
tbody.innerHTML = '<tr><td colspan="6" class="muted">加载失败</td></tr>';
|
||||
tbody.innerHTML = '<tr><td colspan="11" class="muted">加载失败</td></tr>';
|
||||
endListLoad(wrap);
|
||||
});
|
||||
}
|
||||
|
||||
function hideLightbox() {
|
||||
var box = $("or-img-lightbox");
|
||||
if (box) box.hidden = true;
|
||||
var img = $("or-img-lightbox-img");
|
||||
if (img) img.src = "";
|
||||
}
|
||||
|
||||
function showLightbox(src) {
|
||||
var url = String(src || "").trim();
|
||||
if (!url) return;
|
||||
var box = $("or-img-lightbox");
|
||||
var img = $("or-img-lightbox-img");
|
||||
if (box && img) {
|
||||
img.src = url;
|
||||
box.hidden = false;
|
||||
return;
|
||||
}
|
||||
if (typeof global.showImage === "function") {
|
||||
global.showImage(url);
|
||||
} else if (typeof window.showImage === "function") {
|
||||
window.showImage(url);
|
||||
} else {
|
||||
global.open(url, "_blank");
|
||||
}
|
||||
}
|
||||
|
||||
function hideDetail() {
|
||||
var panel = $("or-detail-panel");
|
||||
if (panel) panel.classList.add("hidden");
|
||||
hideLightbox();
|
||||
var backdrop = $("or-detail-backdrop");
|
||||
if (backdrop) backdrop.hidden = true;
|
||||
}
|
||||
|
||||
function openDetail(tradeId) {
|
||||
var panel = $("or-detail-panel");
|
||||
if (!panel) return;
|
||||
panel.classList.remove("hidden");
|
||||
var backdrop = $("or-detail-backdrop");
|
||||
if (!backdrop) return;
|
||||
backdrop.hidden = false;
|
||||
($("or-detail-title") || {}).textContent = "加载中…";
|
||||
($("or-detail-meta") || {}).innerHTML = "";
|
||||
($("or-detail-text") || {}).innerHTML = "";
|
||||
($("or-detail-images") || {}).innerHTML = "";
|
||||
panel.scrollIntoView({ behavior: "smooth", block: "nearest" });
|
||||
|
||||
fetch("/api/options/review/trades/" + tradeId, { credentials: "same-origin" })
|
||||
.then(function (r) {
|
||||
@@ -487,6 +598,91 @@
|
||||
});
|
||||
}
|
||||
|
||||
function optionsJournalImgSrc(file) {
|
||||
var name = String(file || "").trim().replace(/\\/g, "/");
|
||||
var slash = name.lastIndexOf("/");
|
||||
if (slash >= 0) name = name.slice(slash + 1);
|
||||
if (!name) return "";
|
||||
// options_journal_* 在子目录;误走合约上传的 journal_* 在 static/images 根目录
|
||||
var base =
|
||||
name.toLowerCase().indexOf("options_journal_") === 0
|
||||
? "/static/images/options_journal/"
|
||||
: "/static/images/";
|
||||
return base + encodeURIComponent(name);
|
||||
}
|
||||
|
||||
function renderDetailImages(images) {
|
||||
var imagesHost = $("or-detail-images");
|
||||
if (!imagesHost) return;
|
||||
var byTf = {};
|
||||
(images || []).forEach(function (img) {
|
||||
var tf = String((img && img.tf) || "").trim();
|
||||
var file = String((img && img.file) || "").trim();
|
||||
if (!file) return;
|
||||
var key = tf || "_";
|
||||
byTf[key] = file;
|
||||
});
|
||||
var order = ["5m", "15m", "1h", "4h"];
|
||||
var keys = order.slice();
|
||||
Object.keys(byTf).forEach(function (k) {
|
||||
if (keys.indexOf(k) < 0) keys.push(k);
|
||||
});
|
||||
var cells = keys
|
||||
.map(function (tf) {
|
||||
var file = byTf[tf];
|
||||
if (!file) {
|
||||
if (order.indexOf(tf) < 0) return "";
|
||||
return (
|
||||
'<div class="or-detail-img-cell">' +
|
||||
'<span class="or-detail-img-label">' +
|
||||
escapeHtml(tf) +
|
||||
"</span>" +
|
||||
'<div class="or-detail-img-miss">未上传</div>' +
|
||||
"</div>"
|
||||
);
|
||||
}
|
||||
var src = optionsJournalImgSrc(file);
|
||||
var label = escapeHtml(tf === "_" ? "截图" : tf);
|
||||
return (
|
||||
'<div class="or-detail-img-cell">' +
|
||||
'<span class="or-detail-img-label">' +
|
||||
label +
|
||||
"</span>" +
|
||||
'<img class="or-detail-img-thumb" src="' +
|
||||
src +
|
||||
'" alt="' +
|
||||
label +
|
||||
'" data-src="' +
|
||||
src +
|
||||
'" loading="lazy">' +
|
||||
"</div>"
|
||||
);
|
||||
})
|
||||
.filter(Boolean);
|
||||
if (!cells.length) {
|
||||
imagesHost.innerHTML = '<div class="muted">无截图</div>';
|
||||
return;
|
||||
}
|
||||
imagesHost.innerHTML = cells.join("");
|
||||
imagesHost.querySelectorAll("img").forEach(function (img) {
|
||||
img.addEventListener("error", function () {
|
||||
var cell = img.closest(".or-detail-img-cell");
|
||||
if (!cell) return;
|
||||
var label = cell.querySelector(".or-detail-img-label");
|
||||
var tf = label ? label.textContent : "截图";
|
||||
cell.innerHTML =
|
||||
'<span class="or-detail-img-label">' +
|
||||
escapeHtml(tf) +
|
||||
"</span>" +
|
||||
'<div class="or-detail-img-miss">文件缺失或无法加载</div>';
|
||||
});
|
||||
img.addEventListener("click", function () {
|
||||
var src = img.getAttribute("data-src") || img.src;
|
||||
showLightbox(src);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function renderDetail(t) {
|
||||
var e = t.entry || {};
|
||||
reviewedCache[t.id] = t;
|
||||
@@ -502,8 +698,8 @@
|
||||
["合约/计划", tradeTitle(t)],
|
||||
["盈亏", fmtPnl(t.realized_pnl_total)],
|
||||
["持有", fmtHold(t.hold_seconds)],
|
||||
["开仓", t.opened_at || "—"],
|
||||
["平仓", t.closed_at || "—"],
|
||||
["开仓时间", t.opened_at || "—"],
|
||||
["平仓时间", t.closed_at || "—"],
|
||||
["策略", e.strategy_tag || "—"],
|
||||
["方向", e.direction_view || "—"],
|
||||
["结果", e.result_tag || "—"],
|
||||
@@ -517,10 +713,20 @@
|
||||
}
|
||||
meta.innerHTML = cells
|
||||
.map(function (pair) {
|
||||
var cls = "";
|
||||
if (pair[0] === "盈亏" || pair[0] === "永续盈亏" || pair[0] === "期权盈亏") {
|
||||
cls = pnlClass(t.realized_pnl_total);
|
||||
if (pair[0] === "永续盈亏") cls = pnlClass(t.realized_pnl_perp);
|
||||
if (pair[0] === "期权盈亏") cls = pnlClass(t.realized_pnl_options);
|
||||
} else if (pair[0] === "结果") {
|
||||
cls = resultClass(e.result_tag);
|
||||
}
|
||||
return (
|
||||
"<div><div class=\"muted\" style=\"font-size:11px\">" +
|
||||
escapeHtml(pair[0]) +
|
||||
"</div><div>" +
|
||||
'</div><div class="' +
|
||||
cls +
|
||||
'">' +
|
||||
escapeHtml(pair[1]) +
|
||||
"</div></div>"
|
||||
);
|
||||
@@ -540,13 +746,15 @@
|
||||
.map(function (leg) {
|
||||
return (
|
||||
"<tr><td>" +
|
||||
escapeHtml(leg.leg_role || "") +
|
||||
escapeHtml(legRoleLabel(leg.leg_role)) +
|
||||
"</td><td>" +
|
||||
escapeHtml(leg.inst_id || leg.symbol || "") +
|
||||
"</td><td>" +
|
||||
"</td><td class=\"" +
|
||||
pnlClass(leg.realized_pnl) +
|
||||
"\">" +
|
||||
fmtPnl(leg.realized_pnl) +
|
||||
"</td><td>" +
|
||||
escapeHtml(leg.close_reason || "") +
|
||||
escapeHtml(closeReasonLabel(leg.close_reason)) +
|
||||
"</td></tr>"
|
||||
);
|
||||
})
|
||||
@@ -559,64 +767,25 @@
|
||||
|
||||
var imagesHost = $("or-detail-images");
|
||||
if (imagesHost) {
|
||||
var images = e.images || [];
|
||||
if (!images.length) {
|
||||
imagesHost.innerHTML = '<div class="muted">无截图</div>';
|
||||
} else {
|
||||
imagesHost.innerHTML = images
|
||||
.map(function (img) {
|
||||
var file = String(img.file || "").trim();
|
||||
if (!file) return "";
|
||||
var src = "/static/images/options_journal/" + encodeURIComponent(file).replace(/%2F/g, "/");
|
||||
var label = escapeHtml(img.tf || "截图");
|
||||
return (
|
||||
'<div class="or-detail-img-cell">' +
|
||||
'<span class="or-detail-img-label">' +
|
||||
label +
|
||||
"</span>" +
|
||||
'<img class="or-detail-img-thumb" src="' +
|
||||
src +
|
||||
'" alt="' +
|
||||
label +
|
||||
'" data-src="' +
|
||||
src +
|
||||
'">' +
|
||||
"</div>"
|
||||
);
|
||||
})
|
||||
.join("");
|
||||
imagesHost.querySelectorAll("img").forEach(function (img) {
|
||||
img.addEventListener("click", function () {
|
||||
if (typeof global.showImage === "function") {
|
||||
global.showImage(img.getAttribute("data-src"));
|
||||
} else {
|
||||
global.open(img.getAttribute("data-src"), "_blank");
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
renderDetailImages(e.images || []);
|
||||
}
|
||||
}
|
||||
|
||||
function renderGroup(title, items) {
|
||||
if (!items || !items.length) {
|
||||
return (
|
||||
'<div class="or-stat-card"><div class="muted">' +
|
||||
title +
|
||||
'</div><div class="muted">无数据</div></div>'
|
||||
);
|
||||
}
|
||||
if (!items || !items.length) return "";
|
||||
var lines = items
|
||||
.slice(0, 8)
|
||||
.map(function (g) {
|
||||
var keyLabel =
|
||||
title === "对冲结束原因" ? closeReasonLabel(g.key) : String(g.key || "");
|
||||
return (
|
||||
'<div style="display:flex;justify-content:space-between;gap:8px;font-size:13px">' +
|
||||
"<span>" +
|
||||
escapeHtml(g.key) +
|
||||
'<div class="or-stat-row">' +
|
||||
'<span class="or-stat-key">' +
|
||||
escapeHtml(keyLabel) +
|
||||
" · " +
|
||||
g.count +
|
||||
"笔</span>" +
|
||||
"<span>" +
|
||||
'<span class="or-stat-val">' +
|
||||
fmtPnl(g.pnl_sum) +
|
||||
" / 胜" +
|
||||
(g.win_rate || 0) +
|
||||
@@ -626,7 +795,7 @@
|
||||
})
|
||||
.join("");
|
||||
return (
|
||||
'<div class="or-stat-card"><div style="font-weight:600;margin-bottom:6px">' +
|
||||
'<div class="or-stat-card"><div class="or-stat-card-title">' +
|
||||
title +
|
||||
"</div>" +
|
||||
lines +
|
||||
@@ -654,23 +823,31 @@
|
||||
["平均持有", fmtHold(k.avg_hold_sec)],
|
||||
]
|
||||
.map(function (pair) {
|
||||
var cls = "";
|
||||
if (pair[0] === "累计盈亏") cls = pnlClass(k.pnl_sum);
|
||||
if (pair[0] === "平均盈亏") cls = pnlClass(k.avg_pnl);
|
||||
return (
|
||||
'<div><div class="muted" style="font-size:12px">' +
|
||||
'<div class="or-kpi-tile"><div class="or-kpi-label">' +
|
||||
pair[0] +
|
||||
'</div><div style="font-weight:600">' +
|
||||
'</div><div class="or-kpi-value' +
|
||||
(cls ? " " + cls : "") +
|
||||
'">' +
|
||||
pair[1] +
|
||||
"</div></div>"
|
||||
);
|
||||
})
|
||||
.join("");
|
||||
groups.innerHTML = [
|
||||
var html = [
|
||||
renderGroup("按类型", data.by_source_type),
|
||||
renderGroup("按标的", data.by_underlying),
|
||||
renderGroup("按策略", data.by_strategy),
|
||||
renderGroup("对冲结束原因", data.by_close_reason),
|
||||
renderGroup("持有周期", data.by_hold_bucket),
|
||||
renderGroup("Call/Put", data.by_opt_type),
|
||||
].join("");
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join("");
|
||||
groups.innerHTML = html || '<div class="muted" style="font-size:.76rem">暂无分组数据</div>';
|
||||
})
|
||||
.catch(function () {});
|
||||
}
|
||||
@@ -849,12 +1026,13 @@
|
||||
($("or-f-inst") || {}).value =
|
||||
t.source_type === "option_spot"
|
||||
? t.inst_id || ""
|
||||
: (t.source_label || "") + (t.plan_close_reason ? " · " + t.plan_close_reason : "");
|
||||
: (t.source_label || "") +
|
||||
(t.plan_close_reason ? " · " + closeReasonLabel(t.plan_close_reason) : "");
|
||||
($("or-f-pnl") || {}).value = fmtPnl(t.realized_pnl_total);
|
||||
($("or-f-hold") || {}).value = fmtHold(t.hold_seconds);
|
||||
setSelectValue($("or-f-strategy"), e.strategy_tag || "");
|
||||
setSelectValue($("or-f-direction"), e.direction_view || autoDirection(t));
|
||||
($("or-f-exit") || {}).value = e.exit_reason || t.plan_close_reason || "";
|
||||
($("or-f-exit") || {}).value = e.exit_reason || closeReasonLabel(t.plan_close_reason) || "";
|
||||
($("or-f-followed") || {}).value = e.followed_plan || "";
|
||||
setSelectValue($("or-f-result"), e.result_tag || autoResultTag(t.realized_pnl_total));
|
||||
setSelectValue($("or-f-entry"), e.entry_logic || "");
|
||||
@@ -883,7 +1061,21 @@
|
||||
);
|
||||
if (hidden && img.file) {
|
||||
hidden.value = img.file;
|
||||
if (status) status.textContent = "已有 " + img.file;
|
||||
if (status) {
|
||||
var src = optionsJournalImgSrc(img.file);
|
||||
status.innerHTML =
|
||||
'已有 <a href="' +
|
||||
src +
|
||||
'" target="_blank" rel="noopener">' +
|
||||
escapeHtml(img.file) +
|
||||
'</a><br><img class="or-slot-thumb" src="' +
|
||||
src +
|
||||
'" alt="' +
|
||||
escapeHtml(img.tf || "") +
|
||||
'" loading="lazy">';
|
||||
status.className =
|
||||
"journal-upload-status or-upload-status journal-upload-status--ok";
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
@@ -896,13 +1088,13 @@
|
||||
.map(function (leg) {
|
||||
return (
|
||||
"<tr><td>" +
|
||||
escapeHtml(leg.leg_role || "") +
|
||||
escapeHtml(legRoleLabel(leg.leg_role)) +
|
||||
"</td><td>" +
|
||||
escapeHtml(leg.inst_id || leg.symbol || "") +
|
||||
"</td><td>" +
|
||||
fmtPnl(leg.realized_pnl) +
|
||||
"</td><td>" +
|
||||
escapeHtml(leg.close_reason || "") +
|
||||
escapeHtml(closeReasonLabel(leg.close_reason)) +
|
||||
"</td></tr>"
|
||||
);
|
||||
})
|
||||
@@ -1068,9 +1260,34 @@
|
||||
if (detailEdit) {
|
||||
detailEdit.addEventListener("click", function () {
|
||||
var id = Number(detailEdit.getAttribute("data-id") || 0);
|
||||
if (id) openJournalForm(id);
|
||||
if (id) {
|
||||
hideDetail();
|
||||
openJournalForm(id);
|
||||
}
|
||||
});
|
||||
}
|
||||
var detailBackdrop = $("or-detail-backdrop");
|
||||
if (detailBackdrop) {
|
||||
detailBackdrop.addEventListener("click", function (ev) {
|
||||
if (ev.target === detailBackdrop) hideDetail();
|
||||
});
|
||||
}
|
||||
var lightbox = $("or-img-lightbox");
|
||||
if (lightbox) {
|
||||
lightbox.addEventListener("click", function () {
|
||||
hideLightbox();
|
||||
});
|
||||
}
|
||||
document.addEventListener("keydown", function (ev) {
|
||||
if (ev.key !== "Escape") return;
|
||||
var lb = $("or-img-lightbox");
|
||||
if (lb && !lb.hidden) {
|
||||
hideLightbox();
|
||||
return;
|
||||
}
|
||||
var bd = $("or-detail-backdrop");
|
||||
if (bd && !bd.hidden) hideDetail();
|
||||
});
|
||||
["or-filter-uly", "or-filter-opt", "or-include-hedge-legs"].forEach(function (id) {
|
||||
var el = $(id);
|
||||
if (el) {
|
||||
@@ -1081,7 +1298,7 @@
|
||||
});
|
||||
}
|
||||
});
|
||||
["or-filter-strategy", "or-filter-from", "or-filter-to"].forEach(function (id) {
|
||||
["or-filter-q", "or-filter-strategy", "or-filter-from", "or-filter-to"].forEach(function (id) {
|
||||
var el = $(id);
|
||||
if (el) {
|
||||
el.addEventListener("change", function () {
|
||||
@@ -1094,9 +1311,28 @@
|
||||
bindUploadSlots();
|
||||
hideJournalForm();
|
||||
hideDetail();
|
||||
hardenSearchAutofill();
|
||||
setActiveTab("option_spot");
|
||||
}
|
||||
|
||||
function hardenSearchAutofill() {
|
||||
var qEl = $("or-filter-q");
|
||||
if (!qEl) return;
|
||||
function wipe() {
|
||||
qEl.value = "";
|
||||
}
|
||||
wipe();
|
||||
qEl.addEventListener("focus", function () {
|
||||
qEl.removeAttribute("readonly");
|
||||
});
|
||||
qEl.addEventListener("blur", function () {
|
||||
if (!qEl.value) qEl.setAttribute("readonly", "readonly");
|
||||
});
|
||||
// 密码管理器常延后写入用户名,加载后再清两次
|
||||
setTimeout(wipe, 200);
|
||||
setTimeout(wipe, 800);
|
||||
}
|
||||
|
||||
global.OptionsReview = {
|
||||
init: init,
|
||||
openJournalForm: openJournalForm,
|
||||
|
||||
@@ -342,4 +342,47 @@
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function hardenAmountAutofill(ids) {
|
||||
ids.forEach(function (id) {
|
||||
const el = document.getElementById(id);
|
||||
if (!el) return;
|
||||
function wipe() {
|
||||
const v = String(el.value || "").trim();
|
||||
if (/^[a-z][a-z0-9._-]{1,31}$/i.test(v)) el.value = "";
|
||||
}
|
||||
wipe();
|
||||
el.setAttribute("readonly", "readonly");
|
||||
el.addEventListener("focus", function () {
|
||||
el.removeAttribute("readonly");
|
||||
});
|
||||
el.addEventListener("blur", function () {
|
||||
if (!el.value) el.setAttribute("readonly", "readonly");
|
||||
});
|
||||
setTimeout(wipe, 200);
|
||||
setTimeout(wipe, 800);
|
||||
setTimeout(wipe, 2000);
|
||||
});
|
||||
}
|
||||
|
||||
// 全部划转/兑换前去掉 readonly,避免写不进数量
|
||||
["opt-set-swap-all-btn", "opt-set-int-all-btn", "opt-set-cross-all-btn"].forEach(function (btnId) {
|
||||
const btn = document.getElementById(btnId);
|
||||
if (!btn) return;
|
||||
btn.addEventListener(
|
||||
"click",
|
||||
function () {
|
||||
const map = {
|
||||
"opt-set-swap-all-btn": "opt-set-swap-amount",
|
||||
"opt-set-int-all-btn": "opt-set-int-amount",
|
||||
"opt-set-cross-all-btn": "opt-set-cross-amount",
|
||||
};
|
||||
const input = document.getElementById(map[btnId]);
|
||||
if (input) input.removeAttribute("readonly");
|
||||
},
|
||||
true
|
||||
);
|
||||
});
|
||||
|
||||
hardenAmountAutofill(["opt-set-swap-amount", "opt-set-int-amount", "opt-set-cross-amount"]);
|
||||
})();
|
||||
|
||||
Vendored
+32
@@ -58,6 +58,7 @@ HOT_RELOAD_EXACT = frozenset({
|
||||
"RISK_COOLING_HOURS_MANUAL",
|
||||
"RISK_COOLING_HOURS_MANUAL_JOURNAL",
|
||||
"RISK_MANUAL_CLOSE_DAILY_LIMIT",
|
||||
"RISK_DAILY_LOSS_LIMIT",
|
||||
"RISK_MOOD_ISSUES_DAILY_FREEZE",
|
||||
"KEY_AUTO_ORDER_ENABLED",
|
||||
"TRADE_DIRECTION_RESTRICT_ENABLED",
|
||||
@@ -69,7 +70,10 @@ HOT_RELOAD_EXACT = frozenset({
|
||||
"MONITOR_POLL_SECONDS",
|
||||
"AUTO_TRANSFER_ENABLED",
|
||||
"AUTO_TRANSFER_AMOUNT",
|
||||
"AUTO_TRANSFER_FROM",
|
||||
"AUTO_TRANSFER_TO",
|
||||
"AUTO_TRANSFER_BJ_HOUR",
|
||||
"TRANSFER_CCY",
|
||||
"FORCE_CLOSE_ENABLED",
|
||||
"FORCE_CLOSE_BJ_HOUR",
|
||||
"BTC_LEVERAGE",
|
||||
@@ -83,11 +87,20 @@ HOT_RELOAD_EXACT = frozenset({
|
||||
"APP_AUTH_DISABLED",
|
||||
"WECHAT_WEBHOOK",
|
||||
"HEDGE_PLAN_ENABLED",
|
||||
"HEDGE_PLAN_SHOW_PERP_OPTIONS",
|
||||
"HEDGE_PLAN_SHOW_OPTIONS_OPTIONS",
|
||||
"OKX_OPTIONS_CHAIN_ASK_LIQ_FILTER_ENABLED",
|
||||
"HEDGE_PLAN_LIVE_ORDER",
|
||||
"HEDGE_PLAN_OPEN_ORDER",
|
||||
"HEDGE_PLAN_ON_PERP_SL_CLOSE_OPTIONS",
|
||||
"HEDGE_PLAN_ON_PERP_TP_CLOSE_OPTIONS",
|
||||
"HEDGE_PLAN_OO_CLOSE_WINNER_ONLY",
|
||||
"HEDGE_PLAN_OO_CLOSE_MODE_ENABLED",
|
||||
"HEDGE_PLAN_OO_BIAS_SPLIT_BY",
|
||||
"HEDGE_PLAN_OO_BIAS_RATIO",
|
||||
"HEDGE_PLAN_BUDGET_BUFFER",
|
||||
"HEDGE_PLAN_OPTIONS_MUTUAL_EXCLUSIVE",
|
||||
"HEDGE_PLAN_MANUAL_COMPLETE_ON_PARTIAL",
|
||||
"MAX_ACTIVE_HEDGE_PLANS",
|
||||
"HEDGE_PLAN_MONITOR_POLL_SECONDS",
|
||||
"HEDGE_PLAN_PARTIAL_AUTO_CLOSE_OPTION",
|
||||
@@ -116,12 +129,28 @@ SELECT_OPTIONS: dict[str, tuple[tuple[str, str], ...]] = {
|
||||
("long_only", "仅做多"),
|
||||
("short_only", "仅做空"),
|
||||
),
|
||||
"AUTO_TRANSFER_FROM": (
|
||||
("funding", "funding 资金账户"),
|
||||
("swap", "swap 交易账户"),
|
||||
("spot", "spot 现货"),
|
||||
),
|
||||
"AUTO_TRANSFER_TO": (
|
||||
("swap", "swap 交易账户"),
|
||||
("funding", "funding 资金账户"),
|
||||
("spot", "spot 现货"),
|
||||
),
|
||||
"TRANSFER_CCY": (("USDT", "USDT"),),
|
||||
"HEDGE_PLAN_OO_BIAS_SPLIT_BY": (
|
||||
("budget", "预算金额"),
|
||||
("sheets", "张数"),
|
||||
),
|
||||
}
|
||||
|
||||
_SELECT_ALIASES: dict[str, dict[str, str]] = {
|
||||
"OKX_TD_MODE": {"cross_margin": "cross", "isolated_margin": "isolated"},
|
||||
"BINANCE_MARGIN_MODE": {"cross_margin": "cross", "isolated_margin": "isolated"},
|
||||
"GATE_TD_MODE": {"cross_margin": "cross", "isolated_margin": "isolated"},
|
||||
"TRANSFER_CCY": {"usdt": "USDT"},
|
||||
}
|
||||
|
||||
|
||||
@@ -145,10 +174,13 @@ def normalize_select_value(key: str, value: Optional[str]) -> str:
|
||||
if low in aliases:
|
||||
return aliases[low]
|
||||
allowed = {v for v, _ in (SELECT_OPTIONS.get(key) or ())}
|
||||
allowed_by_lower = {v.lower(): v for v in allowed}
|
||||
if low in allowed:
|
||||
return low
|
||||
if raw in allowed:
|
||||
return raw
|
||||
if low in allowed_by_lower:
|
||||
return allowed_by_lower[low]
|
||||
return raw
|
||||
|
||||
|
||||
|
||||
Vendored
+101
-6
@@ -67,7 +67,11 @@ _SHARED_SECTIONS: list[dict[str, Any]] = [
|
||||
("TRADE_SYMBOL_RESTRICT_ENABLED", "币种白名单开关", ""),
|
||||
("TRADE_SYMBOL_WHITELIST", "白名单币种", "逗号分隔,如 BTC,ETH"),
|
||||
("TRADING_DAY_RESET_HOUR", "交易日切点(北京时间)", "整点,默认 8"),
|
||||
("TRADING_DAY_RESET_OPEN_GUARD_ENABLED", "切点前禁止新开仓", ""),
|
||||
(
|
||||
"TRADING_DAY_RESET_OPEN_GUARD_ENABLED",
|
||||
"切点前禁止新开仓",
|
||||
"默认 true;开启则北京时间切点前禁止斐波登记与人工开仓;说明见风控说明·交易执行",
|
||||
),
|
||||
("MAX_ACTIVE_POSITIONS", "最大同时持仓", ""),
|
||||
("MANUAL_MIN_PLANNED_RR", "人工最低盈亏比", "如 1.4"),
|
||||
("KEY_AUTO_ORDER_ENABLED", "关键位自动单", "关闭后箱体/收敛/斐波等不自动开仓;支撑阻力提醒仍可用"),
|
||||
@@ -90,6 +94,7 @@ _SHARED_SECTIONS: list[dict[str, Any]] = [
|
||||
("RISK_COOLING_HOURS_MANUAL", "手动平仓冷静(小时)", ""),
|
||||
("RISK_COOLING_HOURS_MANUAL_JOURNAL", "复盘情绪冷静(小时)", ""),
|
||||
("RISK_MANUAL_CLOSE_DAILY_LIMIT", "日手动平仓次数上限", ""),
|
||||
("RISK_DAILY_LOSS_LIMIT", "日亏损次数上限", "默认2;达限当日冻结开仓;0=不因亏损次数冻结"),
|
||||
("RISK_MOOD_ISSUES_DAILY_FREEZE", "情绪标签日冻结", ""),
|
||||
],
|
||||
},
|
||||
@@ -98,10 +103,10 @@ _SHARED_SECTIONS: list[dict[str, Any]] = [
|
||||
"fields": [
|
||||
("AUTO_TRANSFER_ENABLED", "启用自动划转", ""),
|
||||
("AUTO_TRANSFER_AMOUNT", "目标余额(U)", "交易账户目标 USDT"),
|
||||
("AUTO_TRANSFER_FROM", "划出账户", "funding 或 swap"),
|
||||
("AUTO_TRANSFER_TO", "划入账户", "swap 或 funding"),
|
||||
("AUTO_TRANSFER_FROM", "划出账户", "余额不足时从此账户划入交易账户"),
|
||||
("AUTO_TRANSFER_TO", "划入账户", "目标余额所在账户,一般为 swap"),
|
||||
("AUTO_TRANSFER_BJ_HOUR", "执行整点(北京时间)", ""),
|
||||
("TRANSFER_CCY", "划转币种", "默认 USDT"),
|
||||
("TRANSFER_CCY", "划转币种", ""),
|
||||
],
|
||||
},
|
||||
{
|
||||
@@ -126,6 +131,11 @@ _OPTIONS_SECTION: dict[str, Any] = {
|
||||
("OKX_OPTIONS_TRADE_BUDGET_USDC", "单笔预算(USDC)", ""),
|
||||
("OKX_OPTIONS_BUDGET_BUFFER", "预算缓冲比例", "如 0.95"),
|
||||
("OKX_OPTIONS_DEFAULT_UNDERLY", "默认标的", "如 ETH"),
|
||||
(
|
||||
"OKX_OPTIONS_CHAIN_ASK_LIQ_FILTER_ENABLED",
|
||||
"链上仅显示有卖一",
|
||||
"默认 true;开启后隐藏无卖一深度或深度不足1张的合约(含标记价估算行)",
|
||||
),
|
||||
],
|
||||
}
|
||||
|
||||
@@ -134,14 +144,50 @@ _HEDGE_PLAN_SECTION: dict[str, Any] = {
|
||||
"exchanges": frozenset({"okx"}),
|
||||
"fields": [
|
||||
("HEDGE_PLAN_ENABLED", "启用对冲计划", "关闭则隐藏导航且不可开仓"),
|
||||
("HEDGE_PLAN_SHOW_PERP_OPTIONS", "显示永期对冲", "默认 true;关闭后隐藏永期 Tab,不可测算/开仓"),
|
||||
("HEDGE_PLAN_SHOW_OPTIONS_OPTIONS", "显示期期对冲", "默认 true;关闭后隐藏期期 Tab,不可测算/开仓"),
|
||||
("HEDGE_PLAN_LIVE_ORDER", "允许对冲真实下单", "再与实盘 LIVE_TRADING_ENABLED 同开才可启动永期"),
|
||||
("HEDGE_PLAN_OPEN_ORDER", "永期开仓顺序", "options_first 或 perp_first"),
|
||||
("HEDGE_PLAN_ON_PERP_SL_CLOSE_OPTIONS", "永期止损后强制平期权", "保护机制,建议保持 true"),
|
||||
("HEDGE_PLAN_ON_PERP_TP_CLOSE_OPTIONS", "永期止盈后强制平期权", "默认 false,保险腿不平"),
|
||||
("HEDGE_PLAN_OO_CLOSE_WINNER_ONLY", "期期只平盈利腿", "达目标价只平盈利方"),
|
||||
(
|
||||
"HEDGE_PLAN_OO_CLOSE_MODE_ENABLED",
|
||||
"期期平仓模式(方案C)",
|
||||
"默认 true;开启后页面可选「到期平/全平」(盈利腿平后另一腿);关闭则固定到期平",
|
||||
),
|
||||
(
|
||||
"HEDGE_PLAN_OO_BIAS_SPLIT_BY",
|
||||
"期期做多做空拆分口径",
|
||||
"默认预算金额;budget=按权利金预算按比例分两腿;sheets=先算同张数总张数(2n)再按比例拆",
|
||||
),
|
||||
(
|
||||
"HEDGE_PLAN_OO_BIAS_RATIO",
|
||||
"期期做多做空主腿占比",
|
||||
"默认 0.7(即 7:3);做多主腿=Call,做空主腿=Put;须在 0~1 之间",
|
||||
),
|
||||
(
|
||||
"HEDGE_PLAN_BUDGET_BUFFER",
|
||||
"对冲预算缓冲比例",
|
||||
"默认 0.95;仅对冲计划(期期可用预算=交易户×本比例);与期权页 OKX_OPTIONS_BUDGET_BUFFER 独立",
|
||||
),
|
||||
(
|
||||
"HEDGE_PLAN_OPTIONS_MUTUAL_EXCLUSIVE",
|
||||
"对冲与期权互斥门控",
|
||||
"默认 true;开启时:有对冲计划则不可单独开期权,有单独期权则不可启动对冲;关闭后两边可同时开",
|
||||
),
|
||||
(
|
||||
"HEDGE_PLAN_MANUAL_COMPLETE_ON_PARTIAL",
|
||||
"半腿失败改手动补开",
|
||||
"默认 true;开启时半腿失败不自动平,计划挂 partial,页面可补开永续/腿B;并强制关闭下方自动平",
|
||||
),
|
||||
("MAX_ACTIVE_HEDGE_PLANS", "最大同时活跃计划数", "建议 1"),
|
||||
("HEDGE_PLAN_MONITOR_POLL_SECONDS", "对冲监控轮询(秒)", "默认 15"),
|
||||
("HEDGE_PLAN_PARTIAL_AUTO_CLOSE_OPTION", "半腿失败时自动平期权", ""),
|
||||
(
|
||||
"HEDGE_PLAN_PARTIAL_AUTO_CLOSE_OPTION",
|
||||
"半腿失败时自动平期权",
|
||||
"默认 true;若上方「半腿失败改手动补开」开启则本项强制无效(不会自动平)",
|
||||
),
|
||||
],
|
||||
}
|
||||
|
||||
@@ -152,13 +198,28 @@ _RUNTIME_ENV_DEFAULTS: dict[str, str] = {
|
||||
"RISK_COOLING_HOURS_MANUAL": "4",
|
||||
"RISK_COOLING_HOURS_MANUAL_JOURNAL": "1",
|
||||
"RISK_MANUAL_CLOSE_DAILY_LIMIT": "2",
|
||||
"RISK_DAILY_LOSS_LIMIT": "2",
|
||||
"RISK_MOOD_ISSUES_DAILY_FREEZE": "true",
|
||||
"AUTO_TRANSFER_FROM": "funding",
|
||||
"AUTO_TRANSFER_TO": "swap",
|
||||
"TRANSFER_CCY": "USDT",
|
||||
"HEDGE_PLAN_SHOW_PERP_OPTIONS": "true",
|
||||
"HEDGE_PLAN_SHOW_OPTIONS_OPTIONS": "true",
|
||||
"OKX_OPTIONS_CHAIN_ASK_LIQ_FILTER_ENABLED": "true",
|
||||
"HEDGE_PLAN_OO_CLOSE_MODE_ENABLED": "true",
|
||||
"HEDGE_PLAN_OO_BIAS_SPLIT_BY": "budget",
|
||||
"HEDGE_PLAN_OO_BIAS_RATIO": "0.7",
|
||||
"HEDGE_PLAN_BUDGET_BUFFER": "0.95",
|
||||
"HEDGE_PLAN_OPTIONS_MUTUAL_EXCLUSIVE": "true",
|
||||
"HEDGE_PLAN_MANUAL_COMPLETE_ON_PARTIAL": "true",
|
||||
}
|
||||
|
||||
|
||||
def _effective_env_value(key: str, file_values: dict[str, str], schema_default: str = "") -> str:
|
||||
if key in file_values:
|
||||
return file_values[key]
|
||||
file_val = str(file_values.get(key) or "").strip()
|
||||
if file_val:
|
||||
return file_val
|
||||
runtime = os.getenv(key)
|
||||
if runtime is not None and str(runtime).strip() != "":
|
||||
return str(runtime).strip()
|
||||
@@ -167,6 +228,10 @@ def _effective_env_value(key: str, file_values: dict[str, str], schema_default:
|
||||
return _RUNTIME_ENV_DEFAULTS.get(key, "")
|
||||
|
||||
|
||||
def _env_truthy(raw: str) -> bool:
|
||||
return str(raw or "").strip().lower() in ("1", "true", "yes", "on")
|
||||
|
||||
|
||||
def _schema_field_map(example_path: str) -> dict[str, dict[str, Any]]:
|
||||
out: dict[str, dict[str, Any]] = {}
|
||||
for group in parse_env_example_schema(example_path):
|
||||
@@ -185,6 +250,13 @@ def _build_field(
|
||||
meta = schema.get(key) or {}
|
||||
schema_default = meta.get("default") or ""
|
||||
val = _effective_env_value(key, values, schema_default)
|
||||
# 与运行时一致:手动补开开启时,「自动平期权」展示为关闭(实际也不会执行)
|
||||
if key == "HEDGE_PLAN_PARTIAL_AUTO_CLOSE_OPTION":
|
||||
manual = _effective_env_value(
|
||||
"HEDGE_PLAN_MANUAL_COMPLETE_ON_PARTIAL", values, "true"
|
||||
)
|
||||
if _env_truthy(manual):
|
||||
val = "false"
|
||||
masked = _mask_value(key, val)
|
||||
ftype = meta.get("type") or _field_type(key, val or schema_default)
|
||||
options = select_options_for(key)
|
||||
@@ -296,3 +368,26 @@ def validate_env_ui_updates(
|
||||
)
|
||||
groups.append({"title": sec["title"], "fields": fields})
|
||||
return validate_env_updates(groups, updates)
|
||||
|
||||
|
||||
def coerce_hedge_partial_close_with_manual(
|
||||
clean: dict[str, str],
|
||||
*,
|
||||
env_path: str = "",
|
||||
) -> dict[str, str]:
|
||||
"""手动补开为开启时,强制把自动平写成 false(与运行时一致)."""
|
||||
out = dict(clean or {})
|
||||
manual = out.get("HEDGE_PLAN_MANUAL_COMPLETE_ON_PARTIAL")
|
||||
if manual is None and env_path:
|
||||
try:
|
||||
from lib.env.env_file_lib import env_get_all, read_env_lines
|
||||
|
||||
file_vals = env_get_all(read_env_lines(env_path))
|
||||
manual = _effective_env_value(
|
||||
"HEDGE_PLAN_MANUAL_COMPLETE_ON_PARTIAL", file_vals, "true"
|
||||
)
|
||||
except Exception:
|
||||
manual = "true"
|
||||
if _env_truthy(str(manual or "")):
|
||||
out["HEDGE_PLAN_PARTIAL_AUTO_CLOSE_OPTION"] = "false"
|
||||
return out
|
||||
|
||||
@@ -22,6 +22,7 @@ def execute_transfer_usdt(
|
||||
) -> tuple[bool, str, Any]:
|
||||
if amount <= 0:
|
||||
return False, "划转金额必须大于0", None
|
||||
ccy = (transfer_ccy or "USDT").strip().upper() or "USDT"
|
||||
ok_live, reason = ensure_live_ready()
|
||||
if not ok_live:
|
||||
return False, reason, None
|
||||
@@ -31,7 +32,7 @@ def execute_transfer_usdt(
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
resp = exchange.transfer(transfer_ccy, float(amount), from_account, to_account)
|
||||
resp = exchange.transfer(ccy, float(amount), from_account, to_account)
|
||||
return True, "划转成功", resp
|
||||
except Exception as e:
|
||||
msg = str(e)
|
||||
|
||||
@@ -962,6 +962,119 @@ def cancel_option_order(ex: ccxt.okx, *, inst_id: str, ord_id: str) -> dict[str,
|
||||
return {"ok": False, "msg": _okx_trade_error_message(e)}
|
||||
|
||||
|
||||
def fetch_option_order(ex: ccxt.okx, *, inst_id: str, ord_id: str) -> dict[str, Any]:
|
||||
"""查询单笔期权订单状态."""
|
||||
inst_id = (inst_id or "").strip()
|
||||
ord_id = (ord_id or "").strip()
|
||||
if not inst_id or not ord_id:
|
||||
return {"ok": False, "msg": "缺少 inst_id 或 ord_id"}
|
||||
try:
|
||||
resp = ex.private_get_trade_order({"instId": inst_id, "ordId": ord_id})
|
||||
data = (resp or {}).get("data") or []
|
||||
if not data or not isinstance(data[0], dict):
|
||||
return {"ok": False, "msg": "订单不存在或暂不可查", "raw": resp}
|
||||
o = data[0]
|
||||
sz = _safe_float(o.get("sz"))
|
||||
acc = _safe_float(o.get("accFillSz"))
|
||||
if acc is None:
|
||||
acc = _safe_float(o.get("fillSz")) or 0.0
|
||||
avg = _safe_float(o.get("avgPx"))
|
||||
fill_px = _safe_float(o.get("fillPx"))
|
||||
if avg is None or avg <= 0:
|
||||
avg = fill_px
|
||||
state = str(o.get("state") or "").strip().lower()
|
||||
return {
|
||||
"ok": True,
|
||||
"ord_id": str(o.get("ordId") or ord_id),
|
||||
"inst_id": str(o.get("instId") or inst_id),
|
||||
"state": state,
|
||||
"sz": int(sz) if sz is not None else None,
|
||||
"acc_fill_sz": float(acc or 0),
|
||||
"avg_px": avg,
|
||||
"side": str(o.get("side") or "").lower(),
|
||||
"ord_type": str(o.get("ordType") or ""),
|
||||
"raw": o,
|
||||
}
|
||||
except Exception as e:
|
||||
return {"ok": False, "msg": _okx_trade_error_message(e)}
|
||||
|
||||
|
||||
def wait_option_order_full_fill(
|
||||
ex: ccxt.okx,
|
||||
*,
|
||||
inst_id: str,
|
||||
ord_id: str,
|
||||
need_sheets: int,
|
||||
timeout_sec: float = 12.0,
|
||||
poll_sec: float = 0.35,
|
||||
cancel_on_timeout: bool = True,
|
||||
) -> dict[str, Any]:
|
||||
"""轮询至完全成交;超时则撤单.未完全成交返回 ok=False."""
|
||||
need = max(1, int(need_sheets))
|
||||
deadline = time.time() + max(0.5, float(timeout_sec))
|
||||
last: dict[str, Any] = {}
|
||||
while time.time() < deadline:
|
||||
last = fetch_option_order(ex, inst_id=inst_id, ord_id=ord_id)
|
||||
if not last.get("ok"):
|
||||
time.sleep(max(0.15, float(poll_sec)))
|
||||
continue
|
||||
acc = float(last.get("acc_fill_sz") or 0)
|
||||
state = str(last.get("state") or "")
|
||||
if acc + 1e-9 >= need or state == "filled":
|
||||
if acc + 1e-9 < need:
|
||||
return {
|
||||
"ok": False,
|
||||
"msg": f"订单已结束但成交不足 {need} 张(已成 {acc:g})",
|
||||
"filled_sheets": acc,
|
||||
"order": last,
|
||||
}
|
||||
return {
|
||||
"ok": True,
|
||||
"filled_sheets": int(round(acc)),
|
||||
"avg_px": last.get("avg_px"),
|
||||
"state": state,
|
||||
"order": last,
|
||||
}
|
||||
if state in ("canceled", "cancelled", "mmp_canceled"):
|
||||
if acc + 1e-9 >= need:
|
||||
return {
|
||||
"ok": True,
|
||||
"filled_sheets": int(round(acc)),
|
||||
"avg_px": last.get("avg_px"),
|
||||
"state": state,
|
||||
"order": last,
|
||||
}
|
||||
return {
|
||||
"ok": False,
|
||||
"msg": f"订单已撤销且未完全成交(已成 {acc:g}/{need})",
|
||||
"filled_sheets": acc,
|
||||
"order": last,
|
||||
}
|
||||
time.sleep(max(0.15, float(poll_sec)))
|
||||
|
||||
if cancel_on_timeout:
|
||||
cancel_option_order(ex, inst_id=inst_id, ord_id=ord_id)
|
||||
time.sleep(0.25)
|
||||
last = fetch_option_order(ex, inst_id=inst_id, ord_id=ord_id)
|
||||
acc = float((last or {}).get("acc_fill_sz") or 0) if (last or {}).get("ok") else 0.0
|
||||
if acc + 1e-9 >= need:
|
||||
return {
|
||||
"ok": True,
|
||||
"filled_sheets": int(round(acc)),
|
||||
"avg_px": (last or {}).get("avg_px"),
|
||||
"state": (last or {}).get("state"),
|
||||
"order": last,
|
||||
"timed_out": True,
|
||||
}
|
||||
return {
|
||||
"ok": False,
|
||||
"msg": f"等待成交超时({float(timeout_sec):g}s),已撤未成交部分;已成 {acc:g}/{need}",
|
||||
"filled_sheets": acc,
|
||||
"order": last,
|
||||
"timed_out": True,
|
||||
}
|
||||
|
||||
|
||||
def place_option_limit_order(
|
||||
ex: ccxt.okx,
|
||||
*,
|
||||
@@ -973,12 +1086,16 @@ def place_option_limit_order(
|
||||
tick_sz: Any = None,
|
||||
reduce_only: bool = False,
|
||||
pos_side: str | None = None,
|
||||
ord_type: str = "limit",
|
||||
) -> dict[str, Any]:
|
||||
side_l = (side or "").lower()
|
||||
if side_l not in ("buy", "sell"):
|
||||
return {"ok": False, "msg": "side 必须为 buy 或 sell"}
|
||||
if sheets < 1:
|
||||
return {"ok": False, "msg": "张数至少为 1"}
|
||||
ot = (ord_type or "limit").strip().lower()
|
||||
if ot not in ("limit", "ioc", "fok", "post_only"):
|
||||
return {"ok": False, "msg": f"不支持的 ordType: {ord_type}"}
|
||||
px = round_option_px(float(price), tick_sz, side_l)
|
||||
if px <= 0:
|
||||
return {"ok": False, "msg": "价格无效"}
|
||||
@@ -986,7 +1103,7 @@ def place_option_limit_order(
|
||||
"instId": inst_id,
|
||||
"tdMode": td_mode,
|
||||
"side": side_l,
|
||||
"ordType": "limit",
|
||||
"ordType": ot,
|
||||
"px": format_option_px(px, tick_sz),
|
||||
"sz": str(int(sheets)),
|
||||
}
|
||||
@@ -998,7 +1115,7 @@ def place_option_limit_order(
|
||||
resp = ex.private_post_trade_order(body)
|
||||
data = (resp or {}).get("data") or []
|
||||
if data and str(data[0].get("sCode")) == "0":
|
||||
return {"ok": True, "data": data[0], "raw": resp, "px": px}
|
||||
return {"ok": True, "data": data[0], "raw": resp, "px": px, "ord_type": ot}
|
||||
return {"ok": False, "msg": _okx_trade_error_message(resp=resp), "raw": resp, "px": px}
|
||||
except Exception as e:
|
||||
return {"ok": False, "msg": _okx_trade_error_message(e), "px": px}
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
"""对冲计划与单独期权开仓互斥门控.
|
||||
|
||||
默认开启:有进行中对冲计划时禁止单独开期权;有纯期权持仓时禁止启动对冲计划.
|
||||
关闭 HEDGE_PLAN_OPTIONS_MUTUAL_EXCLUSIVE 后两边可同时开.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from typing import Any, Callable, Optional
|
||||
|
||||
|
||||
def _env_bool(key: str, default: bool = False) -> bool:
|
||||
v = (os.getenv(key) or "").strip().lower()
|
||||
if not v:
|
||||
return default
|
||||
return v in ("1", "true", "yes", "on")
|
||||
|
||||
|
||||
def mutual_exclusive_enabled() -> bool:
|
||||
return _env_bool("HEDGE_PLAN_OPTIONS_MUTUAL_EXCLUSIVE", True)
|
||||
|
||||
|
||||
def block_standalone_option_open_msg(conn: Any) -> Optional[str]:
|
||||
"""若应拦截单独开期权,返回中文原因;否则 None."""
|
||||
if not mutual_exclusive_enabled():
|
||||
return None
|
||||
try:
|
||||
from lib.hedge_plan.hedge_plan_db import count_active_plans, init_hedge_plan_tables
|
||||
|
||||
init_hedge_plan_tables(conn)
|
||||
if count_active_plans(conn) > 0:
|
||||
return "存在进行中对冲计划,禁止单独开期权(可在 env「对冲与期权互斥门控」关闭)"
|
||||
except Exception:
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def _pos_nonzero(raw: dict[str, Any]) -> bool:
|
||||
try:
|
||||
return abs(float(raw.get("pos") or 0)) > 1e-12
|
||||
except (TypeError, ValueError):
|
||||
return False
|
||||
|
||||
|
||||
def has_standalone_option_position(conn: Any, raw_positions: list[dict[str, Any]] | None) -> bool:
|
||||
"""交易所期权持仓中,是否存在未挂在进行中对冲计划腿上的仓位."""
|
||||
if not raw_positions:
|
||||
return False
|
||||
from lib.instance.instance_dashboard_lib import _resolve_options_source
|
||||
|
||||
for p in raw_positions:
|
||||
if not isinstance(p, dict) or not _pos_nonzero(p):
|
||||
continue
|
||||
inst = str(p.get("instId") or p.get("inst_id") or "").strip()
|
||||
if not inst:
|
||||
continue
|
||||
source, _, _ = _resolve_options_source(conn, inst)
|
||||
if source == "option":
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def block_hedge_plan_start_msg(
|
||||
conn: Any,
|
||||
*,
|
||||
fetch_positions: Optional[Callable[[Any], Any]] = None,
|
||||
exchange: Any = None,
|
||||
raw_positions: list[dict[str, Any]] | None = None,
|
||||
) -> Optional[str]:
|
||||
"""若应拦截启动对冲计划,返回中文原因;否则 None."""
|
||||
if not mutual_exclusive_enabled():
|
||||
return None
|
||||
rows = raw_positions
|
||||
if rows is None:
|
||||
if fetch_positions is None or exchange is None:
|
||||
return None
|
||||
try:
|
||||
rows = fetch_positions(exchange) or []
|
||||
except Exception:
|
||||
return None
|
||||
try:
|
||||
if has_standalone_option_position(conn, rows):
|
||||
return "存在单独期权持仓,禁止启动对冲计划(可在 env「对冲与期权互斥门控」关闭)"
|
||||
except Exception:
|
||||
return None
|
||||
return None
|
||||
@@ -86,6 +86,227 @@ def floor_contracts_to_precision(contracts: float, decimals: int) -> float:
|
||||
return math.floor(raw * scale + 1e-12) / scale
|
||||
|
||||
|
||||
def option_unit_cost_usdc(*, ask: float, ct_mult: float) -> float:
|
||||
"""单张权利金(USDC) = 卖一价 × ct_mult."""
|
||||
a = _f(ask)
|
||||
if a is None or a <= 0:
|
||||
return 0.0
|
||||
return float(a) * float(ct_mult or 0.01)
|
||||
|
||||
|
||||
def resolve_oo_budget_usdc(
|
||||
*,
|
||||
trading_usdc: Any,
|
||||
trade_budget_usdc: Any,
|
||||
buffer_ratio: Any = 0.95,
|
||||
) -> dict[str, Any]:
|
||||
"""期期可用预算 = min(交易户×buffer, 单笔预算)."""
|
||||
import math
|
||||
|
||||
trading = _f(trading_usdc)
|
||||
cap = _f(trade_budget_usdc)
|
||||
buf = _f(buffer_ratio)
|
||||
if buf is None or buf <= 0:
|
||||
buf = 0.95
|
||||
if buf > 1:
|
||||
buf = 1.0
|
||||
trading_cap = None if trading is None else max(0.0, float(trading) * float(buf))
|
||||
trade_cap = None if cap is None else max(0.0, float(cap))
|
||||
if trading_cap is None and trade_cap is None:
|
||||
return {
|
||||
"ok": False,
|
||||
"budget_usdc": 0.0,
|
||||
"trading_cap": None,
|
||||
"trade_budget_cap": None,
|
||||
"buffer_ratio": float(buf),
|
||||
"msg": "缺少交易户余额与单笔预算",
|
||||
}
|
||||
if trading_cap is None:
|
||||
budget = float(trade_cap or 0.0)
|
||||
elif trade_cap is None:
|
||||
budget = float(trading_cap)
|
||||
else:
|
||||
budget = min(float(trading_cap), float(trade_cap))
|
||||
budget = float(math.floor(budget * 1e6 + 1e-12) / 1e6)
|
||||
return {
|
||||
"ok": budget > 0,
|
||||
"budget_usdc": budget,
|
||||
"trading_cap": None if trading_cap is None else round(float(trading_cap), 6),
|
||||
"trade_budget_cap": None if trade_cap is None else round(float(trade_cap), 6),
|
||||
"buffer_ratio": float(buf),
|
||||
"msg": "" if budget > 0 else "可用预算为 0",
|
||||
}
|
||||
|
||||
|
||||
def _cap_sheets_by_ask_depth(sheets: int, ask_sz: Any) -> int:
|
||||
import math
|
||||
|
||||
n = max(0, int(sheets))
|
||||
depth = _f(ask_sz)
|
||||
if depth is None:
|
||||
return n
|
||||
if depth <= 0:
|
||||
return 0
|
||||
return min(n, int(math.floor(float(depth) + 1e-12)))
|
||||
|
||||
|
||||
def _normalize_oo_sheets_mode(mode: str) -> str:
|
||||
m = (mode or "same_sheets").strip().lower()
|
||||
if m in ("long_bias", "bias_long", "long", "做多"):
|
||||
return "long_bias"
|
||||
if m in ("short_bias", "bias_short", "short", "做空"):
|
||||
return "short_bias"
|
||||
# 旧「均分」兼容:按预算 50/50(页面已移除)
|
||||
if m in ("split", "equal_budget", "split_budget", "均分"):
|
||||
return "split_budget"
|
||||
return "same_sheets"
|
||||
|
||||
|
||||
def _normalize_oo_bias_split_by(raw: Any) -> str:
|
||||
v = str(raw or "budget").strip().lower()
|
||||
if v in ("sheets", "qty", "quantity", "张数"):
|
||||
return "sheets"
|
||||
return "budget"
|
||||
|
||||
|
||||
def _clamp_oo_bias_ratio(raw: Any, default: float = 0.7) -> float:
|
||||
try:
|
||||
r = float(raw)
|
||||
except (TypeError, ValueError):
|
||||
r = float(default)
|
||||
if r <= 0 or r >= 1:
|
||||
r = float(default)
|
||||
return r
|
||||
|
||||
|
||||
def _oo_call_put_leg_index(opt_type_a: str, opt_type_b: str) -> tuple[Optional[str], Optional[str], str]:
|
||||
"""返回 (call_side, put_side, err);side 为 'a'/'b'."""
|
||||
a = (opt_type_a or "").strip().upper()
|
||||
b = (opt_type_b or "").strip().upper()
|
||||
if a.startswith("C"):
|
||||
a = "C"
|
||||
elif a.startswith("P"):
|
||||
a = "P"
|
||||
if b.startswith("C"):
|
||||
b = "C"
|
||||
elif b.startswith("P"):
|
||||
b = "P"
|
||||
if {a, b} != {"C", "P"}:
|
||||
return None, None, "做多/做空需一腿 Call、一腿 Put"
|
||||
call_side = "a" if a == "C" else "b"
|
||||
put_side = "b" if call_side == "a" else "a"
|
||||
return call_side, put_side, ""
|
||||
|
||||
|
||||
def suggest_oo_sheets(
|
||||
*,
|
||||
mode: str,
|
||||
budget_usdc: float,
|
||||
ask_a: float,
|
||||
ct_mult_a: float = 0.01,
|
||||
ask_sz_a: Any = None,
|
||||
opt_type_a: str = "",
|
||||
ask_b: float,
|
||||
ct_mult_b: float = 0.01,
|
||||
ask_sz_b: Any = None,
|
||||
opt_type_b: str = "",
|
||||
bias_split_by: str = "budget",
|
||||
bias_ratio: float = 0.7,
|
||||
) -> dict[str, Any]:
|
||||
"""期期建议张数:same_sheets / long_bias / short_bias(及旧 split_budget)."""
|
||||
import math
|
||||
|
||||
m = _normalize_oo_sheets_mode(mode)
|
||||
split_by = _normalize_oo_bias_split_by(bias_split_by)
|
||||
ratio = _clamp_oo_bias_ratio(bias_ratio)
|
||||
budget = max(0.0, float(budget_usdc or 0.0))
|
||||
cost_a = option_unit_cost_usdc(ask=ask_a, ct_mult=ct_mult_a)
|
||||
cost_b = option_unit_cost_usdc(ask=ask_b, ct_mult=ct_mult_b)
|
||||
|
||||
def _fail(msg: str, n_a: int = 0, n_b: int = 0) -> dict[str, Any]:
|
||||
return {
|
||||
"mode": m,
|
||||
"sheets_a": n_a,
|
||||
"sheets_b": n_b,
|
||||
"cost_a": round(cost_a, 8),
|
||||
"cost_b": round(cost_b, 8),
|
||||
"premium_est": round(cost_a * n_a + cost_b * n_b, 6),
|
||||
"ok": False,
|
||||
"msg": msg,
|
||||
"bias_split_by": split_by,
|
||||
"bias_ratio": ratio,
|
||||
}
|
||||
|
||||
if budget <= 0:
|
||||
return _fail("可用预算为 0")
|
||||
if cost_a <= 0 or cost_b <= 0:
|
||||
return _fail("缺少有效卖一价,无法建议张数")
|
||||
|
||||
pair = cost_a + cost_b
|
||||
n_pair = int(math.floor(budget / pair + 1e-12)) if pair > 0 else 0
|
||||
# 与同张数一致:先按预算得 n,再各自深度封顶后取 min
|
||||
n_same = min(
|
||||
_cap_sheets_by_ask_depth(n_pair, ask_sz_a),
|
||||
_cap_sheets_by_ask_depth(n_pair, ask_sz_b),
|
||||
)
|
||||
|
||||
if m == "same_sheets":
|
||||
n_a = n_same
|
||||
n_b = n_same
|
||||
elif m == "split_budget":
|
||||
half = budget / 2.0
|
||||
n_a = int(math.floor(half / cost_a + 1e-12))
|
||||
n_b = int(math.floor(half / cost_b + 1e-12))
|
||||
n_a = _cap_sheets_by_ask_depth(n_a, ask_sz_a)
|
||||
n_b = _cap_sheets_by_ask_depth(n_b, ask_sz_b)
|
||||
else:
|
||||
call_side, put_side, err = _oo_call_put_leg_index(opt_type_a, opt_type_b)
|
||||
if err:
|
||||
return _fail(err)
|
||||
major_is_call = m == "long_bias"
|
||||
if split_by == "sheets":
|
||||
# 总张数 = 同张数两侧合计(每腿 n → 共 2n),再按比例拆到 Call/Put
|
||||
total = int(n_same) * 2
|
||||
if total < 2:
|
||||
return _fail("同张数总规模不足 2,无法按比例拆分")
|
||||
major_n = int(round(total * ratio))
|
||||
major_n = max(1, min(major_n, total - 1))
|
||||
minor_n = total - major_n
|
||||
n_call = major_n if major_is_call else minor_n
|
||||
n_put = minor_n if major_is_call else major_n
|
||||
else:
|
||||
maj_budget = budget * ratio
|
||||
min_budget = budget * (1.0 - ratio)
|
||||
cost_call = cost_a if call_side == "a" else cost_b
|
||||
cost_put = cost_b if call_side == "a" else cost_a
|
||||
if major_is_call:
|
||||
n_call = int(math.floor(maj_budget / cost_call + 1e-12)) if cost_call > 0 else 0
|
||||
n_put = int(math.floor(min_budget / cost_put + 1e-12)) if cost_put > 0 else 0
|
||||
else:
|
||||
n_put = int(math.floor(maj_budget / cost_put + 1e-12)) if cost_put > 0 else 0
|
||||
n_call = int(math.floor(min_budget / cost_call + 1e-12)) if cost_call > 0 else 0
|
||||
n_a = n_call if call_side == "a" else n_put
|
||||
n_b = n_put if call_side == "a" else n_call
|
||||
n_a = _cap_sheets_by_ask_depth(n_a, ask_sz_a)
|
||||
n_b = _cap_sheets_by_ask_depth(n_b, ask_sz_b)
|
||||
|
||||
prem = cost_a * n_a + cost_b * n_b
|
||||
ok = n_a >= 1 and n_b >= 1
|
||||
msg = "" if ok else "预算不够开 1+1(或卖一深度不足)"
|
||||
return {
|
||||
"mode": m,
|
||||
"sheets_a": n_a,
|
||||
"sheets_b": n_b,
|
||||
"cost_a": round(cost_a, 8),
|
||||
"cost_b": round(cost_b, 8),
|
||||
"premium_est": round(prem, 6),
|
||||
"ok": ok,
|
||||
"msg": msg,
|
||||
"bias_split_by": split_by,
|
||||
"bias_ratio": ratio,
|
||||
}
|
||||
|
||||
|
||||
def build_perp_options_preview(
|
||||
*,
|
||||
direction: str,
|
||||
@@ -320,6 +541,10 @@ def build_options_options_preview(
|
||||
"expiry_flat_total": round(expiry_loss, 4),
|
||||
"premium_paid": round(prem, 6),
|
||||
"expiry_is_loss": flat_total <= 0,
|
||||
# 盈亏比:盈利/全亏保费(风险=权利金全损)
|
||||
"rr_risk_premium": round(prem, 6),
|
||||
"rr_at_up": round(at_up / prem, 4) if prem > 0 else None,
|
||||
"rr_at_down": round(at_dn / prem, 4) if prem > 0 else None,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -334,6 +559,10 @@ def gate_status(
|
||||
live_trading: bool = False,
|
||||
active_count: int = 0,
|
||||
max_active: int = 1,
|
||||
show_perp_options: bool = True,
|
||||
show_options_options: bool = True,
|
||||
mutual_exclusive: bool = True,
|
||||
has_standalone_option: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
from lib.trade.position_sizing_lib import is_full_margin_mode
|
||||
|
||||
@@ -349,12 +578,23 @@ def gate_status(
|
||||
can_preview = False
|
||||
can_start = False
|
||||
reasons.append("期权模块未启用")
|
||||
if pt == "perp_options" and not show_perp_options:
|
||||
can_preview = False
|
||||
can_start = False
|
||||
reasons.append("永期对冲已隐藏(HEDGE_PLAN_SHOW_PERP_OPTIONS)")
|
||||
if pt == "options_options" and not show_options_options:
|
||||
can_preview = False
|
||||
can_start = False
|
||||
reasons.append("期期对冲已隐藏(HEDGE_PLAN_SHOW_OPTIONS_OPTIONS)")
|
||||
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 mutual_exclusive and has_standalone_option:
|
||||
can_start = False
|
||||
reasons.append("存在单独期权持仓,禁止启动对冲计划(互斥门控)")
|
||||
if pt == "perp_options":
|
||||
if not full:
|
||||
can_start = False
|
||||
@@ -379,6 +619,10 @@ def gate_status(
|
||||
"live_trading": live_trading,
|
||||
"active_count": active_count,
|
||||
"max_active": max_active,
|
||||
"show_perp_options": bool(show_perp_options),
|
||||
"show_options_options": bool(show_options_options),
|
||||
"mutual_exclusive": bool(mutual_exclusive),
|
||||
"has_standalone_option": bool(has_standalone_option),
|
||||
"can_preview": can_preview,
|
||||
"can_start": can_start,
|
||||
"reasons": reasons,
|
||||
|
||||
@@ -72,6 +72,8 @@ def init_hedge_plan_tables(conn: sqlite3.Connection) -> None:
|
||||
)
|
||||
_ensure_column(conn, "hedge_plans", "target_price_up", "REAL")
|
||||
_ensure_column(conn, "hedge_plans", "target_price_down", "REAL")
|
||||
# close_all=盈利腿平后清残腿;hold_expiry=残腿持有至到期(现状)
|
||||
_ensure_column(conn, "hedge_plans", "oo_close_mode", "TEXT")
|
||||
|
||||
|
||||
def _ensure_column(conn: sqlite3.Connection, table: str, col: str, typedef: str) -> None:
|
||||
@@ -126,6 +128,22 @@ def update_plan(conn: sqlite3.Connection, plan_id: int, **fields: Any) -> None:
|
||||
conn.execute(f"UPDATE hedge_plans SET {sets} WHERE id=?", [*fields.values(), plan_id])
|
||||
|
||||
|
||||
def update_leg(conn: sqlite3.Connection, leg_id: int, **fields: Any) -> None:
|
||||
if not fields:
|
||||
return
|
||||
sets = ", ".join(f"{k}=?" for k in fields)
|
||||
conn.execute(f"UPDATE hedge_plan_legs SET {sets} WHERE id=?", [*fields.values(), int(leg_id)])
|
||||
|
||||
|
||||
def missing_leg_role(legs: list[dict[str, Any]]) -> Optional[str]:
|
||||
for leg in legs or []:
|
||||
if str(leg.get("status") or "").strip().lower() == "pending":
|
||||
role = str(leg.get("leg_role") or "").strip()
|
||||
if role:
|
||||
return role
|
||||
return None
|
||||
|
||||
|
||||
def list_plans(
|
||||
conn: sqlite3.Connection,
|
||||
*,
|
||||
@@ -182,15 +200,22 @@ def legs_contract_summary(legs: list[dict[str, Any]]) -> str:
|
||||
parts: list[str] = []
|
||||
for leg in legs:
|
||||
role = str(leg.get("leg_role") or "")
|
||||
st = str(leg.get("status") or "").strip().lower()
|
||||
if st == "pending":
|
||||
suffix = "(待补)"
|
||||
elif st in ("cancelled", "canceled"):
|
||||
suffix = "(未成交)"
|
||||
else:
|
||||
suffix = ""
|
||||
if role == "perp":
|
||||
name = str(leg.get("symbol") or "永续")
|
||||
parts.append(f"永续 {name}")
|
||||
parts.append(f"永续 {name}{suffix}")
|
||||
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)
|
||||
parts.append(f"{label}{suffix}")
|
||||
return " · ".join(parts) if parts else "—"
|
||||
|
||||
|
||||
@@ -201,6 +226,7 @@ def attach_legs_to_plans(conn: sqlite3.Connection, plans: list[dict[str, Any]])
|
||||
row = dict(p)
|
||||
row["legs"] = legs
|
||||
row["contracts_summary"] = legs_contract_summary(legs)
|
||||
row["missing_leg"] = missing_leg_role(legs)
|
||||
out.append(row)
|
||||
return out
|
||||
|
||||
|
||||
@@ -8,7 +8,11 @@ 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
|
||||
from lib.hedge_plan.hedge_plan_settle_lib import (
|
||||
leg_is_expired,
|
||||
resolve_option_leg_realized_pnl,
|
||||
settle_option_leg_at_spot,
|
||||
)
|
||||
|
||||
|
||||
def _now() -> str:
|
||||
@@ -69,6 +73,7 @@ def tick_active_plans(cfg: dict[str, Any]) -> dict[str, Any]:
|
||||
return {"ok": False, "msg": "get_db missing"}
|
||||
conn = get_db()
|
||||
acted: list[dict[str, Any]] = []
|
||||
backfill_stats: dict[str, int] = {}
|
||||
try:
|
||||
from lib.hedge_plan.hedge_plan_db import init_hedge_plan_tables
|
||||
|
||||
@@ -80,10 +85,22 @@ def tick_active_plans(cfg: dict[str, Any]) -> dict[str, Any]:
|
||||
acted.append(r)
|
||||
orphaned = _settle_orphaned_after_tp(cfg, conn)
|
||||
acted.extend(orphaned)
|
||||
try:
|
||||
ex = cfg.get("exchange_options")
|
||||
if ex is not None:
|
||||
from lib.exchange.okx_options_lib import fetch_all_option_positions_history
|
||||
from lib.hedge_plan.hedge_plan_settle_lib import (
|
||||
backfill_hedge_option_legs_realized_pnl,
|
||||
)
|
||||
|
||||
hist = fetch_all_option_positions_history(ex, limit=200)
|
||||
backfill_stats = backfill_hedge_option_legs_realized_pnl(conn, hist)
|
||||
except Exception:
|
||||
pass
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
return {"ok": True, "acted": acted}
|
||||
return {"ok": True, "acted": acted, "pnl_backfill": backfill_stats}
|
||||
|
||||
|
||||
def _notify_end_reload(cfg: dict[str, Any], conn: Any, plan_id: int) -> None:
|
||||
@@ -92,6 +109,55 @@ def _notify_end_reload(cfg: dict[str, Any], conn: Any, plan_id: int) -> None:
|
||||
notify_plan_end(cfg, conn, plan)
|
||||
|
||||
|
||||
def resolve_oo_rest_close_mode(plan: dict[str, Any]) -> str:
|
||||
"""盈利腿平后另一腿:close_all(全平) / hold_expiry(到期平).
|
||||
|
||||
- 方案C关闭 → 强制到期平
|
||||
- 计划未写 oo_close_mode(旧单) → 到期平,避免误清残腿
|
||||
- 新开仓默认写入 close_all
|
||||
"""
|
||||
if not _env_bool("HEDGE_PLAN_OO_CLOSE_MODE_ENABLED", True):
|
||||
return "hold_expiry"
|
||||
raw = plan.get("oo_close_mode")
|
||||
if raw is None or str(raw).strip() == "":
|
||||
return "hold_expiry"
|
||||
v = str(raw).strip().lower()
|
||||
if v in ("hold_expiry", "hold_to_expiry", "expiry", "到期平"):
|
||||
return "hold_expiry"
|
||||
return "close_all"
|
||||
|
||||
|
||||
def _oo_option_legs(legs: list[dict[str, Any]], *, statuses: tuple[str, ...]) -> list[dict[str, Any]]:
|
||||
out = []
|
||||
for x in legs:
|
||||
if not str(x.get("leg_role") or "").startswith("option"):
|
||||
continue
|
||||
if str(x.get("status") or "") in statuses:
|
||||
out.append(x)
|
||||
return out
|
||||
|
||||
|
||||
def _finalize_oo_all_closed(
|
||||
cfg: dict[str, Any], conn: Any, plan: dict[str, Any], legs: list[dict[str, Any]], *, reason: str
|
||||
) -> dict[str, Any]:
|
||||
closed_opts = _oo_option_legs(legs, statuses=("closed",))
|
||||
total_opts = sum(float(x.get("realized_pnl") or 0) for x in closed_opts)
|
||||
close_reason = reason or "oo_rest_closed"
|
||||
bucket = "oo_target" if total_opts > 0 else "oo_expiry_loss"
|
||||
update_plan(
|
||||
conn,
|
||||
int(plan["id"]),
|
||||
status="closed",
|
||||
close_reason=close_reason,
|
||||
realized_pnl_options=round(total_opts, 4),
|
||||
realized_pnl_total=round(total_opts, 4),
|
||||
stats_bucket=bucket,
|
||||
closed_at=_now(),
|
||||
)
|
||||
_notify_end_reload(cfg, conn, int(plan["id"]))
|
||||
return {"plan_id": plan["id"], "close_reason": close_reason, "total": total_opts}
|
||||
|
||||
|
||||
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"]))
|
||||
@@ -101,6 +167,9 @@ def _tick_one(cfg: dict[str, Any], conn: Any, plan: dict[str, Any]) -> Optional[
|
||||
return r
|
||||
if pt == "options_options":
|
||||
r = _tick_oo_expiry(cfg, conn, plan, legs)
|
||||
if r:
|
||||
return r
|
||||
r = _tick_oo_close_rest(cfg, conn, plan, legs)
|
||||
if r:
|
||||
return r
|
||||
return _tick_oo_target(cfg, conn, plan, legs)
|
||||
@@ -178,9 +247,10 @@ def _tick_po(cfg: dict[str, Any], conn: Any, plan: dict[str, Any], legs: list[di
|
||||
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
|
||||
est = (bid - ask_open) * float(opt.get("size") or 1) * ct
|
||||
else:
|
||||
opt_pnl = -premium
|
||||
est = -premium
|
||||
opt_pnl = _option_leg_pnl_after_close(cfg, opt, fallback=est)
|
||||
conn.execute(
|
||||
"UPDATE hedge_plan_legs SET status=?, close_reason=?, closed_at=?, realized_pnl=? WHERE id=?",
|
||||
("closed", reason, _now(), opt_pnl, opt["id"]),
|
||||
@@ -232,10 +302,101 @@ def _tick_po(cfg: dict[str, Any], conn: Any, plan: dict[str, Any], legs: list[di
|
||||
return {"plan_id": plan["id"], "close_reason": reason, "total": total}
|
||||
|
||||
|
||||
def _option_leg_pnl_after_close(
|
||||
cfg: dict[str, Any],
|
||||
leg: dict[str, Any],
|
||||
*,
|
||||
fallback: float,
|
||||
) -> float:
|
||||
"""平仓后写腿盈亏:优先交易所历史,否则用估算."""
|
||||
ex = cfg.get("exchange_options")
|
||||
pnl, _src = resolve_option_leg_realized_pnl(ex=ex, leg=leg, fallback=fallback)
|
||||
return float(pnl if pnl is not None else fallback)
|
||||
|
||||
|
||||
def _estimate_leg_close_pnl(leg: dict[str, Any], idx: Optional[float], bid: Optional[float]) -> float:
|
||||
"""残腿平仓盈亏估算:优先买一回收 − 权利金;无买一则用内在价值."""
|
||||
premium = float(leg.get("premium") or 0)
|
||||
sheets = float(leg.get("size") or 1)
|
||||
ct = float(leg.get("ct_mult") or 0.01)
|
||||
if bid is not None and float(bid) > 0:
|
||||
return float(bid) * sheets * ct - premium
|
||||
if idx is None:
|
||||
return -premium
|
||||
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)
|
||||
return intrinsic * sheets * ct - premium
|
||||
|
||||
|
||||
def _tick_oo_close_rest(
|
||||
cfg: dict[str, Any], conn: Any, plan: dict[str, Any], legs: list[dict[str, Any]]
|
||||
) -> Optional[dict[str, Any]]:
|
||||
"""盈利腿已平后:全平模式清残腿(无2×门控,买一失败则下轮重试)."""
|
||||
if resolve_oo_rest_close_mode(plan) != "close_all":
|
||||
return None
|
||||
open_legs = _oo_option_legs(legs, statuses=("open",))
|
||||
closed_legs = _oo_option_legs(legs, statuses=("closed",))
|
||||
# 至少已平一条,且仍有残腿;避免双腿都还 open 时误清
|
||||
if len(closed_legs) < 1 or len(open_legs) < 1:
|
||||
return None
|
||||
reason0 = str(plan.get("close_reason") or "")
|
||||
allowed_reasons = (
|
||||
"target_win_leg",
|
||||
"target_up_win_leg",
|
||||
"target_down_win_leg",
|
||||
"oo_rest_closing",
|
||||
"",
|
||||
)
|
||||
if reason0 not in allowed_reasons and not (
|
||||
len(closed_legs) >= 1 and len(open_legs) == 1
|
||||
):
|
||||
return None
|
||||
|
||||
idx = _index_px(cfg, str(plan.get("underlying") or "ETH"))
|
||||
acted = False
|
||||
for leg in list(open_legs):
|
||||
close_r = _sell_option(
|
||||
cfg, inst_id=str(leg.get("inst_id") or ""), sheets=float(leg.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),
|
||||
),
|
||||
)
|
||||
update_plan(conn, int(plan["id"]), close_reason="oo_rest_closing")
|
||||
return {"plan_id": plan["id"], "msg": "残腿平仓失败", "close": close_r, "retry": True}
|
||||
bid = _sf(close_r.get("bid"))
|
||||
est = _estimate_leg_close_pnl(leg, idx, bid)
|
||||
pnl = _option_leg_pnl_after_close(cfg, leg, fallback=est)
|
||||
conn.execute(
|
||||
"UPDATE hedge_plan_legs SET status=?, close_reason=?, closed_at=?, realized_pnl=? WHERE id=?",
|
||||
("closed", "oo_rest_close", _now(), round(pnl, 4), leg["id"]),
|
||||
)
|
||||
leg["status"] = "closed"
|
||||
leg["realized_pnl"] = round(pnl, 4)
|
||||
acted = True
|
||||
|
||||
if not acted:
|
||||
return None
|
||||
legs2 = get_plan_legs(conn, int(plan["id"]))
|
||||
still_open = _oo_option_legs(legs2, statuses=("open", "hold_to_expiry"))
|
||||
if still_open:
|
||||
update_plan(conn, int(plan["id"]), close_reason="oo_rest_closing")
|
||||
return {"plan_id": plan["id"], "msg": "残腿部分已平,继续重试", "remaining": len(still_open)}
|
||||
return _finalize_oo_all_closed(
|
||||
cfg, conn, plan, legs2, reason="oo_rest_closed"
|
||||
)
|
||||
|
||||
|
||||
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
|
||||
@@ -261,7 +422,7 @@ def _tick_oo_target(
|
||||
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")]
|
||||
open_legs = _oo_option_legs(legs, statuses=("open",))
|
||||
if len(open_legs) < 2:
|
||||
return None
|
||||
winners = []
|
||||
@@ -288,21 +449,51 @@ def _tick_oo_target(
|
||||
)
|
||||
return {"plan_id": plan["id"], "msg": "平盈利腿失败", "close": close_r}
|
||||
reason = "target_up_win_leg" if hit_side == "up" else "target_down_win_leg"
|
||||
# 选腿用内在估算;落库优先交易所已实现盈亏
|
||||
closed_pnl = _option_leg_pnl_after_close(cfg, best, fallback=float(best_pnl))
|
||||
conn.execute(
|
||||
"UPDATE hedge_plan_legs SET status=?, close_reason=?, closed_at=?, realized_pnl=? WHERE id=?",
|
||||
("closed", reason, _now(), best_pnl, best["id"]),
|
||||
("closed", reason, _now(), closed_pnl, best["id"]),
|
||||
)
|
||||
rest_mode = resolve_oo_rest_close_mode(plan)
|
||||
update_plan(conn, int(plan["id"]), close_reason=reason)
|
||||
mid = dict(plan)
|
||||
mid["close_reason"] = reason
|
||||
mid["status"] = "active"
|
||||
mid["oo_close_mode"] = rest_mode
|
||||
notify_plan_end(cfg, conn, mid)
|
||||
|
||||
# 全平:同轮尝试清残腿;失败则下轮 _tick_oo_close_rest 重试
|
||||
if rest_mode == "close_all":
|
||||
legs2 = get_plan_legs(conn, int(plan["id"]))
|
||||
rest = _tick_oo_close_rest(cfg, conn, mid, legs2)
|
||||
out = {
|
||||
"plan_id": plan["id"],
|
||||
"close_reason": reason,
|
||||
"hit_side": hit_side,
|
||||
"closed_leg": best.get("id"),
|
||||
"index": idx,
|
||||
"oo_close_mode": rest_mode,
|
||||
}
|
||||
if rest:
|
||||
out["rest"] = rest
|
||||
return out
|
||||
|
||||
# 到期平:显式标记残腿 hold_to_expiry
|
||||
for leg in open_legs:
|
||||
if int(leg.get("id") or 0) == int(best.get("id") or 0):
|
||||
continue
|
||||
conn.execute(
|
||||
"UPDATE hedge_plan_legs SET status=? WHERE id=?",
|
||||
("hold_to_expiry", leg["id"]),
|
||||
)
|
||||
return {
|
||||
"plan_id": plan["id"],
|
||||
"close_reason": reason,
|
||||
"hit_side": hit_side,
|
||||
"closed_leg": best.get("id"),
|
||||
"index": idx,
|
||||
"oo_close_mode": rest_mode,
|
||||
}
|
||||
|
||||
|
||||
@@ -347,7 +538,8 @@ def _tick_oo_expiry(
|
||||
|
||||
settled_sum = 0.0
|
||||
for leg in pending:
|
||||
pnl = settle_option_leg_at_spot(leg, float(spot))
|
||||
est = settle_option_leg_at_spot(leg, float(spot))
|
||||
pnl = _option_leg_pnl_after_close(cfg, leg, fallback=est)
|
||||
settled_sum += pnl
|
||||
conn.execute(
|
||||
"UPDATE hedge_plan_legs SET status=?, close_reason=?, closed_at=?, realized_pnl=? WHERE id=?",
|
||||
@@ -396,7 +588,11 @@ def _settle_orphaned_after_tp(cfg: dict[str, Any], conn: Any) -> list[dict[str,
|
||||
spot = _index_px(cfg, str(leg.get("underlying") or "ETH"))
|
||||
if spot is None:
|
||||
continue
|
||||
pnl = settle_option_leg_at_spot(leg, float(spot))
|
||||
pnl_est = settle_option_leg_at_spot(leg, float(spot))
|
||||
# orphan row uses leg_id; map to id for resolver
|
||||
leg_for_pnl = dict(leg)
|
||||
leg_for_pnl["id"] = leg.get("leg_id")
|
||||
pnl = _option_leg_pnl_after_close(cfg, leg_for_pnl, fallback=pnl_est)
|
||||
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"]),
|
||||
|
||||
@@ -81,6 +81,8 @@ def build_hedge_end_message(plan: dict[str, Any]) -> str:
|
||||
"target_win_leg": "期期已平盈利腿(中间态)",
|
||||
"target_up_win_leg": "期期上破·已平盈利腿",
|
||||
"target_down_win_leg": "期期下破·已平盈利腿",
|
||||
"oo_rest_closing": "期期全平·清残腿中",
|
||||
"oo_rest_closed": "期期全平·两腿已平",
|
||||
"oo_expiry_loss": "期期到期无盈利·总亏损",
|
||||
"oo_expiry_win": "期期到期仍盈利",
|
||||
"expiry": "到期收口",
|
||||
@@ -150,14 +152,20 @@ def notify_plan_end(cfg: dict[str, Any], conn: Any, plan: dict[str, Any]) -> boo
|
||||
"target_win_leg",
|
||||
"target_up_win_leg",
|
||||
"target_down_win_leg",
|
||||
"oo_rest_closing",
|
||||
) 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 "目标价"
|
||||
)
|
||||
mode = (plan.get("oo_close_mode") or "").strip().lower()
|
||||
if mode in ("close_all", "全平"):
|
||||
rest_txt = "另一腿将全平(买一清残腿,无2×门控,失败重试)"
|
||||
else:
|
||||
rest_txt = "另一腿到期平(持有至到期结算)"
|
||||
notify_hedge(
|
||||
cfg,
|
||||
build_hedge_alert_message(
|
||||
title=f"期期{side}已平盈利腿,亏损腿继续持有至到期",
|
||||
title=f"期期{side}已平盈利腿 · {rest_txt}",
|
||||
plan_id=plan.get("id"),
|
||||
detail=(
|
||||
f"上破 {_fmt(plan.get('target_price_up') or plan.get('target_price'))}"
|
||||
|
||||
@@ -23,6 +23,18 @@ def open_order_mode() -> str:
|
||||
return v if v in ("options_first", "perp_first") else "options_first"
|
||||
|
||||
|
||||
def manual_complete_on_partial() -> bool:
|
||||
"""半腿失败后挂 partial 并手动补开(默认 true)."""
|
||||
return _env_bool("HEDGE_PLAN_MANUAL_COMPLETE_ON_PARTIAL", True)
|
||||
|
||||
|
||||
def partial_auto_close_enabled() -> bool:
|
||||
"""手动补开开启时强制关闭自动平,避免吃买卖价差."""
|
||||
if manual_complete_on_partial():
|
||||
return False
|
||||
return _env_bool("HEDGE_PLAN_PARTIAL_AUTO_CLOSE_OPTION", True)
|
||||
|
||||
|
||||
def build_po_path_plan(body: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
"""永期下单路径清单(不交易)."""
|
||||
mode = open_order_mode()
|
||||
@@ -70,6 +82,13 @@ def build_oo_path_plan(body: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
]
|
||||
|
||||
|
||||
def _option_open_fill_timeout_sec() -> float:
|
||||
try:
|
||||
return max(2.0, float(os.getenv("OKX_OPTIONS_OPEN_FILL_TIMEOUT_SEC") or "12"))
|
||||
except (TypeError, ValueError):
|
||||
return 12.0
|
||||
|
||||
|
||||
def _buy_option(
|
||||
cfg: dict[str, Any],
|
||||
*,
|
||||
@@ -80,6 +99,7 @@ def _buy_option(
|
||||
from lib.exchange.okx_options_lib import (
|
||||
cap_option_buy_sheets_to_ask_depth,
|
||||
option_buy_liquidity_ok,
|
||||
wait_option_order_full_fill,
|
||||
)
|
||||
|
||||
ex = cfg.get("exchange_options")
|
||||
@@ -134,6 +154,7 @@ def _buy_option(
|
||||
td = "isolated"
|
||||
if callable(td_buy):
|
||||
td = td_buy(cfg.get("options_td_mode") or "isolated")
|
||||
# IOC:能成交多少成交多少,剩余立即撤销;再校验是否完全成交
|
||||
order = place_fn(
|
||||
ex,
|
||||
inst_id=inst_id,
|
||||
@@ -142,14 +163,42 @@ def _buy_option(
|
||||
price=float(ask),
|
||||
td_mode=td,
|
||||
tick_sz=q.get("tick_sz"),
|
||||
ord_type="ioc",
|
||||
)
|
||||
if not order.get("ok"):
|
||||
return order
|
||||
ord_id = str((order.get("data") or {}).get("ordId") or "").strip()
|
||||
if not ord_id:
|
||||
return {"ok": False, "msg": "下单成功但未返回订单号", "order": order}
|
||||
fill = wait_option_order_full_fill(
|
||||
ex,
|
||||
inst_id=inst_id,
|
||||
ord_id=ord_id,
|
||||
need_sheets=sheets_i,
|
||||
timeout_sec=_option_open_fill_timeout_sec(),
|
||||
cancel_on_timeout=True,
|
||||
)
|
||||
if not fill.get("ok"):
|
||||
return {
|
||||
"ok": False,
|
||||
"msg": fill.get("msg") or "未完全成交,开仓失败",
|
||||
"inst_id": inst_id,
|
||||
"sheets": sheets_i,
|
||||
"ask": float(ask),
|
||||
"exchange_ord_id": ord_id,
|
||||
"filled_sheets": fill.get("filled_sheets"),
|
||||
"order": order,
|
||||
"fill": fill,
|
||||
"can_open": False,
|
||||
}
|
||||
fill_px = float(fill.get("avg_px") or ask)
|
||||
filled_n = int(fill.get("filled_sheets") or sheets_i)
|
||||
premium = fill_px * filled_n * ct_mult
|
||||
return {
|
||||
"ok": True,
|
||||
"inst_id": inst_id,
|
||||
"sheets": sheets_i,
|
||||
"ask": float(ask),
|
||||
"sheets": filled_n,
|
||||
"ask": fill_px,
|
||||
"ask_sz": float(ask_sz),
|
||||
"premium": premium,
|
||||
"ct_mult": ct_mult,
|
||||
@@ -158,8 +207,9 @@ def _buy_option(
|
||||
"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"),
|
||||
"exchange_ord_id": ord_id,
|
||||
"order": order,
|
||||
"fill": fill,
|
||||
"can_open": True,
|
||||
}
|
||||
|
||||
@@ -257,6 +307,244 @@ def _sell_option(
|
||||
return order if order.get("ok") else order
|
||||
|
||||
|
||||
def _notify_partial(cfg: dict[str, Any], plan_type: str, msg: str, results: list[dict[str, Any]]) -> None:
|
||||
try:
|
||||
from lib.hedge_plan.hedge_plan_notify_lib import notify_partial_fail
|
||||
|
||||
notify_partial_fail(cfg, plan_type=plan_type, msg=msg, results=results)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _park_partial(
|
||||
cfg: dict[str, Any],
|
||||
*,
|
||||
plan_type: str,
|
||||
body: dict[str, Any],
|
||||
missing_leg: str,
|
||||
msg: str,
|
||||
path: list[dict[str, Any]],
|
||||
results: list[dict[str, Any]],
|
||||
persist: Optional[Callable[..., Any]],
|
||||
dry_run: bool,
|
||||
**filled: Any,
|
||||
) -> dict[str, Any]:
|
||||
"""半腿失败:保留已成腿,挂 partial 供手动补开."""
|
||||
if not dry_run:
|
||||
_notify_partial(cfg, plan_type, msg, results)
|
||||
out: dict[str, Any] = {
|
||||
"ok": True,
|
||||
"partial": True,
|
||||
"status": "partial",
|
||||
"dry_run": dry_run,
|
||||
"plan_type": plan_type,
|
||||
"missing_leg": missing_leg,
|
||||
"msg": msg,
|
||||
"path": path,
|
||||
"results": results,
|
||||
"opened_at": _now(),
|
||||
**filled,
|
||||
}
|
||||
if persist and not dry_run:
|
||||
out["plan_id"] = persist(out, body)
|
||||
return out
|
||||
|
||||
|
||||
def _hedge_budget_buffer(cfg: dict[str, Any] | None = None) -> float:
|
||||
"""对冲专用预算缓冲;默认 0.95.与 OKX_OPTIONS_BUDGET_BUFFER 独立."""
|
||||
raw = None
|
||||
if cfg is not None:
|
||||
raw = cfg.get("budget_buffer")
|
||||
if raw is None or raw == "":
|
||||
raw = os.getenv("HEDGE_PLAN_BUDGET_BUFFER") or "0.95"
|
||||
try:
|
||||
buf = float(raw)
|
||||
except (TypeError, ValueError):
|
||||
buf = 0.95
|
||||
if buf <= 0:
|
||||
buf = 0.95
|
||||
if buf > 1:
|
||||
buf = 1.0
|
||||
return float(buf)
|
||||
|
||||
|
||||
def _oo_bias_settings(cfg: dict[str, Any] | None = None) -> tuple[str, float]:
|
||||
from lib.hedge_plan.hedge_plan_calc_lib import _clamp_oo_bias_ratio, _normalize_oo_bias_split_by
|
||||
|
||||
split = None
|
||||
ratio = None
|
||||
if cfg is not None:
|
||||
split = cfg.get("oo_bias_split_by")
|
||||
ratio = cfg.get("oo_bias_ratio")
|
||||
if split in (None, ""):
|
||||
split = os.getenv("HEDGE_PLAN_OO_BIAS_SPLIT_BY") or "budget"
|
||||
if ratio in (None, ""):
|
||||
ratio = os.getenv("HEDGE_PLAN_OO_BIAS_RATIO") or "0.7"
|
||||
return _normalize_oo_bias_split_by(split), _clamp_oo_bias_ratio(ratio)
|
||||
|
||||
|
||||
def refresh_oo_sizing_before_start(cfg: dict[str, Any], body: dict[str, Any]) -> dict[str, Any]:
|
||||
"""启动前再拉两腿卖一,按对冲预算缓冲重算张数;就地写回 body.leg_*.
|
||||
|
||||
方案 A:成交价与张数均基于点击启动瞬间的最新卖一/余额.
|
||||
"""
|
||||
from lib.exchange.okx_options_lib import fetch_options_trading_usdc, option_buy_liquidity_ok
|
||||
from lib.hedge_plan.hedge_plan_calc_lib import resolve_oo_budget_usdc, suggest_oo_sheets
|
||||
|
||||
leg_a = dict(body.get("leg_a") or {})
|
||||
leg_b = dict(body.get("leg_b") or {})
|
||||
inst_a = str(leg_a.get("inst_id") or "").strip()
|
||||
inst_b = str(leg_b.get("inst_id") or "").strip()
|
||||
if not inst_a or not inst_b:
|
||||
return {"ok": False, "msg": "缺少期权合约"}
|
||||
quote_fn = cfg.get("quote_option_contract")
|
||||
ex = cfg.get("exchange_options")
|
||||
if not callable(quote_fn) or ex is None:
|
||||
return {"ok": False, "msg": "期权报价能力未就绪"}
|
||||
|
||||
qa = quote_fn(ex, inst_a)
|
||||
if not qa.get("ok"):
|
||||
return {"ok": False, "msg": qa.get("msg") or "腿A报价失败", "quote_a": qa}
|
||||
qb = quote_fn(ex, inst_b)
|
||||
if not qb.get("ok"):
|
||||
return {"ok": False, "msg": qb.get("msg") or "腿B报价失败", "quote_b": qb}
|
||||
|
||||
for tag, q in (("A", qa), ("B", qb)):
|
||||
can_open, block_msg = option_buy_liquidity_ok(q.get("ask"), q.get("ask_sz"))
|
||||
if not can_open:
|
||||
return {
|
||||
"ok": False,
|
||||
"msg": f"腿{tag}: {block_msg or '暂无卖一深度,无法买入'}",
|
||||
"quote_a": qa,
|
||||
"quote_b": qb,
|
||||
}
|
||||
|
||||
trading = fetch_options_trading_usdc(ex)
|
||||
buf = _hedge_budget_buffer(cfg)
|
||||
budget_info = resolve_oo_budget_usdc(
|
||||
trading_usdc=trading,
|
||||
trade_budget_usdc=cfg.get("trade_budget_usdc"),
|
||||
buffer_ratio=buf,
|
||||
)
|
||||
if not budget_info.get("ok"):
|
||||
return {
|
||||
"ok": False,
|
||||
"msg": budget_info.get("msg") or "可用预算不足",
|
||||
"budget": budget_info,
|
||||
"quote_a": qa,
|
||||
"quote_b": qb,
|
||||
}
|
||||
|
||||
mode = str(body.get("oo_sheets_mode") or "same_sheets")
|
||||
split_by, bias_ratio = _oo_bias_settings(cfg)
|
||||
opt_a = str(
|
||||
leg_a.get("opt_type")
|
||||
or (qa.get("meta") or {}).get("optType")
|
||||
or qa.get("opt_type")
|
||||
or ""
|
||||
)
|
||||
opt_b = str(
|
||||
leg_b.get("opt_type")
|
||||
or (qb.get("meta") or {}).get("optType")
|
||||
or qb.get("opt_type")
|
||||
or ""
|
||||
)
|
||||
sug = suggest_oo_sheets(
|
||||
mode=mode,
|
||||
budget_usdc=float(budget_info["budget_usdc"]),
|
||||
ask_a=float(qa["ask"]),
|
||||
ct_mult_a=float(qa.get("ct_mult") or leg_a.get("ct_mult") or 0.01),
|
||||
ask_sz_a=qa.get("ask_sz"),
|
||||
opt_type_a=opt_a,
|
||||
ask_b=float(qb["ask"]),
|
||||
ct_mult_b=float(qb.get("ct_mult") or leg_b.get("ct_mult") or 0.01),
|
||||
ask_sz_b=qb.get("ask_sz"),
|
||||
opt_type_b=opt_b,
|
||||
bias_split_by=split_by,
|
||||
bias_ratio=bias_ratio,
|
||||
)
|
||||
if not sug.get("ok"):
|
||||
return {
|
||||
"ok": False,
|
||||
"msg": sug.get("msg") or "按最新卖一无法建议张数",
|
||||
"sizing": sug,
|
||||
"budget": budget_info,
|
||||
"quote_a": qa,
|
||||
"quote_b": qb,
|
||||
}
|
||||
|
||||
prev_a = leg_a.get("sheets")
|
||||
prev_b = leg_b.get("sheets")
|
||||
leg_a["sheets"] = int(sug["sheets_a"])
|
||||
leg_a["ask"] = float(qa["ask"])
|
||||
leg_a["ask_sz"] = qa.get("ask_sz")
|
||||
leg_a["ct_mult"] = float(qa.get("ct_mult") or leg_a.get("ct_mult") or 0.01)
|
||||
if opt_a:
|
||||
leg_a["opt_type"] = opt_a
|
||||
leg_b["sheets"] = int(sug["sheets_b"])
|
||||
leg_b["ask"] = float(qb["ask"])
|
||||
leg_b["ask_sz"] = qb.get("ask_sz")
|
||||
leg_b["ct_mult"] = float(qb.get("ct_mult") or leg_b.get("ct_mult") or 0.01)
|
||||
if opt_b:
|
||||
leg_b["opt_type"] = opt_b
|
||||
body["leg_a"] = leg_a
|
||||
body["leg_b"] = leg_b
|
||||
return {
|
||||
"ok": True,
|
||||
"buffer_ratio": buf,
|
||||
"budget": budget_info,
|
||||
"sizing": sug,
|
||||
"quote_a": qa,
|
||||
"quote_b": qb,
|
||||
"prev_sheets_a": prev_a,
|
||||
"prev_sheets_b": prev_b,
|
||||
"sheets_a": int(sug["sheets_a"]),
|
||||
"sheets_b": int(sug["sheets_b"]),
|
||||
"ask_a": float(qa["ask"]),
|
||||
"ask_b": float(qb["ask"]),
|
||||
"premium_est": sug.get("premium_est"),
|
||||
"msg": (
|
||||
f"已按最新卖一重算: A {sug['sheets_a']}张@{qa['ask']} + "
|
||||
f"B {sug['sheets_b']}张@{qb['ask']} · 预估 {sug.get('premium_est')}U"
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def refresh_po_option_quote_before_start(cfg: dict[str, Any], body: dict[str, Any]) -> dict[str, Any]:
|
||||
"""永期启动前再拉保险腿卖一(张数沿用页面值,不按预算重算)."""
|
||||
from lib.exchange.okx_options_lib import option_buy_liquidity_ok
|
||||
|
||||
inst = str(body.get("opt_inst_id") or "").strip()
|
||||
if not inst:
|
||||
return {"ok": False, "msg": "缺少期权合约"}
|
||||
quote_fn = cfg.get("quote_option_contract")
|
||||
ex = cfg.get("exchange_options")
|
||||
if not callable(quote_fn) or ex is None:
|
||||
return {"ok": False, "msg": "期权报价能力未就绪"}
|
||||
q = quote_fn(ex, inst)
|
||||
if not q.get("ok"):
|
||||
return {"ok": False, "msg": q.get("msg") or "期权报价失败", "quote": q}
|
||||
can_open, block_msg = option_buy_liquidity_ok(q.get("ask"), q.get("ask_sz"))
|
||||
if not can_open:
|
||||
return {
|
||||
"ok": False,
|
||||
"msg": block_msg or "暂无卖一深度,无法买入",
|
||||
"quote": q,
|
||||
}
|
||||
body["ask"] = float(q["ask"])
|
||||
body["ask_sz"] = q.get("ask_sz")
|
||||
if q.get("ct_mult") is not None:
|
||||
body["ct_mult"] = float(q.get("ct_mult") or 0.01)
|
||||
return {
|
||||
"ok": True,
|
||||
"ask": float(q["ask"]),
|
||||
"ask_sz": q.get("ask_sz"),
|
||||
"sheets": body.get("sheets"),
|
||||
"quote": q,
|
||||
"msg": f"已按最新卖一: {body.get('sheets')}张@{q['ask']}",
|
||||
}
|
||||
|
||||
|
||||
def execute_perp_options_start(
|
||||
cfg: dict[str, Any],
|
||||
body: dict[str, Any],
|
||||
@@ -264,6 +552,9 @@ def execute_perp_options_start(
|
||||
dry_run: bool = False,
|
||||
persist: Optional[Callable[..., Any]] = None,
|
||||
) -> dict[str, Any]:
|
||||
refresh = refresh_po_option_quote_before_start(cfg, body)
|
||||
if not refresh.get("ok"):
|
||||
return {"ok": False, "msg": refresh.get("msg") or "启动前刷新卖一失败", "refresh": refresh}
|
||||
path = build_po_path_plan(body)
|
||||
results: list[dict[str, Any]] = []
|
||||
opt_res: Optional[dict[str, Any]] = None
|
||||
@@ -278,6 +569,27 @@ def execute_perp_options_start(
|
||||
)
|
||||
results.append({"step": step["step"], **opt_res})
|
||||
if not opt_res.get("ok"):
|
||||
# 永续已成、期权失败 → 可挂 partial 等补开期权
|
||||
if (
|
||||
perp_res
|
||||
and perp_res.get("ok")
|
||||
and not dry_run
|
||||
and manual_complete_on_partial()
|
||||
and persist
|
||||
):
|
||||
return _park_partial(
|
||||
cfg,
|
||||
plan_type="perp_options",
|
||||
body=body,
|
||||
missing_leg="option_hedge",
|
||||
msg="永续已开、期权失败。计划已挂半腿待补,请在「进行中」补开期权",
|
||||
path=path,
|
||||
results=results,
|
||||
persist=persist,
|
||||
dry_run=dry_run,
|
||||
option=None,
|
||||
perp=perp_res,
|
||||
)
|
||||
return {"ok": False, "msg": opt_res.get("msg") or "期权开仓失败", "path": path, "results": results}
|
||||
else:
|
||||
perp_res = _open_perp(
|
||||
@@ -292,24 +604,45 @@ def execute_perp_options_start(
|
||||
)
|
||||
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):
|
||||
if opt_res and opt_res.get("ok") and not dry_run and partial_auto_close_enabled():
|
||||
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 "永续开仓失败"
|
||||
_notify_partial(cfg, "perp_options", msg, results)
|
||||
return {
|
||||
"ok": False,
|
||||
"msg": msg,
|
||||
"path": path,
|
||||
"results": results,
|
||||
"partial": True,
|
||||
}
|
||||
if (
|
||||
opt_res
|
||||
and opt_res.get("ok")
|
||||
and not dry_run
|
||||
and manual_complete_on_partial()
|
||||
and persist
|
||||
):
|
||||
return _park_partial(
|
||||
cfg,
|
||||
plan_type="perp_options",
|
||||
body=body,
|
||||
missing_leg="perp",
|
||||
msg="期权已开、永续失败。计划已挂半腿待补,请在「进行中」补开永续",
|
||||
path=path,
|
||||
results=results,
|
||||
persist=persist,
|
||||
dry_run=dry_run,
|
||||
option=opt_res,
|
||||
perp=None,
|
||||
)
|
||||
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
|
||||
_notify_partial(cfg, "perp_options", msg, results)
|
||||
return {
|
||||
"ok": False,
|
||||
"msg": msg,
|
||||
@@ -326,6 +659,7 @@ def execute_perp_options_start(
|
||||
"results": results,
|
||||
"option": opt_res,
|
||||
"perp": perp_res,
|
||||
"refresh": refresh,
|
||||
"opened_at": _now(),
|
||||
}
|
||||
if persist and not dry_run:
|
||||
@@ -340,6 +674,9 @@ def execute_options_options_start(
|
||||
dry_run: bool = False,
|
||||
persist: Optional[Callable[..., Any]] = None,
|
||||
) -> dict[str, Any]:
|
||||
refresh = refresh_oo_sizing_before_start(cfg, body)
|
||||
if not refresh.get("ok"):
|
||||
return {"ok": False, "msg": refresh.get("msg") or "启动前刷新卖一/张数失败", "refresh": refresh}
|
||||
path = build_oo_path_plan(body)
|
||||
results: list[dict[str, Any]] = []
|
||||
leg_a = body.get("leg_a") or {}
|
||||
@@ -347,27 +684,55 @@ def execute_options_options_start(
|
||||
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}
|
||||
return {
|
||||
"ok": False,
|
||||
"msg": a_res.get("msg") or "腿A开仓失败",
|
||||
"path": path,
|
||||
"results": results,
|
||||
"refresh": refresh,
|
||||
}
|
||||
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):
|
||||
if not dry_run and partial_auto_close_enabled():
|
||||
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开仓失败"
|
||||
_notify_partial(cfg, "options_options", msg, results)
|
||||
return {
|
||||
"ok": False,
|
||||
"msg": msg,
|
||||
"path": path,
|
||||
"results": results,
|
||||
"partial": True,
|
||||
"refresh": refresh,
|
||||
}
|
||||
if not dry_run and manual_complete_on_partial() and persist:
|
||||
out_p = _park_partial(
|
||||
cfg,
|
||||
plan_type="options_options",
|
||||
body=body,
|
||||
missing_leg="option_b",
|
||||
msg="腿A已开、腿B失败。计划已挂半腿待补,请在「进行中」补开腿B",
|
||||
path=path,
|
||||
results=results,
|
||||
persist=persist,
|
||||
dry_run=dry_run,
|
||||
leg_a=a_res,
|
||||
leg_b=None,
|
||||
)
|
||||
out_p["refresh"] = refresh
|
||||
return out_p
|
||||
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
|
||||
_notify_partial(cfg, "options_options", msg, results)
|
||||
return {
|
||||
"ok": False,
|
||||
"msg": msg,
|
||||
"path": path,
|
||||
"results": results,
|
||||
"partial": True,
|
||||
"refresh": refresh,
|
||||
}
|
||||
out = {
|
||||
"ok": True,
|
||||
@@ -377,6 +742,7 @@ def execute_options_options_start(
|
||||
"results": results,
|
||||
"leg_a": a_res,
|
||||
"leg_b": b_res,
|
||||
"refresh": refresh,
|
||||
"opened_at": _now(),
|
||||
}
|
||||
if persist and not dry_run:
|
||||
@@ -384,6 +750,73 @@ def execute_options_options_start(
|
||||
return out
|
||||
|
||||
|
||||
def execute_complete_missing_leg(
|
||||
cfg: dict[str, Any],
|
||||
plan: dict[str, Any],
|
||||
legs: list[dict[str, Any]],
|
||||
start_body: dict[str, Any],
|
||||
*,
|
||||
dry_run: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""对 partial 计划补开缺失腿;成功后由调用方把计划升为 active."""
|
||||
missing = None
|
||||
for leg in legs:
|
||||
if str(leg.get("status") or "").lower() == "pending":
|
||||
missing = leg
|
||||
break
|
||||
if not missing:
|
||||
return {"ok": False, "msg": "没有待补开的腿"}
|
||||
role = str(missing.get("leg_role") or "")
|
||||
results: list[dict[str, Any]] = []
|
||||
if role == "perp":
|
||||
res = _open_perp(
|
||||
cfg,
|
||||
symbol=str(start_body.get("exchange_symbol") or missing.get("symbol") or ""),
|
||||
direction=str(start_body.get("direction") or "long"),
|
||||
contracts=float(start_body.get("contracts") or missing.get("size") or 0),
|
||||
leverage=int(start_body.get("leverage") or 10),
|
||||
tp=float(start_body["tp"]),
|
||||
sl=float(start_body["sl"]),
|
||||
dry_run=dry_run,
|
||||
)
|
||||
results.append({"step": "perp_market_open", "complete": True, **res})
|
||||
if not res.get("ok"):
|
||||
return {"ok": False, "msg": res.get("msg") or "补开永续失败", "results": results, "leg_role": role}
|
||||
return {
|
||||
"ok": True,
|
||||
"leg_role": role,
|
||||
"leg_id": missing.get("id"),
|
||||
"results": results,
|
||||
"fill": res,
|
||||
"opened_at": _now(),
|
||||
}
|
||||
if role in ("option_hedge", "option_b", "option_a"):
|
||||
if role == "option_b":
|
||||
src = start_body.get("leg_b") or {}
|
||||
inst = str(src.get("inst_id") or missing.get("inst_id") or "")
|
||||
sheets = float(src.get("sheets") or missing.get("size") or 1)
|
||||
elif role == "option_a":
|
||||
src = start_body.get("leg_a") or {}
|
||||
inst = str(src.get("inst_id") or missing.get("inst_id") or "")
|
||||
sheets = float(src.get("sheets") or missing.get("size") or 1)
|
||||
else:
|
||||
inst = str(start_body.get("opt_inst_id") or missing.get("inst_id") or "")
|
||||
sheets = float(start_body.get("sheets") or missing.get("size") or 1)
|
||||
res = _buy_option(cfg, inst_id=inst, sheets=sheets, dry_run=dry_run)
|
||||
results.append({"step": "options_buy_limit", "complete": True, "leg_role": role, **res})
|
||||
if not res.get("ok"):
|
||||
return {"ok": False, "msg": res.get("msg") or "补开期权失败", "results": results, "leg_role": role}
|
||||
return {
|
||||
"ok": True,
|
||||
"leg_role": role,
|
||||
"leg_id": missing.get("id"),
|
||||
"results": results,
|
||||
"fill": res,
|
||||
"opened_at": _now(),
|
||||
}
|
||||
return {"ok": False, "msg": f"未知待补腿: {role}"}
|
||||
|
||||
|
||||
def validate_start_body(plan_type: str, body: dict[str, Any]) -> Optional[str]:
|
||||
pt = (plan_type or "").strip().lower()
|
||||
if pt == "perp_options":
|
||||
@@ -427,3 +860,142 @@ def dump_preview(preview: Any) -> str:
|
||||
return json.dumps(preview, ensure_ascii=False)[:8000]
|
||||
except Exception:
|
||||
return ""
|
||||
|
||||
|
||||
def _live_option_pos_sheets(ex: Any, inst_id: str) -> float:
|
||||
from lib.exchange.okx_options_lib import fetch_option_positions
|
||||
|
||||
inst_id = (inst_id or "").strip()
|
||||
if not inst_id or ex is None:
|
||||
return 0.0
|
||||
rows = fetch_option_positions(ex)
|
||||
if rows is None:
|
||||
return -1.0 # API 失败:未知
|
||||
for r in rows:
|
||||
if str(r.get("instId") or "").strip() != inst_id:
|
||||
continue
|
||||
try:
|
||||
return abs(float(r.get("pos") or 0))
|
||||
except (TypeError, ValueError):
|
||||
return 0.0
|
||||
return 0.0
|
||||
|
||||
|
||||
def _sync_plan_status_after_leg_fix(conn: Any, plan_id: int) -> None:
|
||||
"""腿状态校正后:有 open + pending → partial."""
|
||||
from lib.hedge_plan.hedge_plan_db import get_plan, get_plan_legs, update_plan
|
||||
|
||||
plan = get_plan(conn, int(plan_id))
|
||||
if not plan:
|
||||
return
|
||||
pst = str(plan.get("status") or "")
|
||||
if pst not in ("opening", "active", "partial"):
|
||||
return
|
||||
legs = get_plan_legs(conn, int(plan_id))
|
||||
statuses = [str(l.get("status") or "").lower() for l in legs]
|
||||
n_open = sum(1 for s in statuses if s == "open")
|
||||
n_pending = sum(1 for s in statuses if s == "pending")
|
||||
if n_pending and n_open:
|
||||
update_plan(conn, int(plan_id), status="partial", close_reason="partial_fail")
|
||||
|
||||
|
||||
def reconcile_unfilled_option_legs(cfg: dict[str, Any], conn: Any, plan_id: int) -> list[str]:
|
||||
"""未成交却标 open 的期权腿 → pending(可补开);不显示成持仓."""
|
||||
from lib.hedge_plan.hedge_plan_db import get_plan_legs, update_leg
|
||||
from lib.exchange.okx_options_lib import fetch_option_order
|
||||
|
||||
ex = cfg.get("exchange_options")
|
||||
notes: list[str] = []
|
||||
legs = get_plan_legs(conn, int(plan_id))
|
||||
for leg in legs:
|
||||
role = str(leg.get("leg_role") or "")
|
||||
if not role.startswith("option"):
|
||||
continue
|
||||
st = str(leg.get("status") or "").lower()
|
||||
if st != "open":
|
||||
continue
|
||||
inst = str(leg.get("inst_id") or "").strip()
|
||||
oid = str(leg.get("exchange_ord_id") or "").strip()
|
||||
leg_id = int(leg["id"])
|
||||
sheets = _live_option_pos_sheets(ex, inst)
|
||||
if sheets < 0:
|
||||
continue # 查仓失败不改
|
||||
if sheets >= 1:
|
||||
continue
|
||||
# 无实仓:再看订单是否已成交(仍挂单只改 pending,不撤单)
|
||||
if ex is not None and inst and oid:
|
||||
od = fetch_option_order(ex, inst_id=inst, ord_id=oid)
|
||||
if od.get("ok"):
|
||||
acc = float(od.get("acc_fill_sz") or 0)
|
||||
ostate = str(od.get("state") or "")
|
||||
if acc >= 1 or ostate == "filled":
|
||||
continue # 有成交但仓位暂未同步,暂不改
|
||||
update_leg(
|
||||
conn,
|
||||
leg_id,
|
||||
status="pending",
|
||||
close_reason=None,
|
||||
closed_at=None,
|
||||
avg_open=None,
|
||||
premium=0,
|
||||
)
|
||||
notes.append(f"{inst} 无成交却标open→pending")
|
||||
if notes:
|
||||
_sync_plan_status_after_leg_fix(conn, int(plan_id))
|
||||
return notes
|
||||
|
||||
|
||||
def execute_manual_end_plan(cfg: dict[str, Any], conn: Any, plan_id: int) -> dict[str, Any]:
|
||||
"""人工结束进行中计划:不自动平仓;未成交腿标 cancelled."""
|
||||
from lib.hedge_plan.hedge_plan_db import get_plan, get_plan_legs, update_leg, update_plan
|
||||
from lib.hedge_plan.hedge_plan_notify_lib import notify_plan_end
|
||||
from lib.exchange.okx_options_lib import cancel_option_order
|
||||
|
||||
plan = get_plan(conn, int(plan_id))
|
||||
if not plan:
|
||||
return {"ok": False, "msg": "计划不存在"}
|
||||
st = str(plan.get("status") or "")
|
||||
if st not in ("opening", "active", "partial"):
|
||||
return {"ok": False, "msg": f"当前状态 {st or '—'} 不可结束"}
|
||||
|
||||
notes = reconcile_unfilled_option_legs(cfg, conn, int(plan_id))
|
||||
ex = cfg.get("exchange_options")
|
||||
legs = get_plan_legs(conn, int(plan_id))
|
||||
for leg in legs:
|
||||
lst = str(leg.get("status") or "").lower()
|
||||
inst = str(leg.get("inst_id") or "").strip()
|
||||
oid = str(leg.get("exchange_ord_id") or "").strip()
|
||||
if lst == "pending":
|
||||
if ex is not None and inst and oid:
|
||||
cancel_option_order(ex, inst_id=inst, ord_id=oid)
|
||||
update_leg(
|
||||
conn,
|
||||
int(leg["id"]),
|
||||
status="cancelled",
|
||||
close_reason="manual_end",
|
||||
closed_at=_now(),
|
||||
avg_open=None,
|
||||
premium=0,
|
||||
)
|
||||
notes.append(f"{inst or leg.get('leg_role')} 待补→cancelled")
|
||||
|
||||
update_plan(
|
||||
conn,
|
||||
int(plan_id),
|
||||
status="closed",
|
||||
close_reason="manual",
|
||||
closed_at=_now(),
|
||||
note=((plan.get("note") or "") + " · 人工结束(不平仓)").strip(" ·")[:500],
|
||||
)
|
||||
plan2 = get_plan(conn, int(plan_id))
|
||||
if plan2:
|
||||
try:
|
||||
notify_plan_end(cfg, conn, plan2)
|
||||
except Exception:
|
||||
pass
|
||||
return {
|
||||
"ok": True,
|
||||
"plan_id": int(plan_id),
|
||||
"msg": "计划已结束(未自动平仓;有持仓请自行平掉)",
|
||||
"notes": notes,
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from typing import Any
|
||||
from typing import Any, Optional
|
||||
|
||||
from flask import Flask, jsonify, request
|
||||
from jinja2 import ChoiceLoader, FileSystemLoader
|
||||
@@ -97,6 +97,11 @@ def _build_cfg(app_module: Any) -> dict[str, Any]:
|
||||
"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(),
|
||||
"trade_budget_usdc": float(os.getenv("OKX_OPTIONS_TRADE_BUDGET_USDC") or "10"),
|
||||
# 对冲专用缓冲;与期权页 OKX_OPTIONS_BUDGET_BUFFER 独立
|
||||
"budget_buffer": float(os.getenv("HEDGE_PLAN_BUDGET_BUFFER") or "0.95"),
|
||||
"oo_bias_split_by": _oo_bias_split_by(),
|
||||
"oo_bias_ratio": _oo_bias_ratio(),
|
||||
"live_trading": _env_bool("LIVE_TRADING_ENABLED", False),
|
||||
"send_wechat": getattr(app_module, "send_wechat_msg", None),
|
||||
}
|
||||
@@ -106,6 +111,40 @@ def _hedge_enabled() -> bool:
|
||||
return _env_bool("HEDGE_PLAN_ENABLED", False)
|
||||
|
||||
|
||||
def _show_perp_options() -> bool:
|
||||
return _env_bool("HEDGE_PLAN_SHOW_PERP_OPTIONS", True)
|
||||
|
||||
|
||||
def _show_options_options() -> bool:
|
||||
return _env_bool("HEDGE_PLAN_SHOW_OPTIONS_OPTIONS", True)
|
||||
|
||||
|
||||
def _oo_close_mode_enabled() -> bool:
|
||||
return _env_bool("HEDGE_PLAN_OO_CLOSE_MODE_ENABLED", True)
|
||||
|
||||
|
||||
def _oo_bias_split_by() -> str:
|
||||
from lib.hedge_plan.hedge_plan_calc_lib import _normalize_oo_bias_split_by
|
||||
|
||||
return _normalize_oo_bias_split_by(os.getenv("HEDGE_PLAN_OO_BIAS_SPLIT_BY") or "budget")
|
||||
|
||||
|
||||
def _oo_bias_ratio() -> float:
|
||||
from lib.hedge_plan.hedge_plan_calc_lib import _clamp_oo_bias_ratio
|
||||
|
||||
return _clamp_oo_bias_ratio(os.getenv("HEDGE_PLAN_OO_BIAS_RATIO") or "0.7")
|
||||
|
||||
|
||||
def _normalize_oo_close_mode(raw: Any) -> str:
|
||||
"""方案C关闭时强制 hold_expiry;开启时默认 close_all."""
|
||||
if not _oo_close_mode_enabled():
|
||||
return "hold_expiry"
|
||||
v = str(raw or "close_all").strip().lower()
|
||||
if v in ("hold_expiry", "hold_to_expiry", "expiry", "到期平"):
|
||||
return "hold_expiry"
|
||||
return "close_all"
|
||||
|
||||
|
||||
def _live_order() -> bool:
|
||||
return _env_bool("HEDGE_PLAN_LIVE_ORDER", False)
|
||||
|
||||
@@ -119,18 +158,35 @@ def _max_active() -> int:
|
||||
|
||||
def _gates_dict(cfg: dict[str, Any], plan_type: str) -> dict[str, Any]:
|
||||
active = 0
|
||||
has_standalone = False
|
||||
mutual = True
|
||||
try:
|
||||
from lib.hedge_plan.hedge_options_exclusive_lib import (
|
||||
has_standalone_option_position,
|
||||
mutual_exclusive_enabled,
|
||||
)
|
||||
from lib.hedge_plan.hedge_plan_db import count_active_plans, init_hedge_plan_tables
|
||||
|
||||
mutual = mutual_exclusive_enabled()
|
||||
conn = cfg["get_db"]()
|
||||
try:
|
||||
init_hedge_plan_tables(conn)
|
||||
active = count_active_plans(conn)
|
||||
if mutual:
|
||||
try:
|
||||
from lib.exchange.okx_options_lib import fetch_option_positions
|
||||
|
||||
ex = cfg.get("exchange_options") or cfg.get("exchange")
|
||||
raw = fetch_option_positions(ex) if ex is not None else []
|
||||
has_standalone = has_standalone_option_position(conn, raw or [])
|
||||
except Exception:
|
||||
has_standalone = False
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
except Exception:
|
||||
active = 0
|
||||
has_standalone = False
|
||||
return gate_status(
|
||||
hedge_enabled=_hedge_enabled(),
|
||||
sizing_mode=load_position_sizing_mode(),
|
||||
@@ -140,9 +196,23 @@ def _gates_dict(cfg: dict[str, Any], plan_type: str) -> dict[str, Any]:
|
||||
live_trading=bool(cfg.get("live_trading")) or _env_bool("LIVE_TRADING_ENABLED", False),
|
||||
active_count=active,
|
||||
max_active=_max_active(),
|
||||
show_perp_options=_show_perp_options(),
|
||||
show_options_options=_show_options_options(),
|
||||
mutual_exclusive=mutual,
|
||||
has_standalone_option=has_standalone,
|
||||
)
|
||||
|
||||
|
||||
def _gates_public(cfg: dict[str, Any], plan_type: str) -> dict[str, Any]:
|
||||
g = _gates_dict(cfg, plan_type)
|
||||
g["oo_close_mode_enabled"] = _oo_close_mode_enabled()
|
||||
g["oo_close_mode_default"] = "close_all" if _oo_close_mode_enabled() else "hold_expiry"
|
||||
g["oo_bias_split_by"] = _oo_bias_split_by()
|
||||
g["oo_bias_ratio"] = _oo_bias_ratio()
|
||||
g["budget_buffer"] = float(cfg.get("budget_buffer") or 0.95)
|
||||
return g
|
||||
|
||||
|
||||
def _maybe_start_monitor(cfg: dict[str, Any]) -> None:
|
||||
if not _hedge_enabled():
|
||||
return
|
||||
@@ -171,6 +241,18 @@ def _maybe_start_monitor(cfg: dict[str, Any]) -> None:
|
||||
cfg["hedge_monitor_thread"] = t
|
||||
|
||||
|
||||
def _start_body_json(body: dict[str, Any], missing_leg: Optional[str] = None) -> str:
|
||||
import json
|
||||
|
||||
try:
|
||||
return json.dumps(
|
||||
{"start_body": body, "missing_leg": missing_leg},
|
||||
ensure_ascii=False,
|
||||
)[:8000]
|
||||
except Exception:
|
||||
return ""
|
||||
|
||||
|
||||
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,
|
||||
@@ -184,25 +266,36 @@ def _persist_po(cfg: dict[str, Any], result: dict[str, Any], body: dict[str, Any
|
||||
conn = cfg["get_db"]()
|
||||
try:
|
||||
init_hedge_plan_tables(conn)
|
||||
is_partial = bool(result.get("partial"))
|
||||
missing = str(result.get("missing_leg") or "") if is_partial else ""
|
||||
opt = result.get("option") or {}
|
||||
perp = result.get("perp") or {}
|
||||
premium = float(opt.get("premium") or 0)
|
||||
if is_partial:
|
||||
opt_ok = missing != "option_hedge" and bool(result.get("option"))
|
||||
perp_ok = missing != "perp" and bool(result.get("perp"))
|
||||
else:
|
||||
opt_ok = True
|
||||
perp_ok = True
|
||||
premium = float((opt or {}).get("premium") or 0) if opt_ok else 0.0
|
||||
plan_id = insert_plan(
|
||||
conn,
|
||||
{
|
||||
"plan_type": "perp_options",
|
||||
"status": "active",
|
||||
"status": "partial" if is_partial else "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),
|
||||
"perp_size": float((perp or {}).get("contracts") or body.get("contracts") or 0),
|
||||
"margin": body.get("margin"),
|
||||
"leverage": float(body.get("leverage") or 10),
|
||||
"premium_total": premium,
|
||||
"preview_json": _start_body_json(body, missing or None),
|
||||
"close_reason": "partial_fail" if is_partial else None,
|
||||
"opened_at": result.get("opened_at"),
|
||||
"note": (result.get("msg") or "")[:500] if is_partial else None,
|
||||
},
|
||||
)
|
||||
insert_leg(
|
||||
@@ -212,11 +305,11 @@ def _persist_po(cfg: dict[str, Any], result: dict[str, Any], body: dict[str, Any
|
||||
"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"),
|
||||
"size": float((perp or {}).get("contracts") or body.get("contracts") or 0),
|
||||
"avg_open": float(body.get("entry") or 0) if perp_ok else None,
|
||||
"status": "open" if perp_ok else "pending",
|
||||
"exchange_ord_id": str((perp or {}).get("exchange_ord_id") or ""),
|
||||
"opened_at": result.get("opened_at") if perp_ok else None,
|
||||
},
|
||||
)
|
||||
insert_leg(
|
||||
@@ -224,24 +317,25 @@ def _persist_po(cfg: dict[str, Any], result: dict[str, Any], body: dict[str, Any
|
||||
{
|
||||
"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"),
|
||||
"inst_id": str((opt or {}).get("inst_id") or body.get("opt_inst_id") or ""),
|
||||
"opt_type": str((opt or {}).get("opt_type") or body.get("opt_type") or ""),
|
||||
"strike": (opt or {}).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"),
|
||||
"size": float((opt or {}).get("sheets") or body.get("sheets") or 1),
|
||||
"avg_open": float((opt or {}).get("ask") or 0) if opt_ok else None,
|
||||
"premium": premium if opt_ok else 0,
|
||||
"status": "open" if opt_ok else "pending",
|
||||
"exchange_ord_id": str((opt or {}).get("exchange_ord_id") or ""),
|
||||
"opened_at": result.get("opened_at") if opt_ok else None,
|
||||
},
|
||||
)
|
||||
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()
|
||||
if not is_partial:
|
||||
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()
|
||||
@@ -260,14 +354,20 @@ def _persist_oo(cfg: dict[str, Any], result: dict[str, Any], body: dict[str, Any
|
||||
conn = cfg["get_db"]()
|
||||
try:
|
||||
init_hedge_plan_tables(conn)
|
||||
is_partial = bool(result.get("partial"))
|
||||
missing = str(result.get("missing_leg") or "") if is_partial else ""
|
||||
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)
|
||||
a_ok = True if not is_partial else bool(result.get("leg_a"))
|
||||
b_ok = True if not is_partial else (missing != "option_b" and bool(result.get("leg_b")))
|
||||
premium = (float(a.get("premium") or 0) if a_ok else 0.0) + (
|
||||
float(b.get("premium") or 0) if b_ok else 0.0
|
||||
)
|
||||
plan_id = insert_plan(
|
||||
conn,
|
||||
{
|
||||
"plan_type": "options_options",
|
||||
"status": "active",
|
||||
"status": "partial" if is_partial else "active",
|
||||
"underlying": str(body.get("underlying") or "ETH").upper(),
|
||||
"target_price": float(
|
||||
body.get("target_price_up")
|
||||
@@ -286,33 +386,41 @@ def _persist_oo(cfg: dict[str, Any], result: dict[str, Any], body: dict[str, Any
|
||||
),
|
||||
"sizing_mode_at_open": load_position_sizing_mode(),
|
||||
"premium_total": premium,
|
||||
"oo_close_mode": _normalize_oo_close_mode(body.get("oo_close_mode")),
|
||||
"preview_json": _start_body_json(body, missing or None),
|
||||
"close_reason": "partial_fail" if is_partial else None,
|
||||
"opened_at": result.get("opened_at"),
|
||||
"note": (result.get("msg") or "")[:500] if is_partial else None,
|
||||
},
|
||||
)
|
||||
for role, res, src in (("option_a", a, body.get("leg_a") or {}), ("option_b", b, body.get("leg_b") or {})):
|
||||
for role, res, src, ok in (
|
||||
("option_a", a, body.get("leg_a") or {}, a_ok),
|
||||
("option_b", b, body.get("leg_b") or {}, b_ok),
|
||||
):
|
||||
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"),
|
||||
"inst_id": str((res or {}).get("inst_id") or src.get("inst_id") or ""),
|
||||
"opt_type": str((res or {}).get("opt_type") or src.get("opt_type") or ""),
|
||||
"strike": (res or {}).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"),
|
||||
"size": float((res or {}).get("sheets") or src.get("sheets") or 1),
|
||||
"avg_open": float((res or {}).get("ask") or 0) if ok else None,
|
||||
"premium": float((res or {}).get("premium") or 0) if ok else 0,
|
||||
"status": "open" if ok else "pending",
|
||||
"exchange_ord_id": str((res or {}).get("exchange_ord_id") or ""),
|
||||
"opened_at": result.get("opened_at") if ok else None,
|
||||
},
|
||||
)
|
||||
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()
|
||||
if not is_partial:
|
||||
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()
|
||||
@@ -335,7 +443,7 @@ def register_hedge_plan_routes(app: Flask, cfg: dict[str, Any]) -> None:
|
||||
@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)})
|
||||
return jsonify({"ok": True, **_gates_public(cfg, plan_type)})
|
||||
|
||||
@app.route("/api/hedge-plan/market")
|
||||
@lr
|
||||
@@ -395,6 +503,8 @@ def register_hedge_plan_routes(app: Flask, cfg: dict[str, Any]) -> None:
|
||||
"account_label": cfg.get("options_account_label") or "期权账户",
|
||||
"account_note": "期权腿使用期权账户(交易 USDC)",
|
||||
"options_account": opt_acct,
|
||||
"trade_budget_usdc": cfg.get("trade_budget_usdc"),
|
||||
"budget_buffer": cfg.get("budget_buffer"),
|
||||
}
|
||||
)
|
||||
|
||||
@@ -482,6 +592,130 @@ def register_hedge_plan_routes(app: Flask, cfg: dict[str, Any]) -> None:
|
||||
out["gates"] = gates
|
||||
return jsonify(out), (200 if out.get("ok") else 400)
|
||||
|
||||
@app.route("/api/hedge-plan/<int:plan_id>/end", methods=["POST"])
|
||||
@lr
|
||||
def api_hedge_end_plan(plan_id: int):
|
||||
"""人工结束进行中计划:不自动平仓;未成交腿改为 cancelled."""
|
||||
from lib.hedge_plan.hedge_plan_db import init_hedge_plan_tables
|
||||
from lib.hedge_plan.hedge_plan_orders_lib import execute_manual_end_plan
|
||||
|
||||
conn = cfg["get_db"]()
|
||||
try:
|
||||
init_hedge_plan_tables(conn)
|
||||
out = execute_manual_end_plan(cfg, 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/<int:plan_id>/complete-leg", methods=["POST"])
|
||||
@lr
|
||||
def api_hedge_complete_leg(plan_id: int):
|
||||
"""半腿待补:手动补开缺失腿,成功后升为 active."""
|
||||
import json
|
||||
|
||||
from lib.hedge_plan.hedge_plan_db import (
|
||||
get_plan,
|
||||
get_plan_legs,
|
||||
init_hedge_plan_tables,
|
||||
update_leg,
|
||||
update_plan,
|
||||
)
|
||||
from lib.hedge_plan.hedge_plan_notify_lib import notify_plan_start
|
||||
from lib.hedge_plan.hedge_plan_orders_lib import execute_complete_missing_leg
|
||||
|
||||
body = request.get_json(silent=True) or {}
|
||||
dry_run = bool(body.get("dry_run")) or _env_bool("HEDGE_PLAN_DRY_RUN", False)
|
||||
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
|
||||
if str(plan.get("status") or "") != "partial":
|
||||
return jsonify({"ok": False, "msg": "仅半腿待补(partial)计划可补开"}), 400
|
||||
legs = get_plan_legs(conn, plan_id)
|
||||
start_body: dict[str, Any] = {}
|
||||
try:
|
||||
meta = json.loads(plan.get("preview_json") or "{}")
|
||||
if isinstance(meta, dict):
|
||||
start_body = dict(meta.get("start_body") or {})
|
||||
except Exception:
|
||||
start_body = {}
|
||||
if not start_body:
|
||||
return jsonify({"ok": False, "msg": "缺少开仓参数,无法补开"}), 400
|
||||
# 允许请求体覆盖少量字段
|
||||
for k in ("contracts", "leverage", "sheets", "tp", "sl"):
|
||||
if body.get(k) not in (None, ""):
|
||||
start_body[k] = body.get(k)
|
||||
out = execute_complete_missing_leg(
|
||||
cfg, plan, legs, start_body, dry_run=dry_run
|
||||
)
|
||||
if not out.get("ok"):
|
||||
return jsonify(out), 400
|
||||
if dry_run:
|
||||
return jsonify(out)
|
||||
fill = out.get("fill") or {}
|
||||
leg_id = out.get("leg_id")
|
||||
role = str(out.get("leg_role") or "")
|
||||
opened_at = out.get("opened_at")
|
||||
if leg_id:
|
||||
if role == "perp":
|
||||
update_leg(
|
||||
conn,
|
||||
int(leg_id),
|
||||
status="open",
|
||||
size=float(fill.get("contracts") or start_body.get("contracts") or 0),
|
||||
avg_open=float(start_body.get("entry") or plan.get("entry_mark") or 0),
|
||||
exchange_ord_id=str(fill.get("exchange_ord_id") or ""),
|
||||
opened_at=opened_at,
|
||||
)
|
||||
update_plan(
|
||||
conn,
|
||||
plan_id,
|
||||
status="active",
|
||||
close_reason=None,
|
||||
note=None,
|
||||
perp_size=float(fill.get("contracts") or start_body.get("contracts") or 0),
|
||||
)
|
||||
else:
|
||||
prem = float(fill.get("premium") or 0)
|
||||
update_leg(
|
||||
conn,
|
||||
int(leg_id),
|
||||
status="open",
|
||||
size=float(fill.get("sheets") or start_body.get("sheets") or 1),
|
||||
avg_open=float(fill.get("ask") or 0),
|
||||
premium=prem,
|
||||
exchange_ord_id=str(fill.get("exchange_ord_id") or ""),
|
||||
opened_at=opened_at,
|
||||
inst_id=str(fill.get("inst_id") or ""),
|
||||
)
|
||||
old_prem = float(plan.get("premium_total") or 0)
|
||||
update_plan(
|
||||
conn,
|
||||
plan_id,
|
||||
status="active",
|
||||
close_reason=None,
|
||||
note=None,
|
||||
premium_total=old_prem + prem,
|
||||
)
|
||||
conn.commit()
|
||||
plan2 = get_plan(conn, plan_id)
|
||||
legs2 = get_plan_legs(conn, plan_id)
|
||||
if plan2:
|
||||
notify_plan_start(cfg, conn, plan2, legs2)
|
||||
conn.commit()
|
||||
out["plan_id"] = plan_id
|
||||
out["status"] = "active"
|
||||
out["plan"] = plan2
|
||||
out["legs"] = legs2
|
||||
return jsonify(out)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
@app.route("/api/hedge-plan/list")
|
||||
@lr
|
||||
def api_hedge_list():
|
||||
@@ -530,6 +764,7 @@ def register_hedge_plan_routes(app: Flask, cfg: dict[str, Any]) -> None:
|
||||
init_hedge_plan_tables,
|
||||
list_plans,
|
||||
)
|
||||
from lib.hedge_plan.hedge_plan_orders_lib import reconcile_unfilled_option_legs
|
||||
|
||||
conn = cfg["get_db"]()
|
||||
try:
|
||||
@@ -538,6 +773,16 @@ def register_hedge_plan_routes(app: Flask, cfg: dict[str, Any]) -> None:
|
||||
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)
|
||||
for row in rows:
|
||||
try:
|
||||
reconcile_unfilled_option_legs(cfg, conn, int(row["id"]))
|
||||
except Exception:
|
||||
pass
|
||||
# 校正后可能 status 变化,重新拉一遍
|
||||
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:
|
||||
@@ -567,6 +812,7 @@ def register_hedge_plan_routes(app: Flask, cfg: dict[str, Any]) -> None:
|
||||
init_hedge_plan_tables,
|
||||
legs_contract_summary,
|
||||
)
|
||||
from lib.hedge_plan.hedge_plan_orders_lib import reconcile_unfilled_option_legs
|
||||
|
||||
conn = cfg["get_db"]()
|
||||
try:
|
||||
@@ -574,6 +820,10 @@ def register_hedge_plan_routes(app: Flask, cfg: dict[str, Any]) -> None:
|
||||
plan = get_plan(conn, plan_id)
|
||||
if not plan:
|
||||
return jsonify({"ok": False, "msg": "计划不存在"}), 404
|
||||
# 打开细节时校正:无成交却标 open → cancelled
|
||||
if str(plan.get("status") or "") in ("opening", "active", "partial"):
|
||||
reconcile_unfilled_option_legs(cfg, conn, plan_id)
|
||||
plan = get_plan(conn, plan_id) or plan
|
||||
legs = get_plan_legs(conn, plan_id)
|
||||
conn.commit()
|
||||
finally:
|
||||
|
||||
@@ -1,12 +1,17 @@
|
||||
"""对冲计划结算辅助:到期内在价值与期权腿收口."""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import time
|
||||
from typing import Any, Optional
|
||||
from datetime import datetime
|
||||
from typing import Any, Callable, Optional
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from lib.exchange.okx_options_lib import normalize_option_exp_ms
|
||||
from lib.exchange.okx_options_lib import normalize_option_exp_ms, resolve_option_close_from_history
|
||||
from lib.hedge_plan.hedge_plan_calc_lib import option_expiry_pnl
|
||||
|
||||
_APP_TZ = ZoneInfo((os.getenv("APP_TIMEZONE") or os.getenv("TZ") or "Asia/Shanghai").strip() or "Asia/Shanghai")
|
||||
|
||||
|
||||
def _sf(v: Any) -> Optional[float]:
|
||||
try:
|
||||
@@ -60,3 +65,149 @@ def all_option_legs_expired(legs: list[dict[str, Any]], *, now_ms: Optional[int]
|
||||
if not opts:
|
||||
return False
|
||||
return all(leg_is_expired(x, now_ms=now_ms) for x in opts)
|
||||
|
||||
|
||||
def _parse_opened_ms(raw: Any) -> Optional[int]:
|
||||
"""墙钟开仓时间 → UTC ms.库内时间为业务时区(默认 Asia/Shanghai),不可当 UTC."""
|
||||
if raw is None or raw == "":
|
||||
return None
|
||||
s = str(raw).strip()
|
||||
if not s:
|
||||
return None
|
||||
for fmt, ln in (("%Y-%m-%d %H:%M:%S", 19), ("%Y-%m-%d %H:%M:%f", 26), ("%Y-%m-%d %H:%M", 16)):
|
||||
try:
|
||||
dt = datetime.strptime(s[:ln], fmt).replace(tzinfo=_APP_TZ)
|
||||
return int(dt.timestamp() * 1000)
|
||||
except ValueError:
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def resolve_option_leg_realized_pnl(
|
||||
*,
|
||||
ex: Any = None,
|
||||
leg: dict[str, Any],
|
||||
fallback: Optional[float] = None,
|
||||
fetch_history_fn: Optional[Callable[[str], list[dict[str, Any]]]] = None,
|
||||
hist_rows: Optional[list[dict[str, Any]]] = None,
|
||||
) -> tuple[Optional[float], str]:
|
||||
"""
|
||||
期权腿已实现盈亏:优先 OKX positions-history realizedPnl.
|
||||
返回 (pnl, source) source=exchange|fallback|none.
|
||||
"""
|
||||
inst_id = str(leg.get("inst_id") or "").strip()
|
||||
open_ms = _parse_opened_ms(leg.get("opened_at"))
|
||||
rows = hist_rows
|
||||
if rows is None and inst_id:
|
||||
try:
|
||||
if callable(fetch_history_fn):
|
||||
rows = fetch_history_fn(inst_id)
|
||||
elif ex is not None:
|
||||
from lib.exchange.okx_options_lib import fetch_option_position_history
|
||||
|
||||
rows = fetch_option_position_history(ex, inst_id)
|
||||
except Exception:
|
||||
rows = None
|
||||
if rows:
|
||||
info = resolve_option_close_from_history(rows, open_ms=open_ms)
|
||||
pnl = _sf((info or {}).get("realized_pnl")) if info else None
|
||||
if pnl is not None:
|
||||
return round(float(pnl), 4), "exchange"
|
||||
if fallback is not None:
|
||||
return round(float(fallback), 4), "fallback"
|
||||
return None, "none"
|
||||
|
||||
|
||||
def backfill_hedge_option_legs_realized_pnl(
|
||||
conn: Any,
|
||||
hist_rows: list[dict[str, Any]],
|
||||
*,
|
||||
update_plan_fn: Optional[Callable[..., Any]] = None,
|
||||
) -> dict[str, int]:
|
||||
"""用交易所历史覆盖已平期权腿盈亏,并重算已结束计划合计."""
|
||||
from lib.hedge_plan.hedge_plan_db import get_plan, get_plan_legs, update_plan
|
||||
|
||||
by_inst: dict[str, list[dict[str, Any]]] = {}
|
||||
for raw in hist_rows or []:
|
||||
if not isinstance(raw, dict):
|
||||
continue
|
||||
inst = str(raw.get("instId") or "").strip()
|
||||
if inst:
|
||||
by_inst.setdefault(inst, []).append(raw)
|
||||
|
||||
legs = conn.execute(
|
||||
"""
|
||||
SELECT * FROM hedge_plan_legs
|
||||
WHERE status = 'closed'
|
||||
AND inst_id IS NOT NULL AND TRIM(inst_id) != ''
|
||||
AND (leg_role LIKE 'option%' OR opt_type IS NOT NULL)
|
||||
ORDER BY id DESC
|
||||
LIMIT 400
|
||||
"""
|
||||
).fetchall()
|
||||
updated_legs = 0
|
||||
touched_plans: set[int] = set()
|
||||
for row in legs:
|
||||
leg = dict(row)
|
||||
inst = str(leg.get("inst_id") or "").strip()
|
||||
if not inst or inst not in by_inst:
|
||||
continue
|
||||
pnl, src = resolve_option_leg_realized_pnl(
|
||||
leg=leg,
|
||||
hist_rows=by_inst[inst],
|
||||
fallback=None,
|
||||
)
|
||||
if src != "exchange" or pnl is None:
|
||||
continue
|
||||
local = _sf(leg.get("realized_pnl"))
|
||||
if local is not None and abs(local - pnl) < 1e-6:
|
||||
continue
|
||||
conn.execute(
|
||||
"UPDATE hedge_plan_legs SET realized_pnl=? WHERE id=?",
|
||||
(pnl, int(leg["id"])),
|
||||
)
|
||||
updated_legs += 1
|
||||
touched_plans.add(int(leg["plan_id"]))
|
||||
|
||||
updated_plans = 0
|
||||
updater = update_plan_fn or update_plan
|
||||
for pid in touched_plans:
|
||||
plan = get_plan(conn, pid)
|
||||
if not plan or str(plan.get("status") or "") != "closed":
|
||||
continue
|
||||
plan_legs = get_plan_legs(conn, pid)
|
||||
opt_sum = 0.0
|
||||
for lg in plan_legs:
|
||||
role = str(lg.get("leg_role") or "")
|
||||
if not (role.startswith("option") or lg.get("opt_type")):
|
||||
continue
|
||||
if str(lg.get("status") or "") != "closed":
|
||||
continue
|
||||
opt_sum += float(_sf(lg.get("realized_pnl")) or 0.0)
|
||||
perp = float(_sf(plan.get("realized_pnl_perp")) or 0.0)
|
||||
ptype = str(plan.get("plan_type") or "")
|
||||
if ptype == "options_options":
|
||||
total = opt_sum
|
||||
kwargs: dict[str, Any] = {
|
||||
"realized_pnl_options": round(opt_sum, 4),
|
||||
"realized_pnl_total": round(total, 4),
|
||||
}
|
||||
else:
|
||||
total = perp + opt_sum
|
||||
kwargs = {
|
||||
"realized_pnl_perp": round(perp, 4),
|
||||
"realized_pnl_options": round(opt_sum, 4),
|
||||
"realized_pnl_total": round(total, 4),
|
||||
}
|
||||
old_total = _sf(plan.get("realized_pnl_total"))
|
||||
old_opts = _sf(plan.get("realized_pnl_options"))
|
||||
if (
|
||||
old_total is not None
|
||||
and abs(old_total - total) < 1e-6
|
||||
and old_opts is not None
|
||||
and abs(old_opts - opt_sum) < 1e-6
|
||||
):
|
||||
continue
|
||||
updater(conn, pid, **kwargs)
|
||||
updated_plans += 1
|
||||
return {"legs": updated_legs, "plans": updated_plans}
|
||||
|
||||
@@ -2,6 +2,10 @@
|
||||
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-show-perp="{{ '1' if hedge_plan_show_perp_options | default(true) else '0' }}"
|
||||
data-show-oo="{{ '1' if hedge_plan_show_options_options | default(true) else '0' }}"
|
||||
data-oo-close-mode-enabled="{{ '1' if hedge_plan_oo_close_mode_enabled | default(true) else '0' }}"
|
||||
data-budget-buffer="{{ hedge_plan_budget_buffer | default(0.95) }}"
|
||||
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 %}
|
||||
@@ -10,6 +14,9 @@
|
||||
{% if not options_enabled %}
|
||||
<div class="flash" style="margin-bottom:12px">期权模块未启用,无法拉期权链.请先配置期权账户.</div>
|
||||
{% endif %}
|
||||
{% if hedge_plan_enabled and not (hedge_plan_show_perp_options | default(true)) and not (hedge_plan_show_options_options | default(true)) %}
|
||||
<div class="flash" style="margin-bottom:12px">永期与期期 Tab 均已隐藏:可在 <code>env配置 → 对冲计划</code> 打开显示开关;进行中/历史仍可查看.</div>
|
||||
{% endif %}
|
||||
|
||||
<div class="card hp-head-card">
|
||||
<div class="hp-head-row">
|
||||
@@ -19,8 +26,12 @@
|
||||
<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>
|
||||
{% if hedge_plan_show_perp_options | default(true) %}
|
||||
<button type="button" class="hp-tab" role="tab" aria-selected="false" data-tab="perp_options">永期对冲</button>
|
||||
{% endif %}
|
||||
{% if hedge_plan_show_options_options | default(true) %}
|
||||
<button type="button" class="hp-tab" role="tab" aria-selected="false" data-tab="options_options">期期对冲</button>
|
||||
{% endif %}
|
||||
<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>
|
||||
@@ -31,37 +42,61 @@
|
||||
|
||||
<div id="hp-tab-perp_options" class="hp-tab-panel" role="tabpanel">
|
||||
<div class="options-dual-grid" id="hp-po-layout">
|
||||
<div class="card">
|
||||
<div class="card hp-po-perp-card">
|
||||
<h2>永续 · <span id="hp-perp-uly-label">ETH</span> <span class="muted hp-acct-tag" id="hp-perp-acct-tag">合约账户</span></h2>
|
||||
<details class="tip-collapse hp-rule-collapse">
|
||||
<summary class="tip-collapse-summary">规则说明</summary>
|
||||
<div class="tip-collapse-body rule-tip">
|
||||
<p><strong>账户</strong>:永续腿走<strong>合约账户</strong>(USDT);保险期权走<strong>期权账户</strong>(USDC)。两账户分开下单、资金不互通。</p>
|
||||
<p><strong>下单</strong>:先「计算」再「启动」。启动瞬间会再拉卖一并以 IOC 等完全成交;半腿失败可补开或「结束计划」(不平仓)。永期开仓需全仓计仓 + 对冲实盘门禁。</p>
|
||||
<p><strong>板块</strong>:左填永续开仓/止盈止损与张数;右选保险腿(做多配 Put、做空配 Call)。止盈后保险腿默认可持有;止损会联动平期权。</p>
|
||||
</div>
|
||||
</details>
|
||||
<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 class="hp-po-top">
|
||||
<div class="hp-oo-seg hp-po-dir-seg" role="group" aria-label="方向">
|
||||
<button type="button" class="btn-secondary hp-po-dir is-selected" data-dir="long" title="做多永续"><span class="hp-oo-check" aria-hidden="true">✓</span>做多</button>
|
||||
<button type="button" class="btn-secondary hp-po-dir" data-dir="short" title="做空永续"><span class="hp-oo-check" aria-hidden="true">✓</span>做空</button>
|
||||
</div>
|
||||
<span id="hp-po-mark" class="hp-po-mark" aria-live="polite">标记 —</span>
|
||||
</div>
|
||||
<p id="hp-perp-quote" class="muted hp-po-meta">加载中…</p>
|
||||
<div class="hp-po-fields">
|
||||
<label class="hp-po-field">
|
||||
<span class="hp-po-field-lab">开仓价 <em>USDT</em></span>
|
||||
<input type="number" step="any" id="hp-entry" placeholder="入场价" autocomplete="off" inputmode="decimal" data-lpignore="true" data-1p-ignore="true" data-form-type="other" />
|
||||
</label>
|
||||
<label class="hp-po-field">
|
||||
<span class="hp-po-field-lab">张数 <em>合约张</em></span>
|
||||
<input type="number" step="any" id="hp-contracts" placeholder="数量" autocomplete="off" inputmode="decimal" data-lpignore="true" data-1p-ignore="true" data-form-type="other" />
|
||||
</label>
|
||||
<label class="hp-po-field hp-po-field--tp">
|
||||
<span class="hp-po-field-lab">止盈 <em>USDT</em></span>
|
||||
<input type="number" step="any" id="hp-tp" placeholder="目标价" autocomplete="off" inputmode="decimal" data-lpignore="true" data-1p-ignore="true" data-form-type="other" />
|
||||
</label>
|
||||
<label class="hp-po-field hp-po-field--sl">
|
||||
<span class="hp-po-field-lab">止损 <em>USDT</em></span>
|
||||
<input type="number" step="any" id="hp-sl" placeholder="保护价" autocomplete="off" inputmode="decimal" data-lpignore="true" data-1p-ignore="true" data-form-type="other" />
|
||||
</label>
|
||||
</div>
|
||||
<div class="hp-po-summary">
|
||||
<div id="hp-perp-pnl-line" class="hp-po-pnl"></div>
|
||||
<div id="hp-sizing-line" class="muted hp-po-sizing"></div>
|
||||
</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">
|
||||
<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 hp-po-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>
|
||||
<span id="hp-index-line" class="hp-po-index" aria-live="polite">指数 —</span>
|
||||
</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>
|
||||
@@ -80,66 +115,67 @@
|
||||
</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>
|
||||
<label>张数 <span class="hp-unit">期权张</span> <input type="number" step="1" min="1" id="hp-sheets" value="1" autocomplete="off" inputmode="numeric" data-lpignore="true" data-1p-ignore="true" data-form-type="other" /></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 id="hp-opt-bal-line" class="muted hp-po-meta 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>
|
||||
<details class="tip-collapse hp-rule-collapse">
|
||||
<summary class="tip-collapse-summary">规则说明</summary>
|
||||
<div class="tip-collapse-body rule-tip">
|
||||
<p><strong>账户</strong>:两腿都在<strong>期权账户</strong>。可用预算 = min(交易 USDC × 对冲缓冲 <strong id="hp-oo-buf-ratio">{{ '%.2f'|format(hedge_plan_budget_buffer|default(0.95)|float) }}</strong>, 单笔预算);可在 env「对冲预算缓冲比例」改。</p>
|
||||
<p><strong>下单</strong>:选 Call + Put 后「计算」再「启动」。启动会再拉卖一并按最新价重算张数,IOC 完全成交才算成功;资金不足可在右侧划转。</p>
|
||||
<p><strong>板块</strong>:左填上破/下破与张数模式(同张数/做多/做空);右 T 型选腿。「全平」= 盈利腿平后清另一腿;「到期平」= 另一腿持有至到期。</p>
|
||||
</div>
|
||||
</details>
|
||||
<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 class="form-row hp-target-row hp-oo-target-row">
|
||||
<label>上破目标 <input type="number" step="any" id="hp-target-up" placeholder="向上突破" autocomplete="off" inputmode="decimal" data-lpignore="true" data-1p-ignore="true" data-form-type="other" /></label>
|
||||
<label>下破目标 <input type="number" step="any" id="hp-target-down" placeholder="向下突破" autocomplete="off" inputmode="decimal" data-lpignore="true" data-1p-ignore="true" data-form-type="other" /></label>
|
||||
<span id="hp-oo-index" class="hp-oo-index" aria-live="polite">指数 —</span>
|
||||
</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 class="hp-oo-controls">
|
||||
<div class="hp-oo-ctrl">
|
||||
<span class="hp-oo-ctrl-lab">张数</span>
|
||||
<div class="hp-oo-seg" role="group" aria-label="自动张数">
|
||||
<button type="button" class="btn-secondary hp-oo-size-mode is-selected" data-oo-size="same_sheets" title="两腿同张数,总权利金≤预算"><span class="hp-oo-check" aria-hidden="true">✓</span>同张数</button>
|
||||
<button type="button" class="btn-secondary hp-oo-size-mode" data-oo-size="long_bias" title="偏多:Call 占比更高(比例见 env)"><span class="hp-oo-check" aria-hidden="true">✓</span>做多</button>
|
||||
<button type="button" class="btn-secondary hp-oo-size-mode" data-oo-size="short_bias" title="偏空:Put 占比更高(比例见 env)"><span class="hp-oo-check" aria-hidden="true">✓</span>做空</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="hp-oo-ctrl" id="hp-oo-close-mode-row">
|
||||
<span class="hp-oo-ctrl-lab" title="仅控制盈利腿平掉后的另一腿">平仓</span>
|
||||
<div class="hp-oo-seg" role="group" aria-label="平仓模式">
|
||||
<button type="button" class="btn-secondary hp-oo-close-mode is-selected" data-oo-close="close_all" title="盈利腿平后立刻买一清另一腿(无2×,失败重试)"><span class="hp-oo-check" aria-hidden="true">✓</span>全平</button>
|
||||
<button type="button" class="btn-secondary hp-oo-close-mode" data-oo-close="hold_expiry" title="盈利腿平后另一腿持有至到期"><span class="hp-oo-check" aria-hidden="true">✓</span>到期平</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<p class="muted hp-oo-meta" id="hp-oo-budget-line"></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 />
|
||||
<input type="number" step="1" min="0" id="hp-oo-sheets-a" value="1" disabled autocomplete="off" inputmode="numeric" data-lpignore="true" data-1p-ignore="true" data-form-type="other" />
|
||||
</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 />
|
||||
<input type="number" step="1" min="0" id="hp-oo-sheets-b" value="1" disabled autocomplete="off" inputmode="numeric" data-lpignore="true" data-1p-ignore="true" data-form-type="other" />
|
||||
</label>
|
||||
</div>
|
||||
<p class="muted" id="hp-oo-prem-line"></p>
|
||||
@@ -170,33 +206,33 @@
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div class="hp-oo-transfer hp-oo-transfer--compact" id="hp-oo-transfer">
|
||||
<div class="hp-oo-transfer-bals muted">
|
||||
<span>资金 <strong id="hp-oo-funding-usdc">—</strong></span>
|
||||
<span class="hp-oo-transfer-sep">·</span>
|
||||
<span>交易 <strong id="hp-oo-trading-usdc">—</strong></span>
|
||||
<span class="hp-oo-transfer-unit">USDC</span>
|
||||
<span class="muted" id="hp-oo-xfer-msg"></span>
|
||||
</div>
|
||||
<div class="form-row hp-oo-transfer-form" autocomplete="off">
|
||||
{# 诱饵账号框:避免浏览器把划转数量当成登录用户名填 dekun #}
|
||||
<input type="text" name="username" autocomplete="username" tabindex="-1" aria-hidden="true"
|
||||
style="position:absolute;left:-9999px;width:1px;height:1px;opacity:0" value="">
|
||||
<select id="hp-oo-xfer-dir" aria-label="划转方向" autocomplete="off">
|
||||
<option value="funding_to_trading" selected>资金 → 交易</option>
|
||||
<option value="trading_to_funding">交易 → 资金</option>
|
||||
</select>
|
||||
<input type="number" id="hp-oo-xfer-amount" name="cm_hp_xfer_amt" min="0.01" step="0.01" placeholder="数量"
|
||||
autocomplete="off" inputmode="decimal" data-lpignore="true" data-1p-ignore="true" data-bwignore="true" data-form-type="other" readonly />
|
||||
<button type="button" class="btn-secondary btn-sm" id="hp-oo-xfer-all">全部</button>
|
||||
<button type="button" class="btn-primary btn-sm" id="hp-oo-xfer-btn">划转</button>
|
||||
</div>
|
||||
</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>
|
||||
@@ -254,5 +290,36 @@
|
||||
<div id="hp-detail-body" class="hp-modal-body muted">加载中…</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="hp-preview-modal" class="hp-modal-backdrop" hidden>
|
||||
<div class="hp-modal hp-preview-modal" role="dialog" aria-modal="true" aria-labelledby="hp-preview-title">
|
||||
<div class="hp-modal-head">
|
||||
<h3 id="hp-preview-title">情景测算</h3>
|
||||
<button type="button" class="btn-secondary" id="hp-preview-cancel-x" aria-label="关闭">关闭</button>
|
||||
</div>
|
||||
<div id="hp-preview-summary" class="muted hp-preview-summary"></div>
|
||||
<div class="options-strike-table-wrap">
|
||||
<table class="options-strike-table" id="hp-result-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>情景</th>
|
||||
<th>现货价</th>
|
||||
<th id="hp-preview-mid-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 class="form-row hp-preview-actions">
|
||||
<button type="button" class="btn-secondary" id="hp-preview-cancel">取消</button>
|
||||
<button type="button" class="primary" id="hp-preview-start" disabled title="需开启 HEDGE_PLAN_LIVE_ORDER 等门禁">启动计划</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<script src="/static/hedge_plan.js?v=13"></script>
|
||||
<script src="/static/hedge_plan.js?v=33"></script>
|
||||
|
||||
@@ -0,0 +1,833 @@
|
||||
"""中控振幅统计:OKX 指数(可降级永续)按时段切窗,点数口径.
|
||||
|
||||
仅只读行情;不触及下单链路.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import csv
|
||||
import io
|
||||
import statistics
|
||||
import time
|
||||
from datetime import date, datetime, timedelta
|
||||
from typing import Any, Callable, Optional
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
import httpx
|
||||
|
||||
APP_TZ = ZoneInfo("Asia/Shanghai")
|
||||
END_HOUR = 16
|
||||
EXCHANGE = "okx"
|
||||
TIMEFRAME = "1H"
|
||||
|
||||
SYMBOLS: dict[str, dict[str, str]] = {
|
||||
"eth": {
|
||||
"label": "ETH",
|
||||
"index_inst": "ETH-USD",
|
||||
"swap_inst": "ETH-USDT-SWAP",
|
||||
},
|
||||
"btc": {
|
||||
"label": "BTC",
|
||||
"index_inst": "BTC-USD",
|
||||
"swap_inst": "BTC-USDT-SWAP",
|
||||
},
|
||||
}
|
||||
|
||||
PERIOD_DAYS: dict[str, int] = {
|
||||
"1m": 30,
|
||||
"2m": 60,
|
||||
"3m": 90,
|
||||
"6m": 180,
|
||||
"1y": 365,
|
||||
}
|
||||
|
||||
OKX_INDEX_CANDLES = "https://www.okx.com/api/v5/market/index-candles"
|
||||
OKX_HISTORY_INDEX_CANDLES = "https://www.okx.com/api/v5/market/history-index-candles"
|
||||
OKX_SWAP_CANDLES = "https://www.okx.com/api/v5/market/candles"
|
||||
OKX_HISTORY_SWAP_CANDLES = "https://www.okx.com/api/v5/market/history-candles"
|
||||
|
||||
|
||||
def normalize_symbol(raw: str) -> str:
|
||||
s = (raw or "").strip().lower()
|
||||
if s in ("eth", "ethereum"):
|
||||
return "eth"
|
||||
if s in ("btc", "bitcoin"):
|
||||
return "btc"
|
||||
raise ValueError("symbol 仅支持 eth / btc")
|
||||
|
||||
|
||||
def resolve_sample_days(period: str, custom_days: Any = None) -> int:
|
||||
p = (period or "2m").strip().lower()
|
||||
if p == "custom":
|
||||
try:
|
||||
n = int(custom_days)
|
||||
except (TypeError, ValueError):
|
||||
raise ValueError("自定义天数无效") from None
|
||||
return max(7, min(400, n))
|
||||
if p not in PERIOD_DAYS:
|
||||
raise ValueError("周期无效")
|
||||
return PERIOD_DAYS[p]
|
||||
|
||||
|
||||
def window_bounds_for_settlement(settlement: date, start_hour: int) -> tuple[datetime, datetime]:
|
||||
"""返回 [start, end) 的本地时刻;end 为结算日 16:00."""
|
||||
if not (0 <= int(start_hour) <= 23):
|
||||
raise ValueError("起点须为 0-23 整点")
|
||||
end = datetime(settlement.year, settlement.month, settlement.day, END_HOUR, 0, 0, tzinfo=APP_TZ)
|
||||
sh = int(start_hour)
|
||||
if sh >= END_HOUR:
|
||||
prev = settlement - timedelta(days=1)
|
||||
start = datetime(prev.year, prev.month, prev.day, sh, 0, 0, tzinfo=APP_TZ)
|
||||
else:
|
||||
start = datetime(settlement.year, settlement.month, settlement.day, sh, 0, 0, tzinfo=APP_TZ)
|
||||
return start, end
|
||||
|
||||
|
||||
def list_settlement_dates(*, sample_days: int, now: Optional[datetime] = None) -> list[date]:
|
||||
"""最近 sample_days 个已收窗结算日(不含进行中的今天未到 16:00)."""
|
||||
now = now or datetime.now(APP_TZ)
|
||||
if now.tzinfo is None:
|
||||
now = now.replace(tzinfo=APP_TZ)
|
||||
else:
|
||||
now = now.astimezone(APP_TZ)
|
||||
today = now.date()
|
||||
today_end = datetime(today.year, today.month, today.day, END_HOUR, 0, 0, tzinfo=APP_TZ)
|
||||
latest = today if now >= today_end else today - timedelta(days=1)
|
||||
return [latest - timedelta(days=i) for i in range(int(sample_days))]
|
||||
|
||||
|
||||
def _safe_float(v: Any) -> Optional[float]:
|
||||
try:
|
||||
if v is None or v == "":
|
||||
return None
|
||||
return float(v)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def bars_to_map(bars: list[dict[str, Any]]) -> dict[int, dict[str, float]]:
|
||||
"""open_time_ms -> {o,h,l,c}."""
|
||||
m: dict[int, dict[str, float]] = {}
|
||||
for b in bars or []:
|
||||
if not isinstance(b, dict):
|
||||
continue
|
||||
ts = b.get("ts")
|
||||
if ts is None:
|
||||
ts = b.get("open_time_ms")
|
||||
try:
|
||||
ts_i = int(ts)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
o = _safe_float(b.get("o") if "o" in b else b.get("open"))
|
||||
h = _safe_float(b.get("h") if "h" in b else b.get("high"))
|
||||
l = _safe_float(b.get("l") if "l" in b else b.get("low"))
|
||||
c = _safe_float(b.get("c") if "c" in b else b.get("close"))
|
||||
if None in (o, h, l, c):
|
||||
continue
|
||||
m[ts_i] = {"o": float(o), "h": float(h), "l": float(l), "c": float(c)}
|
||||
return m
|
||||
|
||||
|
||||
def compute_day_row(
|
||||
settlement: date,
|
||||
start_hour: int,
|
||||
bar_map: dict[int, dict[str, float]],
|
||||
) -> Optional[dict[str, Any]]:
|
||||
start, end = window_bounds_for_settlement(settlement, start_hour)
|
||||
start_ms = int(start.timestamp() * 1000)
|
||||
# 1H 棒覆盖 [T, T+1h);窗终点 16:00 用 15:00 棒的 close
|
||||
last_bar_ms = int((end - timedelta(hours=1)).timestamp() * 1000)
|
||||
if start_ms not in bar_map or last_bar_ms not in bar_map:
|
||||
return None
|
||||
opens = bar_map[start_ms]["o"]
|
||||
close = bar_map[last_bar_ms]["c"]
|
||||
hi = bar_map[start_ms]["h"]
|
||||
lo = bar_map[start_ms]["l"]
|
||||
t = start_ms
|
||||
while t <= last_bar_ms:
|
||||
b = bar_map.get(t)
|
||||
if b:
|
||||
hi = max(hi, b["h"])
|
||||
lo = min(lo, b["l"])
|
||||
t += 3600 * 1000
|
||||
up = hi - opens
|
||||
down = opens - lo
|
||||
amp = hi - lo
|
||||
change = close - opens
|
||||
wd = settlement.weekday() # Mon=0 … Sun=6
|
||||
is_we = wd >= 5
|
||||
return {
|
||||
"settlement_day": settlement.isoformat(),
|
||||
"window_start": start.strftime("%Y-%m-%d %H:%M"),
|
||||
"window_end": end.strftime("%Y-%m-%d %H:%M"),
|
||||
"weekday": wd,
|
||||
"weekday_label": "六" if wd == 5 else ("日" if wd == 6 else ""),
|
||||
"is_weekend": is_we,
|
||||
"open": round(opens, 4),
|
||||
"high": round(hi, 4),
|
||||
"low": round(lo, 4),
|
||||
"close": round(close, 4),
|
||||
"up_points": round(up, 4),
|
||||
"down_points": round(down, 4),
|
||||
"amplitude": round(amp, 4),
|
||||
"change": round(change, 4),
|
||||
}
|
||||
|
||||
|
||||
def normalize_straddle_premium(raw: Any) -> Optional[float]:
|
||||
"""双边权利金(点数).空/≤0 表示不做跨式对照."""
|
||||
if raw is None or raw == "":
|
||||
return None
|
||||
try:
|
||||
v = float(raw)
|
||||
except (TypeError, ValueError):
|
||||
raise ValueError("双边权利金须为数字") from None
|
||||
if v <= 0:
|
||||
return None
|
||||
return v
|
||||
|
||||
|
||||
def normalize_take_profit(raw: Any) -> Optional[float]:
|
||||
"""止盈点.空/≤0 表示不止盈,有效波动用 |涨跌|."""
|
||||
if raw is None or raw == "":
|
||||
return None
|
||||
try:
|
||||
v = float(raw)
|
||||
except (TypeError, ValueError):
|
||||
raise ValueError("止盈点须为数字") from None
|
||||
if v <= 0:
|
||||
return None
|
||||
return v
|
||||
|
||||
|
||||
def normalize_weekend_filter(raw: Any) -> str:
|
||||
"""all | exclude | only;默认全部."""
|
||||
s = (str(raw) if raw is not None else "all").strip().lower()
|
||||
if s in ("", "all", "全部"):
|
||||
return "all"
|
||||
if s in ("exclude", "exclude_weekend", "no_weekend", "排除周末"):
|
||||
return "exclude"
|
||||
if s in ("only", "weekend_only", "only_weekend", "仅周末"):
|
||||
return "only"
|
||||
raise ValueError("周末筛选须为 all / exclude / only")
|
||||
|
||||
|
||||
def filter_weekend_rows(rows: list[dict[str, Any]], weekend_filter: Any = "all") -> list[dict[str, Any]]:
|
||||
mode = normalize_weekend_filter(weekend_filter)
|
||||
if mode == "all":
|
||||
return list(rows or [])
|
||||
out: list[dict[str, Any]] = []
|
||||
for r in rows or []:
|
||||
is_we = bool(r.get("is_weekend"))
|
||||
if "is_weekend" not in r and r.get("settlement_day"):
|
||||
try:
|
||||
is_we = date.fromisoformat(str(r["settlement_day"])).weekday() >= 5
|
||||
except ValueError:
|
||||
is_we = False
|
||||
if mode == "exclude" and is_we:
|
||||
continue
|
||||
if mode == "only" and not is_we:
|
||||
continue
|
||||
out.append(r)
|
||||
return out
|
||||
|
||||
|
||||
def effective_move_points(row: dict[str, Any], take_profit: Optional[float]) -> float:
|
||||
"""触达止盈(≥)用止盈点,否则用 |涨跌|."""
|
||||
abs_chg = abs(float(row.get("change") or 0))
|
||||
if take_profit is None:
|
||||
return abs_chg
|
||||
tp = float(take_profit)
|
||||
up = float(row.get("up_points") or 0)
|
||||
down = float(row.get("down_points") or 0)
|
||||
if up >= tp or down >= tp:
|
||||
return tp
|
||||
return abs_chg
|
||||
|
||||
|
||||
def enrich_rows_pnl(
|
||||
rows: list[dict[str, Any]],
|
||||
*,
|
||||
straddle_premium: Optional[float] = None,
|
||||
take_profit: Optional[float] = None,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""为日表附加有效波动 / 是否触达止盈 / 收益(有权利金时)."""
|
||||
prem = normalize_straddle_premium(straddle_premium)
|
||||
tp = normalize_take_profit(take_profit)
|
||||
out: list[dict[str, Any]] = []
|
||||
for r in rows or []:
|
||||
item = dict(r)
|
||||
if "is_weekend" not in item and item.get("settlement_day"):
|
||||
try:
|
||||
wd = date.fromisoformat(str(item["settlement_day"])).weekday()
|
||||
item["weekday"] = wd
|
||||
item["weekday_label"] = "六" if wd == 5 else ("日" if wd == 6 else "")
|
||||
item["is_weekend"] = wd >= 5
|
||||
except ValueError:
|
||||
item.setdefault("weekday_label", "")
|
||||
item.setdefault("is_weekend", False)
|
||||
move = effective_move_points(item, tp)
|
||||
hit = False
|
||||
if tp is not None:
|
||||
hit = float(item.get("up_points") or 0) >= tp or float(item.get("down_points") or 0) >= tp
|
||||
item["effective_move"] = round(move, 4)
|
||||
item["take_profit_hit"] = hit
|
||||
item["profit"] = round(move - prem, 4) if prem is not None else None
|
||||
out.append(item)
|
||||
return out
|
||||
|
||||
|
||||
def straddle_long_stats(
|
||||
rows: list[dict[str, Any]],
|
||||
premium: float,
|
||||
*,
|
||||
take_profit: Any = None,
|
||||
) -> dict[str, Any]:
|
||||
"""买跨:越过权利金用严格 >;收益=有效波动−权利金(止盈≥触达用止盈点,否则|涨跌|)."""
|
||||
prem = float(premium)
|
||||
if prem <= 0:
|
||||
raise ValueError("双边权利金须 > 0")
|
||||
tp = normalize_take_profit(take_profit)
|
||||
enriched = enrich_rows_pnl(rows, straddle_premium=prem, take_profit=tp)
|
||||
if not enriched:
|
||||
return {
|
||||
"side": "long_straddle",
|
||||
"premium": prem,
|
||||
"take_profit": tp,
|
||||
"sample_count": 0,
|
||||
"up_exceed_days": 0,
|
||||
"up_exceed_ratio": None,
|
||||
"down_exceed_days": 0,
|
||||
"down_exceed_ratio": None,
|
||||
"abs_change_exceed_days": 0,
|
||||
"abs_change_exceed_ratio": None,
|
||||
"tp_hit_days": 0,
|
||||
"tp_hit_ratio": None,
|
||||
"pnl_total": None,
|
||||
"pnl_avg": None,
|
||||
"win_days": 0,
|
||||
"win_ratio": None,
|
||||
"pnl_max": None,
|
||||
"pnl_min": None,
|
||||
}
|
||||
n = len(enriched)
|
||||
up_ex = sum(1 for r in enriched if float(r["up_points"]) > prem)
|
||||
down_ex = sum(1 for r in enriched if float(r["down_points"]) > prem)
|
||||
abs_ex = sum(1 for r in enriched if abs(float(r["change"])) > prem)
|
||||
tp_hits = sum(1 for r in enriched if r.get("take_profit_hit"))
|
||||
pnls = [float(r["profit"]) for r in enriched if r.get("profit") is not None]
|
||||
win = sum(1 for p in pnls if p > 0)
|
||||
return {
|
||||
"side": "long_straddle",
|
||||
"premium": round(prem, 4),
|
||||
"take_profit": round(tp, 4) if tp is not None else None,
|
||||
"sample_count": n,
|
||||
"up_exceed_days": up_ex,
|
||||
"up_exceed_ratio": round(up_ex / n, 4),
|
||||
"down_exceed_days": down_ex,
|
||||
"down_exceed_ratio": round(down_ex / n, 4),
|
||||
"abs_change_exceed_days": abs_ex,
|
||||
"abs_change_exceed_ratio": round(abs_ex / n, 4),
|
||||
"tp_hit_days": tp_hits,
|
||||
"tp_hit_ratio": round(tp_hits / n, 4) if tp is not None else None,
|
||||
"pnl_total": round(sum(pnls), 4),
|
||||
"pnl_avg": round(statistics.fmean(pnls), 4),
|
||||
"win_days": win,
|
||||
"win_ratio": round(win / n, 4),
|
||||
"pnl_max": round(max(pnls), 4),
|
||||
"pnl_min": round(min(pnls), 4),
|
||||
}
|
||||
|
||||
|
||||
def summarize_rows(
|
||||
rows: list[dict[str, Any]],
|
||||
*,
|
||||
straddle_premium: Any = None,
|
||||
take_profit: Any = None,
|
||||
) -> dict[str, Any]:
|
||||
if not rows:
|
||||
out = {
|
||||
"sample_count": 0,
|
||||
"max_amplitude": None,
|
||||
"max_amplitude_day": None,
|
||||
"avg_amplitude": None,
|
||||
"median_amplitude": None,
|
||||
"max_up_points": None,
|
||||
"avg_up_points": None,
|
||||
"max_down_points": None,
|
||||
"avg_down_points": None,
|
||||
"up_day_ratio": None,
|
||||
"down_day_ratio": None,
|
||||
"straddle": None,
|
||||
}
|
||||
prem = normalize_straddle_premium(straddle_premium)
|
||||
if prem is not None:
|
||||
out["straddle"] = straddle_long_stats([], prem, take_profit=take_profit)
|
||||
return out
|
||||
amps = [float(r["amplitude"]) for r in rows]
|
||||
ups = [float(r["up_points"]) for r in rows]
|
||||
downs = [float(r["down_points"]) for r in rows]
|
||||
max_amp = max(amps)
|
||||
max_amp_day = next(r["settlement_day"] for r in rows if float(r["amplitude"]) == max_amp)
|
||||
up_days = sum(1 for r in rows if float(r["change"]) > 0)
|
||||
down_days = sum(1 for r in rows if float(r["change"]) < 0)
|
||||
n = len(rows)
|
||||
out: dict[str, Any] = {
|
||||
"sample_count": n,
|
||||
"max_amplitude": round(max_amp, 4),
|
||||
"max_amplitude_day": max_amp_day,
|
||||
"avg_amplitude": round(statistics.fmean(amps), 4),
|
||||
"median_amplitude": round(statistics.median(amps), 4),
|
||||
"max_up_points": round(max(ups), 4),
|
||||
"avg_up_points": round(statistics.fmean(ups), 4),
|
||||
"max_down_points": round(max(downs), 4),
|
||||
"avg_down_points": round(statistics.fmean(downs), 4),
|
||||
"up_day_ratio": round(up_days / n, 4),
|
||||
"down_day_ratio": round(down_days / n, 4),
|
||||
"straddle": None,
|
||||
}
|
||||
prem = normalize_straddle_premium(straddle_premium)
|
||||
if prem is not None:
|
||||
out["straddle"] = straddle_long_stats(rows, prem, take_profit=take_profit)
|
||||
return out
|
||||
|
||||
|
||||
def _parse_okx_candle_row(row: list) -> Optional[dict[str, Any]]:
|
||||
if not row or len(row) < 5:
|
||||
return None
|
||||
try:
|
||||
ts = int(row[0])
|
||||
o, h, l, c = float(row[1]), float(row[2]), float(row[3]), float(row[4])
|
||||
except (TypeError, ValueError, IndexError):
|
||||
return None
|
||||
return {"ts": ts, "o": o, "h": h, "l": l, "c": c}
|
||||
|
||||
|
||||
def _okx_get_json(
|
||||
client: httpx.Client,
|
||||
url: str,
|
||||
params: dict[str, str],
|
||||
*,
|
||||
retries: int = 8,
|
||||
) -> dict[str, Any]:
|
||||
"""GET OKX 公共行情;遇 429 指数退避重试."""
|
||||
last_err: Optional[BaseException] = None
|
||||
for attempt in range(max(1, int(retries))):
|
||||
try:
|
||||
r = client.get(url, params=params)
|
||||
if r.status_code == 429:
|
||||
wait = min(12.0, 0.7 * (2**attempt))
|
||||
time.sleep(wait)
|
||||
last_err = httpx.HTTPStatusError(
|
||||
f"429 Too Many Requests for url '{r.url}'",
|
||||
request=r.request,
|
||||
response=r,
|
||||
)
|
||||
continue
|
||||
r.raise_for_status()
|
||||
body = r.json()
|
||||
if not isinstance(body, dict):
|
||||
raise RuntimeError("OKX 返回非对象 JSON")
|
||||
return body
|
||||
except httpx.HTTPStatusError as exc:
|
||||
status = exc.response.status_code if exc.response is not None else None
|
||||
if status == 429 and attempt + 1 < retries:
|
||||
wait = min(12.0, 0.7 * (2**attempt))
|
||||
time.sleep(wait)
|
||||
last_err = exc
|
||||
continue
|
||||
raise
|
||||
except httpx.TransportError as exc:
|
||||
if attempt + 1 < retries:
|
||||
time.sleep(min(8.0, 0.5 * (2**attempt)))
|
||||
last_err = exc
|
||||
continue
|
||||
raise
|
||||
if last_err is not None:
|
||||
raise last_err
|
||||
raise RuntimeError("OKX 请求失败")
|
||||
|
||||
|
||||
def fetch_okx_candles(
|
||||
*,
|
||||
url: str,
|
||||
inst_id: str,
|
||||
since_ms: int,
|
||||
until_ms: int,
|
||||
bar: str = "1H",
|
||||
client: Optional[httpx.Client] = None,
|
||||
timeout: float = 30.0,
|
||||
history_url: Optional[str] = None,
|
||||
max_pages: int = 200,
|
||||
page_pause_sec: float = 0.12,
|
||||
history_page_pause_sec: float = 0.22,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""拉取 [since_ms, until_ms] 覆盖的 K 线(含边界).
|
||||
|
||||
OKX 近期接口约仅 1440 根;更早需 history_* 端点续拉.
|
||||
分页带间隔,429 自动退避重试.
|
||||
"""
|
||||
own = client is None
|
||||
client = client or httpx.Client(
|
||||
timeout=timeout,
|
||||
trust_env=False,
|
||||
headers={"User-Agent": "crypto_monitor-amp-stats/1.0"},
|
||||
)
|
||||
try:
|
||||
out: dict[int, dict[str, Any]] = {}
|
||||
after: Optional[str] = None
|
||||
active_url = url
|
||||
switched_history = False
|
||||
for page_i in range(max(20, int(max_pages))):
|
||||
if page_i > 0:
|
||||
pause = history_page_pause_sec if switched_history or "history" in active_url else page_pause_sec
|
||||
if pause > 0:
|
||||
time.sleep(pause)
|
||||
params: dict[str, str] = {"instId": inst_id, "bar": bar, "limit": "100"}
|
||||
if after:
|
||||
params["after"] = after
|
||||
body = _okx_get_json(client, active_url, params)
|
||||
if str(body.get("code") or "") not in ("0", "0.0", ""):
|
||||
raise RuntimeError(body.get("msg") or f"OKX error {body.get('code')}")
|
||||
data = body.get("data") or []
|
||||
if not data:
|
||||
# 近期接口到头 → 切历史端点再试
|
||||
if history_url and not switched_history and after is not None:
|
||||
active_url = history_url
|
||||
switched_history = True
|
||||
time.sleep(max(history_page_pause_sec, 0.35))
|
||||
continue
|
||||
break
|
||||
oldest_ts = None
|
||||
for row in data:
|
||||
parsed = _parse_okx_candle_row(row)
|
||||
if not parsed:
|
||||
continue
|
||||
ts = int(parsed["ts"])
|
||||
oldest_ts = ts if oldest_ts is None else min(oldest_ts, ts)
|
||||
if ts < since_ms - 3600 * 1000:
|
||||
continue
|
||||
if ts > until_ms + 3600 * 1000:
|
||||
continue
|
||||
out[ts] = parsed
|
||||
if oldest_ts is None:
|
||||
break
|
||||
if oldest_ts <= since_ms:
|
||||
break
|
||||
# 无新进度时避免死循环
|
||||
if after is not None and str(oldest_ts) == after:
|
||||
if history_url and not switched_history:
|
||||
active_url = history_url
|
||||
switched_history = True
|
||||
time.sleep(max(history_page_pause_sec, 0.35))
|
||||
continue
|
||||
break
|
||||
after = str(oldest_ts)
|
||||
# 近期接口返回变少且仍未覆盖 since → 切历史
|
||||
if (
|
||||
history_url
|
||||
and not switched_history
|
||||
and len(data) < 100
|
||||
and oldest_ts > since_ms
|
||||
):
|
||||
active_url = history_url
|
||||
switched_history = True
|
||||
time.sleep(max(history_page_pause_sec, 0.35))
|
||||
return [out[k] for k in sorted(out.keys())]
|
||||
finally:
|
||||
if own:
|
||||
client.close()
|
||||
|
||||
|
||||
def fetch_symbol_bars(
|
||||
symbol: str,
|
||||
*,
|
||||
since_ms: int,
|
||||
until_ms: int,
|
||||
fetch_fn: Optional[Callable[..., list[dict[str, Any]]]] = None,
|
||||
) -> tuple[list[dict[str, Any]], str, str]:
|
||||
"""返回 (bars, price_source_label, inst_id)."""
|
||||
key = normalize_symbol(symbol)
|
||||
meta = SYMBOLS[key]
|
||||
if fetch_fn:
|
||||
bars = fetch_fn(inst_id=meta["index_inst"], since_ms=since_ms, until_ms=until_ms)
|
||||
return bars, f"okx_index:{meta['index_inst']}", meta["index_inst"]
|
||||
|
||||
index_err: Optional[BaseException] = None
|
||||
try:
|
||||
bars = fetch_okx_candles(
|
||||
url=OKX_INDEX_CANDLES,
|
||||
history_url=OKX_HISTORY_INDEX_CANDLES,
|
||||
inst_id=meta["index_inst"],
|
||||
since_ms=since_ms,
|
||||
until_ms=until_ms,
|
||||
)
|
||||
if bars:
|
||||
return bars, f"okx_index:{meta['index_inst']}", meta["index_inst"]
|
||||
except Exception as exc:
|
||||
index_err = exc
|
||||
# 指数侧已触发限频时先冷却,再降级永续,避免连环 429
|
||||
time.sleep(1.2)
|
||||
|
||||
try:
|
||||
bars = fetch_okx_candles(
|
||||
url=OKX_SWAP_CANDLES,
|
||||
history_url=OKX_HISTORY_SWAP_CANDLES,
|
||||
inst_id=meta["swap_inst"],
|
||||
since_ms=since_ms,
|
||||
until_ms=until_ms,
|
||||
)
|
||||
except Exception as exc:
|
||||
detail = f"index={index_err}; swap={exc}" if index_err else str(exc)
|
||||
raise RuntimeError(f"OKX K线拉取失败({detail})") from exc
|
||||
if not bars:
|
||||
detail = f"index={index_err}" if index_err else "empty"
|
||||
raise RuntimeError(f"OKX 指数与永续 K 线均无数据({detail})")
|
||||
return bars, f"okx_swap:{meta['swap_inst']}", meta["swap_inst"]
|
||||
|
||||
|
||||
def compute_amp_stats(
|
||||
*,
|
||||
symbol: str = "eth",
|
||||
start_hour: int = 16,
|
||||
period: str = "2m",
|
||||
custom_days: Any = None,
|
||||
straddle_premium: Any = None,
|
||||
take_profit: Any = None,
|
||||
weekend_filter: Any = "all",
|
||||
now: Optional[datetime] = None,
|
||||
fetch_fn: Optional[Callable[..., list[dict[str, Any]]]] = None,
|
||||
) -> dict[str, Any]:
|
||||
key = normalize_symbol(symbol)
|
||||
sh = int(start_hour)
|
||||
if sh < 0 or sh > 23:
|
||||
raise ValueError("起点须为 0-23 整点")
|
||||
prem = normalize_straddle_premium(straddle_premium)
|
||||
tp = normalize_take_profit(take_profit)
|
||||
we_mode = normalize_weekend_filter(weekend_filter)
|
||||
sample_days = resolve_sample_days(period, custom_days)
|
||||
settlements = list_settlement_dates(sample_days=sample_days, now=now)
|
||||
if not settlements:
|
||||
raise RuntimeError("无可用结算日")
|
||||
# 最远窗起点
|
||||
oldest = settlements[-1]
|
||||
newest = settlements[0]
|
||||
start0, _ = window_bounds_for_settlement(oldest, sh)
|
||||
_, end1 = window_bounds_for_settlement(newest, sh)
|
||||
since_ms = int(start0.timestamp() * 1000)
|
||||
until_ms = int(end1.timestamp() * 1000)
|
||||
bars, price_source, inst_id = fetch_symbol_bars(
|
||||
key, since_ms=since_ms, until_ms=until_ms, fetch_fn=fetch_fn
|
||||
)
|
||||
bar_map = bars_to_map(bars)
|
||||
rows_all: list[dict[str, Any]] = []
|
||||
missing: list[str] = []
|
||||
for d in settlements:
|
||||
row = compute_day_row(d, sh, bar_map)
|
||||
if row is None:
|
||||
missing.append(d.isoformat())
|
||||
continue
|
||||
rows_all.append(row)
|
||||
return build_amp_result(
|
||||
rows_all=rows_all,
|
||||
symbol_key=key,
|
||||
start_hour=sh,
|
||||
period=period,
|
||||
sample_days=sample_days,
|
||||
straddle_premium=prem,
|
||||
take_profit=tp,
|
||||
weekend_filter=we_mode,
|
||||
price_source=price_source,
|
||||
inst_id=inst_id,
|
||||
missing=missing,
|
||||
)
|
||||
|
||||
|
||||
def build_amp_result(
|
||||
*,
|
||||
rows_all: list[dict[str, Any]],
|
||||
symbol_key: str,
|
||||
start_hour: int,
|
||||
period: str,
|
||||
sample_days: int,
|
||||
straddle_premium: Any = None,
|
||||
take_profit: Any = None,
|
||||
weekend_filter: Any = "all",
|
||||
price_source: str = "",
|
||||
inst_id: str = "",
|
||||
missing: Optional[list[str]] = None,
|
||||
) -> dict[str, Any]:
|
||||
prem = normalize_straddle_premium(straddle_premium)
|
||||
tp = normalize_take_profit(take_profit)
|
||||
we_mode = normalize_weekend_filter(weekend_filter)
|
||||
filtered = filter_weekend_rows(rows_all, we_mode)
|
||||
rows = enrich_rows_pnl(filtered, straddle_premium=prem, take_profit=tp)
|
||||
summary = summarize_rows(rows, straddle_premium=prem, take_profit=tp)
|
||||
if period == "custom" or str(period).startswith("custom:"):
|
||||
period_label = period if str(period).startswith("custom:") else f"custom:{sample_days}"
|
||||
else:
|
||||
period_label = str(period)
|
||||
miss = missing or []
|
||||
return {
|
||||
"ok": True,
|
||||
"exchange": EXCHANGE,
|
||||
"symbol": symbol_key,
|
||||
"symbol_label": SYMBOLS[symbol_key]["label"],
|
||||
"start_hour": start_hour,
|
||||
"end_hour": END_HOUR,
|
||||
"period": period_label,
|
||||
"sample_days_requested": sample_days,
|
||||
"straddle_premium": prem,
|
||||
"take_profit": tp,
|
||||
"weekend_filter": we_mode,
|
||||
"timeframe": TIMEFRAME,
|
||||
"price_source": price_source,
|
||||
"inst_id": inst_id,
|
||||
"timezone": "Asia/Shanghai",
|
||||
"rows_all": rows_all,
|
||||
"rows": rows,
|
||||
"summary": summary,
|
||||
"missing_days": miss[:30],
|
||||
"missing_count": len(miss),
|
||||
}
|
||||
|
||||
|
||||
def reframe_amp_stats(
|
||||
*,
|
||||
rows_all: list[dict[str, Any]],
|
||||
symbol: str = "eth",
|
||||
start_hour: int = 16,
|
||||
period: str = "2m",
|
||||
sample_days: int = 60,
|
||||
straddle_premium: Any = None,
|
||||
take_profit: Any = None,
|
||||
weekend_filter: Any = "all",
|
||||
price_source: str = "",
|
||||
inst_id: str = "",
|
||||
missing: Optional[list[str]] = None,
|
||||
) -> dict[str, Any]:
|
||||
"""已有日表上改周末/权利金/止盈,不拉 K 线."""
|
||||
key = normalize_symbol(symbol)
|
||||
return build_amp_result(
|
||||
rows_all=list(rows_all or []),
|
||||
symbol_key=key,
|
||||
start_hour=int(start_hour),
|
||||
period=period,
|
||||
sample_days=int(sample_days or 60),
|
||||
straddle_premium=straddle_premium,
|
||||
take_profit=take_profit,
|
||||
weekend_filter=weekend_filter,
|
||||
price_source=price_source,
|
||||
inst_id=inst_id,
|
||||
missing=missing,
|
||||
)
|
||||
|
||||
|
||||
def rows_page(rows: list[dict[str, Any]], *, page: int = 1, page_size: int = 20) -> dict[str, Any]:
|
||||
page = max(1, int(page or 1))
|
||||
page_size = max(5, min(100, int(page_size or 20)))
|
||||
total = len(rows)
|
||||
start = (page - 1) * page_size
|
||||
chunk = rows[start : start + page_size]
|
||||
return {
|
||||
"page": page,
|
||||
"page_size": page_size,
|
||||
"total": total,
|
||||
"total_pages": max(1, (total + page_size - 1) // page_size) if total else 1,
|
||||
"rows": chunk,
|
||||
}
|
||||
|
||||
|
||||
def build_export_csv(payload: dict[str, Any]) -> str:
|
||||
buf = io.StringIO()
|
||||
# Excel 友好 BOM
|
||||
buf.write("\ufeff")
|
||||
w = csv.writer(buf)
|
||||
s = payload.get("summary") or {}
|
||||
w.writerow(["【统计摘要】"])
|
||||
w.writerow(["交易所", payload.get("exchange")])
|
||||
w.writerow(["标的", payload.get("symbol_label")])
|
||||
w.writerow(["价源", payload.get("price_source")])
|
||||
w.writerow(["起点整点", f"{payload.get('start_hour')}:00"])
|
||||
w.writerow(["终点", f"{payload.get('end_hour')}:00"])
|
||||
w.writerow(["周期", payload.get("period")])
|
||||
w.writerow(["周末筛选", payload.get("weekend_filter")])
|
||||
w.writerow(["样本数", s.get("sample_count")])
|
||||
w.writerow(["最大振幅", s.get("max_amplitude"), "日期", s.get("max_amplitude_day")])
|
||||
w.writerow(["振幅均值", s.get("avg_amplitude"), "中位数", s.get("median_amplitude")])
|
||||
w.writerow(["开→高最大", s.get("max_up_points"), "均值", s.get("avg_up_points")])
|
||||
w.writerow(["开→低最大", s.get("max_down_points"), "均值", s.get("avg_down_points")])
|
||||
w.writerow(["上涨窗占比", s.get("up_day_ratio"), "下跌窗占比", s.get("down_day_ratio")])
|
||||
st = s.get("straddle") or {}
|
||||
if st:
|
||||
w.writerow([])
|
||||
w.writerow(["【买跨对照·双边权利金】", st.get("premium"), "止盈点", st.get("take_profit")])
|
||||
w.writerow(["开→高超过权利金", st.get("up_exceed_days"), "占比", st.get("up_exceed_ratio")])
|
||||
w.writerow(["开→低超过权利金", st.get("down_exceed_days"), "占比", st.get("down_exceed_ratio")])
|
||||
w.writerow(["|涨跌|超过权利金", st.get("abs_change_exceed_days"), "占比", st.get("abs_change_exceed_ratio")])
|
||||
if st.get("take_profit") is not None:
|
||||
w.writerow(["触达止盈天数", st.get("tp_hit_days"), "占比", st.get("tp_hit_ratio")])
|
||||
w.writerow(
|
||||
[
|
||||
"买跨点数盈亏合计",
|
||||
st.get("pnl_total"),
|
||||
"日均",
|
||||
st.get("pnl_avg"),
|
||||
"赚钱天数",
|
||||
st.get("win_days"),
|
||||
"胜率",
|
||||
st.get("win_ratio"),
|
||||
]
|
||||
)
|
||||
w.writerow(["单日最大赚", st.get("pnl_max"), "单日最大亏", st.get("pnl_min")])
|
||||
w.writerow([])
|
||||
w.writerow(["【日表明细】"])
|
||||
w.writerow(
|
||||
[
|
||||
"结算日",
|
||||
"星期",
|
||||
"周末",
|
||||
"窗起点",
|
||||
"窗终点",
|
||||
"开盘",
|
||||
"最高",
|
||||
"最低",
|
||||
"收盘",
|
||||
"开→高",
|
||||
"开→低",
|
||||
"振幅",
|
||||
"涨跌值",
|
||||
"有效波动",
|
||||
"触达止盈",
|
||||
"收益",
|
||||
]
|
||||
)
|
||||
for r in payload.get("rows") or []:
|
||||
w.writerow(
|
||||
[
|
||||
r.get("settlement_day"),
|
||||
r.get("weekday_label") or "",
|
||||
"是" if r.get("is_weekend") else "否",
|
||||
r.get("window_start"),
|
||||
r.get("window_end"),
|
||||
r.get("open"),
|
||||
r.get("high"),
|
||||
r.get("low"),
|
||||
r.get("close"),
|
||||
r.get("up_points"),
|
||||
r.get("down_points"),
|
||||
r.get("amplitude"),
|
||||
r.get("change"),
|
||||
r.get("effective_move"),
|
||||
"是" if r.get("take_profit_hit") else "否",
|
||||
r.get("profit"),
|
||||
]
|
||||
)
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
def export_filename(payload: dict[str, Any]) -> str:
|
||||
sym = (payload.get("symbol") or "eth").lower()
|
||||
sh = int(payload.get("start_hour") or 16)
|
||||
period = str(payload.get("period") or "2m").replace(":", "")
|
||||
day = datetime.now(APP_TZ).strftime("%Y%m%d")
|
||||
return f"okx_{sym}_amp_{sh}to16_{period}_{day}.csv"
|
||||
@@ -61,6 +61,7 @@ def install_instance_theme_static(app) -> None:
|
||||
"records_review_page.js": "application/javascript; charset=utf-8",
|
||||
"ai_review_render.js": "application/javascript; charset=utf-8",
|
||||
"form_submit_guard.js": "application/javascript; charset=utf-8",
|
||||
"autofill_guard.js": "application/javascript; charset=utf-8",
|
||||
"key_monitor_form.js": "application/javascript; charset=utf-8",
|
||||
"time_close_ui.js": "application/javascript; charset=utf-8",
|
||||
"manual_order_rr_preview.js": "application/javascript; charset=utf-8",
|
||||
@@ -70,6 +71,7 @@ def install_instance_theme_static(app) -> None:
|
||||
"strategy_roll.js": "application/javascript; charset=utf-8",
|
||||
"instance_page.css": "text/css; charset=utf-8",
|
||||
"instance_embed.js": "application/javascript; charset=utf-8",
|
||||
"instance_mobile_nav.js": "application/javascript; charset=utf-8",
|
||||
"instance_stats.js": "application/javascript; charset=utf-8",
|
||||
"instance_live.js": "application/javascript; charset=utf-8",
|
||||
"instance_settings_prefs.js": "application/javascript; charset=utf-8",
|
||||
@@ -671,6 +673,72 @@ def register_hub_routes(app):
|
||||
}
|
||||
)
|
||||
|
||||
@app.route("/api/hub/options/review/archive")
|
||||
@_hub_auth_required
|
||||
def api_hub_options_review_archive():
|
||||
"""中控期权档案:近 N 天已平仓复盘记录(默认排除对冲腿)."""
|
||||
from datetime import datetime, timedelta
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from flask import current_app
|
||||
|
||||
from lib.options.options_review_lib import (
|
||||
compute_review_stats,
|
||||
ensure_local_review_synced,
|
||||
list_review_trades,
|
||||
)
|
||||
|
||||
c = _ctx()
|
||||
get_db = c.get("get_db")
|
||||
if not get_db:
|
||||
return jsonify({"ok": False, "msg": "HUB_CTX 缺少 get_db"}), 500
|
||||
try:
|
||||
days = int(request.args.get("days") or "365")
|
||||
except ValueError:
|
||||
days = 365
|
||||
days = max(1, min(days, 3650))
|
||||
try:
|
||||
limit = int(request.args.get("limit") or "2000")
|
||||
except ValueError:
|
||||
limit = 2000
|
||||
limit = max(1, min(limit, 5000))
|
||||
include_hedge_legs = str(request.args.get("include_hedge_legs") or "").strip() in (
|
||||
"1",
|
||||
"true",
|
||||
"yes",
|
||||
)
|
||||
tz = ZoneInfo("Asia/Shanghai")
|
||||
closed_from = (datetime.now(tz) - timedelta(days=days)).strftime("%Y-%m-%d")
|
||||
cfg = (current_app.extensions or {}).get("options_cfg") or {}
|
||||
ex = cfg.get("exchange_options")
|
||||
conn = get_db()
|
||||
try:
|
||||
ensure_local_review_synced(conn, ex=ex, backfill_exchange_pnl=bool(ex))
|
||||
trades = list_review_trades(
|
||||
conn,
|
||||
include_hedge_legs=include_hedge_legs,
|
||||
closed_from=closed_from,
|
||||
limit=limit,
|
||||
offset=0,
|
||||
)
|
||||
stats = compute_review_stats(
|
||||
conn,
|
||||
include_hedge_legs=include_hedge_legs,
|
||||
closed_from=closed_from,
|
||||
)
|
||||
finally:
|
||||
conn.close()
|
||||
return jsonify(
|
||||
{
|
||||
"ok": True,
|
||||
"days": days,
|
||||
"limit": limit,
|
||||
"product": "options",
|
||||
"trades": trades,
|
||||
"stats": stats,
|
||||
}
|
||||
)
|
||||
|
||||
@app.route("/api/hub/trades/today")
|
||||
@_hub_auth_required
|
||||
def api_hub_trades_today():
|
||||
|
||||
@@ -0,0 +1,400 @@
|
||||
"""中控策略对比:同风险额下 合约 / 单期权 / 期期7:3 情景测算(纯函数)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
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 default_contract_size(base: str) -> float:
|
||||
"""OKX 线性永续常用面值(币/张);与计算器缺省一致."""
|
||||
b = (base or "ETH").strip().upper()
|
||||
return 0.01
|
||||
|
||||
|
||||
def default_ct_mult(base: str) -> float:
|
||||
return 0.01
|
||||
|
||||
|
||||
def floor_sheets(n: float, step: float = 1.0) -> float:
|
||||
if n is None or not math.isfinite(n) or n <= 0:
|
||||
return 0.0
|
||||
s = float(step) if step and step > 0 else 1.0
|
||||
return math.floor(n / s + 1e-12) * s
|
||||
|
||||
|
||||
def option_unit_cost(*, ask: float, ct_mult: float) -> float:
|
||||
return float(ask) * float(ct_mult or 0.01)
|
||||
|
||||
|
||||
def option_intrinsic_value(
|
||||
*,
|
||||
opt_type: str,
|
||||
strike: float,
|
||||
spot: float,
|
||||
sheets: float,
|
||||
ct_mult: float,
|
||||
) -> float:
|
||||
o = (opt_type or "").strip().upper()
|
||||
k = float(strike)
|
||||
s = float(spot)
|
||||
if o == "C":
|
||||
intrinsic = max(0.0, s - k)
|
||||
elif o == "P":
|
||||
intrinsic = max(0.0, k - s)
|
||||
else:
|
||||
intrinsic = 0.0
|
||||
return intrinsic * float(sheets) * float(ct_mult or 0.01)
|
||||
|
||||
|
||||
def option_pnl_at_spot(
|
||||
*,
|
||||
opt_type: str,
|
||||
strike: float,
|
||||
spot: float,
|
||||
sheets: float,
|
||||
ct_mult: float,
|
||||
premium_paid: float,
|
||||
) -> float:
|
||||
return option_intrinsic_value(
|
||||
opt_type=opt_type,
|
||||
strike=strike,
|
||||
spot=spot,
|
||||
sheets=sheets,
|
||||
ct_mult=ct_mult,
|
||||
) - float(premium_paid)
|
||||
|
||||
|
||||
def perp_pnl(
|
||||
*,
|
||||
direction: str,
|
||||
entry: float,
|
||||
exit_px: float,
|
||||
contracts: float,
|
||||
contract_size: float,
|
||||
) -> float:
|
||||
coins = float(contracts) * float(contract_size or 0.01)
|
||||
d = (direction or "long").strip().lower()
|
||||
if d == "short":
|
||||
return (float(entry) - float(exit_px)) * coins
|
||||
return (float(exit_px) - float(entry)) * coins
|
||||
|
||||
|
||||
def _validate_common(inp: dict[str, Any]) -> Optional[str]:
|
||||
base = str(inp.get("base") or "ETH").strip().upper()
|
||||
if base not in ("ETH", "BTC"):
|
||||
return "标的仅支持 ETH / BTC"
|
||||
direction = str(inp.get("direction") or "long").strip().lower()
|
||||
if direction not in ("long", "short"):
|
||||
return "方向须为 long / short"
|
||||
s0 = _f(inp.get("entry"))
|
||||
sl = _f(inp.get("sl"))
|
||||
tp = _f(inp.get("tp"))
|
||||
risk = _f(inp.get("risk_u"))
|
||||
if s0 is None or s0 <= 0:
|
||||
return "请填写有效入场价"
|
||||
if sl is None or sl <= 0:
|
||||
return "请填写有效止损价"
|
||||
if tp is None or tp <= 0:
|
||||
return "请填写有效止盈价"
|
||||
if risk is None or risk <= 0:
|
||||
return "请填写有效风险额 R"
|
||||
if direction == "long" and not (sl < s0 < tp):
|
||||
return "做多须满足 止损 < 入场 < 止盈"
|
||||
if direction == "short" and not (tp < s0 < sl):
|
||||
return "做空须满足 止盈 < 入场 < 止损"
|
||||
return None
|
||||
|
||||
|
||||
def _calc_perp(inp: dict[str, Any], *, contract_size: float) -> dict[str, Any]:
|
||||
direction = str(inp.get("direction") or "long").strip().lower()
|
||||
s0 = float(inp["entry"])
|
||||
sl = float(inp["sl"])
|
||||
tp = float(inp["tp"])
|
||||
risk = float(inp["risk_u"])
|
||||
per_sheet_sl = abs(s0 - sl) * contract_size
|
||||
sheets = floor_sheets(risk / per_sheet_sl) if per_sheet_sl > 0 else 0.0
|
||||
actual_sl_loss = abs(perp_pnl(
|
||||
direction=direction, entry=s0, exit_px=sl, contracts=sheets, contract_size=contract_size
|
||||
))
|
||||
tp_pnl = perp_pnl(
|
||||
direction=direction, entry=s0, exit_px=tp, contracts=sheets, contract_size=contract_size
|
||||
)
|
||||
# 路径 C:本单已止损 −actual;踏空未拿到 = 原止盈盈利
|
||||
path_a = round(tp_pnl, 4)
|
||||
path_b = round(-actual_sl_loss if sheets > 0 else -risk, 4)
|
||||
path_c_realized = path_b
|
||||
path_c_missed = path_a
|
||||
return {
|
||||
"kind": "perp",
|
||||
"sheets": sheets,
|
||||
"contract_size": contract_size,
|
||||
"per_sheet_sl_u": round(per_sheet_sl, 6),
|
||||
"risk_used_u": round(actual_sl_loss, 4),
|
||||
"path_a_tp": path_a,
|
||||
"path_b_sl": path_b,
|
||||
"path_c_realized": path_c_realized,
|
||||
"path_c_missed": path_c_missed,
|
||||
"path_c_note": "本单已止损;踏空未拿到原止盈空间",
|
||||
"worst_u": path_b,
|
||||
}
|
||||
|
||||
|
||||
def _calc_single_option(inp: dict[str, Any], *, ct_mult: float) -> dict[str, Any]:
|
||||
direction = str(inp.get("direction") or "long").strip().lower()
|
||||
risk = float(inp["risk_u"])
|
||||
tp = float(inp.get("tp_opt") if inp.get("tp_opt") not in (None, "") else inp["tp"])
|
||||
sl = float(inp["sl"])
|
||||
opt = inp.get("option") if isinstance(inp.get("option"), dict) else {}
|
||||
default_type = "C" if direction == "long" else "P"
|
||||
opt_type = str(opt.get("opt_type") or default_type).strip().upper()
|
||||
if opt_type not in ("C", "P"):
|
||||
opt_type = default_type
|
||||
strike = _f(opt.get("strike"))
|
||||
ask = _f(opt.get("ask"))
|
||||
if strike is None or strike <= 0:
|
||||
return {"ok": False, "msg": "请填写单期权行权价"}
|
||||
if ask is None or ask <= 0:
|
||||
return {"ok": False, "msg": "请填写单期权卖一价"}
|
||||
unit = option_unit_cost(ask=ask, ct_mult=ct_mult)
|
||||
sheets = floor_sheets(risk / unit) if unit > 0 else 0.0
|
||||
premium = option_unit_cost(ask=ask, ct_mult=ct_mult) * sheets if sheets else 0.0
|
||||
# 若张数为 0
|
||||
path_a = option_pnl_at_spot(
|
||||
opt_type=opt_type, strike=strike, spot=tp, sheets=sheets, ct_mult=ct_mult, premium_paid=premium
|
||||
)
|
||||
path_b_at_sl = option_pnl_at_spot(
|
||||
opt_type=opt_type, strike=strike, spot=sl, sheets=sheets, ct_mult=ct_mult, premium_paid=premium
|
||||
)
|
||||
path_b_worst = -premium
|
||||
# 踏空路径:合约被洗后标的仍到 TP,期权仍持有 → 同止盈
|
||||
path_c = path_a
|
||||
return {
|
||||
"ok": True,
|
||||
"kind": "option",
|
||||
"opt_type": opt_type,
|
||||
"strike": strike,
|
||||
"ask": ask,
|
||||
"ct_mult": ct_mult,
|
||||
"sheets": sheets,
|
||||
"unit_cost_u": round(unit, 6),
|
||||
"premium_u": round(premium, 4),
|
||||
"path_a_tp": round(path_a, 4),
|
||||
"path_b_sl": round(path_b_at_sl, 4),
|
||||
"path_b_worst": round(path_b_worst, 4),
|
||||
"path_c_hold_to_tp": round(path_c, 4),
|
||||
"path_c_note": "合约踏空路径下期权仍持有至目标价(内在近似)",
|
||||
"worst_u": round(path_b_worst, 4),
|
||||
}
|
||||
|
||||
|
||||
def _calc_hedge(inp: dict[str, Any], *, ct_mult: float) -> dict[str, Any]:
|
||||
direction = str(inp.get("direction") or "long").strip().lower()
|
||||
risk = float(inp["risk_u"])
|
||||
tp = float(inp.get("tp_hedge") if inp.get("tp_hedge") not in (None, "") else inp["tp"])
|
||||
sl = float(inp["sl"])
|
||||
hedge = inp.get("hedge") if isinstance(inp.get("hedge"), dict) else {}
|
||||
main_default = "C" if direction == "long" else "P"
|
||||
side_default = "P" if direction == "long" else "C"
|
||||
main = hedge.get("main") if isinstance(hedge.get("main"), dict) else {}
|
||||
side = hedge.get("side") if isinstance(hedge.get("side"), dict) else {}
|
||||
main_type = str(main.get("opt_type") or main_default).strip().upper()
|
||||
side_type = str(side.get("opt_type") or side_default).strip().upper()
|
||||
if main_type not in ("C", "P"):
|
||||
main_type = main_default
|
||||
if side_type not in ("C", "P"):
|
||||
side_type = side_default
|
||||
main_k = _f(main.get("strike"))
|
||||
main_ask = _f(main.get("ask"))
|
||||
side_k = _f(side.get("strike"))
|
||||
side_ask = _f(side.get("ask"))
|
||||
if None in (main_k, main_ask, side_k, side_ask) or min(
|
||||
main_k or 0, main_ask or 0, side_k or 0, side_ask or 0
|
||||
) <= 0:
|
||||
return {"ok": False, "msg": "请填写期期对冲两腿的行权价与卖一"}
|
||||
main_budget = 0.7 * risk
|
||||
side_budget = 0.3 * risk
|
||||
main_unit = option_unit_cost(ask=float(main_ask), ct_mult=ct_mult)
|
||||
side_unit = option_unit_cost(ask=float(side_ask), ct_mult=ct_mult)
|
||||
main_sheets = floor_sheets(main_budget / main_unit) if main_unit > 0 else 0.0
|
||||
side_sheets = floor_sheets(side_budget / side_unit) if side_unit > 0 else 0.0
|
||||
main_prem = main_unit * main_sheets
|
||||
side_prem = side_unit * side_sheets
|
||||
premium = main_prem + side_prem
|
||||
|
||||
def combo_at(spot: float) -> float:
|
||||
a = option_pnl_at_spot(
|
||||
opt_type=main_type,
|
||||
strike=float(main_k),
|
||||
spot=spot,
|
||||
sheets=main_sheets,
|
||||
ct_mult=ct_mult,
|
||||
premium_paid=main_prem,
|
||||
)
|
||||
b = option_pnl_at_spot(
|
||||
opt_type=side_type,
|
||||
strike=float(side_k),
|
||||
spot=spot,
|
||||
sheets=side_sheets,
|
||||
ct_mult=ct_mult,
|
||||
premium_paid=side_prem,
|
||||
)
|
||||
return a + b
|
||||
|
||||
path_a = combo_at(tp)
|
||||
path_b_at_sl = combo_at(sl)
|
||||
path_b_worst = -premium
|
||||
path_c = path_a
|
||||
return {
|
||||
"ok": True,
|
||||
"kind": "hedge",
|
||||
"ratio": "7:3",
|
||||
"ct_mult": ct_mult,
|
||||
"main": {
|
||||
"opt_type": main_type,
|
||||
"strike": main_k,
|
||||
"ask": main_ask,
|
||||
"sheets": main_sheets,
|
||||
"premium_u": round(main_prem, 4),
|
||||
"budget_u": round(main_budget, 4),
|
||||
},
|
||||
"side": {
|
||||
"opt_type": side_type,
|
||||
"strike": side_k,
|
||||
"ask": side_ask,
|
||||
"sheets": side_sheets,
|
||||
"premium_u": round(side_prem, 4),
|
||||
"budget_u": round(side_budget, 4),
|
||||
},
|
||||
"premium_u": round(premium, 4),
|
||||
"path_a_tp": round(path_a, 4),
|
||||
"path_b_sl": round(path_b_at_sl, 4),
|
||||
"path_b_worst": round(path_b_worst, 4),
|
||||
"path_c_hold_to_tp": round(path_c, 4),
|
||||
"path_c_note": "合约踏空路径下对冲组合仍持有至目标价(内在近似)",
|
||||
"worst_u": round(path_b_worst, 4),
|
||||
}
|
||||
|
||||
|
||||
def recommend(perp: dict[str, Any], opt: dict[str, Any], hedge: dict[str, Any], risk: float) -> dict[str, Any]:
|
||||
"""可解释规则推荐."""
|
||||
candidates: list[tuple[str, float, dict[str, Any]]] = []
|
||||
if perp and perp.get("sheets", 0) > 0:
|
||||
candidates.append(("合约", float(perp.get("path_a_tp") or 0), perp))
|
||||
if opt and opt.get("ok") and opt.get("sheets", 0) > 0:
|
||||
candidates.append(("单期权", float(opt.get("path_a_tp") or 0), opt))
|
||||
if hedge and hedge.get("ok") and (hedge.get("premium_u") or 0) > 0:
|
||||
candidates.append(("期期对冲", float(hedge.get("path_a_tp") or 0), hedge))
|
||||
if not candidates:
|
||||
return {
|
||||
"choice": "—",
|
||||
"reason": "输入不足,无法推荐",
|
||||
"bullets": ["请检查风险额与卖一/止损距是否过小导致张数为 0"],
|
||||
}
|
||||
|
||||
best_name, best_a, _ = max(candidates, key=lambda x: x[1])
|
||||
perp_a = float(perp.get("path_a_tp") or 0) if perp else 0.0
|
||||
opt_a = float(opt.get("path_a_tp") or 0) if opt and opt.get("ok") else 0.0
|
||||
hedge_a = float(hedge.get("path_a_tp") or 0) if hedge and hedge.get("ok") else 0.0
|
||||
|
||||
# 踏空:合约 C 实现为亏损,期权/对冲 C 仍接近 A
|
||||
perp_miss = float(perp.get("path_c_missed") or 0) if perp else 0.0
|
||||
opt_c = float(opt.get("path_c_hold_to_tp") or 0) if opt and opt.get("ok") else None
|
||||
hedge_c = float(hedge.get("path_c_hold_to_tp") or 0) if hedge and hedge.get("ok") else None
|
||||
anti_whipsaw = False
|
||||
if perp_miss > 0 and (
|
||||
(opt_c is not None and opt_c > 0) or (hedge_c is not None and hedge_c > 0)
|
||||
):
|
||||
anti_whipsaw = True
|
||||
|
||||
# 合约止盈明显更高(>= 另两者 1.15 倍)且用户能接受踏空 → 推合约
|
||||
others_max = max(opt_a, hedge_a, 0.0)
|
||||
choice = best_name
|
||||
if perp_a > 0 and perp_a >= others_max * 1.15 and perp_a >= best_a * 0.99:
|
||||
choice = "合约"
|
||||
if anti_whipsaw:
|
||||
reason = "合约止盈赔付更高,但震荡易洗时存在踏空;能接受洗盘再走可选合约"
|
||||
else:
|
||||
reason = "同风险下合约干净止盈赔付最高"
|
||||
elif anti_whipsaw and (opt_a > 0 or hedge_a > 0):
|
||||
# 抗踏空优先期权类;期期与单腿接近时推期期
|
||||
if hedge_a > 0 and (opt_a <= 0 or hedge_a >= opt_a * 0.85):
|
||||
choice = "期期对冲"
|
||||
reason = "震荡易洗时期权类更抗踏空;期期 7:3 兼顾方向与保护"
|
||||
else:
|
||||
choice = "单期权"
|
||||
reason = "震荡易洗时单期权仍可持有到目标,抗踏空优于合约"
|
||||
else:
|
||||
reason = f"同风险下「{best_name}」干净止盈赔付最高"
|
||||
|
||||
bullets = [
|
||||
f"止盈对比:合约 {perp_a:.2f}U / 单期权 {opt_a:.2f}U / 期期 {hedge_a:.2f}U(风险 R={risk:.2f}U)",
|
||||
(
|
||||
"止损与踏空:合约打止损即结束并可能踏空;"
|
||||
"期权/对冲最坏约亏满权利金,踏空路径下常仍持有至目标"
|
||||
if anti_whipsaw
|
||||
else "止损与踏空:三者最坏接近 −R;关注合约是否易被洗后错过止盈"
|
||||
),
|
||||
f"选用建议:{reason}",
|
||||
]
|
||||
return {"choice": choice, "reason": reason, "bullets": bullets}
|
||||
|
||||
|
||||
def run_compare(inp: dict[str, Any]) -> dict[str, Any]:
|
||||
err = _validate_common(inp)
|
||||
if err:
|
||||
return {"ok": False, "msg": err}
|
||||
base = str(inp.get("base") or "ETH").strip().upper()
|
||||
risk = float(inp["risk_u"])
|
||||
cs = _f(inp.get("contract_size")) or default_contract_size(base)
|
||||
ct = _f(inp.get("ct_mult")) or default_ct_mult(base)
|
||||
perp = _calc_perp(inp, contract_size=float(cs))
|
||||
opt = _calc_single_option(inp, ct_mult=float(ct))
|
||||
hedge = _calc_hedge(inp, ct_mult=float(ct))
|
||||
rec = recommend(
|
||||
perp,
|
||||
opt if opt.get("ok") else {"ok": False},
|
||||
hedge if hedge.get("ok") else {"ok": False},
|
||||
risk,
|
||||
)
|
||||
warnings: list[str] = []
|
||||
if perp.get("sheets", 0) <= 0:
|
||||
warnings.append("合约张数为 0:止损距过大或 R 过小")
|
||||
if isinstance(opt, dict) and opt.get("ok") and opt.get("sheets", 0) <= 0:
|
||||
warnings.append("单期权张数为 0:卖一过高或 R 过小")
|
||||
if isinstance(hedge, dict) and hedge.get("ok") and hedge.get("premium_u", 0) <= 0:
|
||||
warnings.append("期期对冲未开出张数:卖一过高或 R 过小")
|
||||
if isinstance(opt, dict) and not opt.get("ok"):
|
||||
warnings.append(str(opt.get("msg") or "单期权输入不完整"))
|
||||
if isinstance(hedge, dict) and not hedge.get("ok"):
|
||||
warnings.append(str(hedge.get("msg") or "期期对冲输入不完整"))
|
||||
return {
|
||||
"ok": True,
|
||||
"base": base,
|
||||
"direction": str(inp.get("direction") or "long").strip().lower(),
|
||||
"entry": float(inp["entry"]),
|
||||
"sl": float(inp["sl"]),
|
||||
"tp": float(inp["tp"]),
|
||||
"risk_u": risk,
|
||||
"contract_size": float(cs),
|
||||
"ct_mult": float(ct),
|
||||
"perp": perp,
|
||||
"option": opt,
|
||||
"hedge": hedge,
|
||||
"recommend": rec,
|
||||
"warnings": warnings,
|
||||
"notes": [
|
||||
"期权止盈按标的到价的内在价值近似,非盘口卖出价",
|
||||
"到期小盈/小亏未纳入主表与推荐",
|
||||
"仅本地测算,不下单",
|
||||
],
|
||||
}
|
||||
@@ -0,0 +1,599 @@
|
||||
"""中控期权档案:同步 OKX options_review_trades 到 hub_symbol_archive.db."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from lib.hub.hub_symbol_archive_lib import (
|
||||
TRADING_DAY_RESET_HOUR,
|
||||
_connect,
|
||||
default_db_path,
|
||||
init_db as init_perp_archive_db,
|
||||
ms_to_trading_day,
|
||||
parse_wall_clock_ms,
|
||||
resolve_period_bounds,
|
||||
trading_day_bounds_ms,
|
||||
)
|
||||
|
||||
|
||||
def _now_ms() -> int:
|
||||
return int(time.time() * 1000)
|
||||
|
||||
|
||||
def init_options_archive_db(db_path: Path | None = None) -> None:
|
||||
"""确保期权缓存表存在(与永续共用同一 SQLite)."""
|
||||
init_perp_archive_db(db_path)
|
||||
conn = _connect(db_path)
|
||||
try:
|
||||
conn.execute(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS archive_options_trade_cache (
|
||||
exchange_key TEXT NOT NULL,
|
||||
history_key TEXT NOT NULL,
|
||||
source_type TEXT,
|
||||
underlying TEXT,
|
||||
opened_at TEXT,
|
||||
closed_at TEXT,
|
||||
opened_at_ms INTEGER,
|
||||
closed_at_ms INTEGER,
|
||||
hold_seconds INTEGER,
|
||||
realized_pnl_total REAL,
|
||||
status_raw TEXT,
|
||||
pos_id TEXT,
|
||||
inst_id TEXT,
|
||||
opt_type TEXT,
|
||||
strike REAL,
|
||||
exp_time TEXT,
|
||||
sheets INTEGER,
|
||||
open_avg REAL,
|
||||
close_avg REAL,
|
||||
premium_paid REAL,
|
||||
realized_pnl REAL,
|
||||
hedge_plan_id INTEGER,
|
||||
plan_close_reason TEXT,
|
||||
realized_pnl_perp REAL,
|
||||
realized_pnl_options REAL,
|
||||
premium_total REAL,
|
||||
direction TEXT,
|
||||
tp REAL,
|
||||
sl REAL,
|
||||
target_price REAL,
|
||||
target_price_up REAL,
|
||||
target_price_down REAL,
|
||||
legs_json TEXT,
|
||||
linked_hedge_plan_id INTEGER,
|
||||
excluded_as_hedge_leg INTEGER DEFAULT 0,
|
||||
strategy_tag TEXT,
|
||||
result_tag TEXT,
|
||||
reviewed INTEGER DEFAULT 0,
|
||||
source_label TEXT,
|
||||
payload_json TEXT NOT NULL,
|
||||
synced_at INTEGER NOT NULL,
|
||||
PRIMARY KEY (exchange_key, history_key)
|
||||
)
|
||||
"""
|
||||
)
|
||||
conn.execute(
|
||||
"""
|
||||
CREATE INDEX IF NOT EXISTS idx_archive_options_closed
|
||||
ON archive_options_trade_cache (exchange_key, closed_at_ms)
|
||||
"""
|
||||
)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def purge_stale_options_trades_cache(
|
||||
exchange_key: str,
|
||||
active_history_keys: list[str],
|
||||
*,
|
||||
db_path: Path | None = None,
|
||||
) -> int:
|
||||
init_options_archive_db(db_path)
|
||||
ex_k = (exchange_key or "").strip().lower()
|
||||
if not ex_k:
|
||||
return 0
|
||||
active = {str(k).strip() for k in (active_history_keys or []) if str(k).strip()}
|
||||
conn = _connect(db_path)
|
||||
try:
|
||||
rows = conn.execute(
|
||||
"SELECT history_key FROM archive_options_trade_cache WHERE exchange_key=?",
|
||||
(ex_k,),
|
||||
).fetchall()
|
||||
stale = [r["history_key"] for r in rows if r["history_key"] not in active]
|
||||
removed = 0
|
||||
for hk in stale:
|
||||
cur = conn.execute(
|
||||
"DELETE FROM archive_options_trade_cache WHERE exchange_key=? AND history_key=?",
|
||||
(ex_k, hk),
|
||||
)
|
||||
removed += int(cur.rowcount or 0)
|
||||
return removed
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def _optional_float(raw: Any) -> float | None:
|
||||
if raw in (None, ""):
|
||||
return None
|
||||
try:
|
||||
return float(raw)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def _optional_int(raw: Any) -> int | None:
|
||||
if raw in (None, ""):
|
||||
return None
|
||||
try:
|
||||
return int(raw)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def upsert_options_trades_cache(
|
||||
exchange_key: str,
|
||||
trades: list[dict[str, Any]],
|
||||
*,
|
||||
db_path: Path | None = None,
|
||||
prune_missing: bool = True,
|
||||
) -> dict[str, int]:
|
||||
init_options_archive_db(db_path)
|
||||
ex_k = (exchange_key or "").strip().lower()
|
||||
if not ex_k:
|
||||
return {"upserted": 0, "removed": 0}
|
||||
now = _now_ms()
|
||||
n = 0
|
||||
active_keys: list[str] = []
|
||||
conn = _connect(db_path)
|
||||
try:
|
||||
for t in trades or []:
|
||||
if not isinstance(t, dict):
|
||||
continue
|
||||
hk = str(t.get("history_key") or "").strip()
|
||||
if not hk:
|
||||
continue
|
||||
if int(t.get("excluded_as_hedge_leg") or 0):
|
||||
continue
|
||||
active_keys.append(hk)
|
||||
opened_at = t.get("opened_at")
|
||||
closed_at = t.get("closed_at")
|
||||
opened_ms = t.get("opened_at_ms") or parse_wall_clock_ms(opened_at)
|
||||
closed_ms = t.get("closed_at_ms") or parse_wall_clock_ms(closed_at)
|
||||
entry = t.get("entry") if isinstance(t.get("entry"), dict) else {}
|
||||
strategy_tag = t.get("strategy_tag") or (entry or {}).get("strategy_tag")
|
||||
result_tag = t.get("result_tag") or (entry or {}).get("result_tag")
|
||||
reviewed = 1 if t.get("reviewed") or entry else 0
|
||||
row = dict(t)
|
||||
row["exchange_key"] = ex_k
|
||||
payload = json.dumps(row, ensure_ascii=False, default=str)
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO archive_options_trade_cache (
|
||||
exchange_key, history_key, source_type, underlying,
|
||||
opened_at, closed_at, opened_at_ms, closed_at_ms, hold_seconds,
|
||||
realized_pnl_total, status_raw,
|
||||
pos_id, inst_id, opt_type, strike, exp_time, sheets,
|
||||
open_avg, close_avg, premium_paid, realized_pnl,
|
||||
hedge_plan_id, plan_close_reason, realized_pnl_perp, realized_pnl_options,
|
||||
premium_total, direction, tp, sl, target_price, target_price_up, target_price_down,
|
||||
legs_json, linked_hedge_plan_id, excluded_as_hedge_leg,
|
||||
strategy_tag, result_tag, reviewed, source_label,
|
||||
payload_json, synced_at
|
||||
) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
|
||||
ON CONFLICT(exchange_key, history_key) DO UPDATE SET
|
||||
source_type=excluded.source_type,
|
||||
underlying=excluded.underlying,
|
||||
opened_at=excluded.opened_at,
|
||||
closed_at=excluded.closed_at,
|
||||
opened_at_ms=excluded.opened_at_ms,
|
||||
closed_at_ms=excluded.closed_at_ms,
|
||||
hold_seconds=excluded.hold_seconds,
|
||||
realized_pnl_total=excluded.realized_pnl_total,
|
||||
status_raw=excluded.status_raw,
|
||||
pos_id=excluded.pos_id,
|
||||
inst_id=excluded.inst_id,
|
||||
opt_type=excluded.opt_type,
|
||||
strike=excluded.strike,
|
||||
exp_time=excluded.exp_time,
|
||||
sheets=excluded.sheets,
|
||||
open_avg=excluded.open_avg,
|
||||
close_avg=excluded.close_avg,
|
||||
premium_paid=excluded.premium_paid,
|
||||
realized_pnl=excluded.realized_pnl,
|
||||
hedge_plan_id=excluded.hedge_plan_id,
|
||||
plan_close_reason=excluded.plan_close_reason,
|
||||
realized_pnl_perp=excluded.realized_pnl_perp,
|
||||
realized_pnl_options=excluded.realized_pnl_options,
|
||||
premium_total=excluded.premium_total,
|
||||
direction=excluded.direction,
|
||||
tp=excluded.tp,
|
||||
sl=excluded.sl,
|
||||
target_price=excluded.target_price,
|
||||
target_price_up=excluded.target_price_up,
|
||||
target_price_down=excluded.target_price_down,
|
||||
legs_json=excluded.legs_json,
|
||||
linked_hedge_plan_id=excluded.linked_hedge_plan_id,
|
||||
excluded_as_hedge_leg=excluded.excluded_as_hedge_leg,
|
||||
strategy_tag=excluded.strategy_tag,
|
||||
result_tag=excluded.result_tag,
|
||||
reviewed=excluded.reviewed,
|
||||
source_label=excluded.source_label,
|
||||
payload_json=excluded.payload_json,
|
||||
synced_at=excluded.synced_at
|
||||
""",
|
||||
(
|
||||
ex_k,
|
||||
hk,
|
||||
t.get("source_type"),
|
||||
t.get("underlying"),
|
||||
opened_at,
|
||||
closed_at,
|
||||
int(opened_ms) if opened_ms else None,
|
||||
int(closed_ms) if closed_ms else None,
|
||||
_optional_int(t.get("hold_seconds")),
|
||||
float(t.get("realized_pnl_total") or t.get("realized_pnl") or 0),
|
||||
t.get("status_raw"),
|
||||
t.get("pos_id"),
|
||||
t.get("inst_id"),
|
||||
t.get("opt_type"),
|
||||
_optional_float(t.get("strike")),
|
||||
t.get("exp_time"),
|
||||
_optional_int(t.get("sheets")),
|
||||
_optional_float(t.get("open_avg")),
|
||||
_optional_float(t.get("close_avg")),
|
||||
_optional_float(t.get("premium_paid")),
|
||||
_optional_float(t.get("realized_pnl")),
|
||||
_optional_int(t.get("hedge_plan_id")),
|
||||
t.get("plan_close_reason"),
|
||||
_optional_float(t.get("realized_pnl_perp")),
|
||||
_optional_float(t.get("realized_pnl_options")),
|
||||
_optional_float(t.get("premium_total")),
|
||||
t.get("direction"),
|
||||
_optional_float(t.get("tp")),
|
||||
_optional_float(t.get("sl")),
|
||||
_optional_float(t.get("target_price")),
|
||||
_optional_float(t.get("target_price_up")),
|
||||
_optional_float(t.get("target_price_down")),
|
||||
t.get("legs_json")
|
||||
if isinstance(t.get("legs_json"), str)
|
||||
else (json.dumps(t.get("legs"), ensure_ascii=False) if t.get("legs") else None),
|
||||
_optional_int(t.get("linked_hedge_plan_id")),
|
||||
int(t.get("excluded_as_hedge_leg") or 0),
|
||||
strategy_tag,
|
||||
result_tag,
|
||||
reviewed,
|
||||
t.get("source_label"),
|
||||
payload,
|
||||
now,
|
||||
),
|
||||
)
|
||||
n += 1
|
||||
finally:
|
||||
conn.close()
|
||||
removed = 0
|
||||
if prune_missing:
|
||||
removed = purge_stale_options_trades_cache(ex_k, active_keys, db_path=db_path)
|
||||
return {"upserted": n, "removed": removed}
|
||||
|
||||
|
||||
def _options_row_to_dict(row: Any) -> dict[str, Any]:
|
||||
out: dict[str, Any] = dict(row)
|
||||
payload = {}
|
||||
raw = out.get("payload_json")
|
||||
if raw:
|
||||
try:
|
||||
payload = json.loads(raw) if isinstance(raw, str) else {}
|
||||
except (TypeError, ValueError, json.JSONDecodeError):
|
||||
payload = {}
|
||||
if isinstance(payload, dict):
|
||||
for k, v in payload.items():
|
||||
if k not in out or out.get(k) in (None, ""):
|
||||
out[k] = v
|
||||
pnl = float(out.get("realized_pnl_total") or out.get("realized_pnl") or 0)
|
||||
out["realized_pnl_total"] = pnl
|
||||
out["pnl_amount"] = pnl # 复用永续统计/日历字段名
|
||||
hold_sec = out.get("hold_seconds")
|
||||
if hold_sec is not None:
|
||||
try:
|
||||
out["hold_minutes"] = round(float(hold_sec) / 60.0, 2)
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
if not out.get("opened_at_ms") and out.get("opened_at"):
|
||||
ms = parse_wall_clock_ms(out.get("opened_at"))
|
||||
if ms:
|
||||
out["opened_at_ms"] = int(ms)
|
||||
if not out.get("closed_at_ms") and out.get("closed_at"):
|
||||
ms = parse_wall_clock_ms(out.get("closed_at"))
|
||||
if ms:
|
||||
out["closed_at_ms"] = int(ms)
|
||||
out["trade_id"] = out.get("history_key")
|
||||
out["id"] = out.get("history_key")
|
||||
out["symbol"] = out.get("inst_id") or out.get("underlying") or ""
|
||||
return out
|
||||
|
||||
|
||||
def _empty_options_stats() -> dict[str, Any]:
|
||||
return {
|
||||
"open_count": 0,
|
||||
"sick_count": 0,
|
||||
"sick_pct": 0.0,
|
||||
"pnl_total": 0.0,
|
||||
"pnl_ex_sick": 0.0,
|
||||
"win_count": 0,
|
||||
"loss_count": 0,
|
||||
"avg_win": 0.0,
|
||||
"avg_loss": 0.0,
|
||||
"max_win": 0.0,
|
||||
"max_loss": 0.0,
|
||||
"win_rate": 0.0,
|
||||
"profit_loss_ratio": 0.0,
|
||||
"turnover_total": 0.0,
|
||||
"commission_total": 0.0,
|
||||
"premium_total": 0.0,
|
||||
"by_exchange": {},
|
||||
"by_source_type": {},
|
||||
}
|
||||
|
||||
|
||||
def _compute_options_period_stats(trade_rows: list[dict[str, Any]]) -> dict[str, Any]:
|
||||
st = _empty_options_stats()
|
||||
wins: list[float] = []
|
||||
losses: list[float] = []
|
||||
by_ex: dict[str, dict[str, Any]] = {}
|
||||
by_src: dict[str, dict[str, Any]] = {}
|
||||
|
||||
def bucket() -> dict[str, Any]:
|
||||
return {
|
||||
"open_count": 0,
|
||||
"pnl_total": 0.0,
|
||||
"win_count": 0,
|
||||
"loss_count": 0,
|
||||
"premium_total": 0.0,
|
||||
}
|
||||
|
||||
for td in trade_rows:
|
||||
pnl = float(td.get("pnl_amount") or td.get("realized_pnl_total") or 0)
|
||||
ex = str(td.get("exchange_key") or "okx")
|
||||
src = str(td.get("source_type") or td.get("source_label") or "?")
|
||||
prem = float(td.get("premium_total") or td.get("premium_paid") or 0)
|
||||
st["open_count"] += 1
|
||||
st["pnl_total"] += pnl
|
||||
st["premium_total"] += prem
|
||||
if pnl > 0.0001:
|
||||
st["win_count"] += 1
|
||||
wins.append(pnl)
|
||||
elif pnl < -0.0001:
|
||||
st["loss_count"] += 1
|
||||
losses.append(pnl)
|
||||
if ex not in by_ex:
|
||||
by_ex[ex] = bucket()
|
||||
by_ex[ex]["open_count"] += 1
|
||||
by_ex[ex]["pnl_total"] += pnl
|
||||
by_ex[ex]["premium_total"] += prem
|
||||
if pnl > 0.0001:
|
||||
by_ex[ex]["win_count"] += 1
|
||||
elif pnl < -0.0001:
|
||||
by_ex[ex]["loss_count"] += 1
|
||||
if src not in by_src:
|
||||
by_src[src] = bucket()
|
||||
by_src[src]["open_count"] += 1
|
||||
by_src[src]["pnl_total"] += pnl
|
||||
|
||||
total = int(st["open_count"] or 0)
|
||||
st["pnl_ex_sick"] = round(float(st["pnl_total"]), 4)
|
||||
st["pnl_total"] = round(float(st["pnl_total"]), 4)
|
||||
st["premium_total"] = round(float(st["premium_total"]), 4)
|
||||
st["avg_win"] = round(sum(wins) / len(wins), 4) if wins else 0.0
|
||||
st["avg_loss"] = round(sum(losses) / len(losses), 4) if losses else 0.0
|
||||
st["max_win"] = round(max(wins), 4) if wins else 0.0
|
||||
st["max_loss"] = round(min(losses), 4) if losses else 0.0
|
||||
st["win_rate"] = round(st["win_count"] / total * 100, 1) if total else 0.0
|
||||
if wins and losses and abs(st["avg_loss"]) > 1e-9:
|
||||
st["profit_loss_ratio"] = round(abs(st["avg_win"] / st["avg_loss"]), 2)
|
||||
for ex, b in by_ex.items():
|
||||
b["pnl_total"] = round(float(b["pnl_total"]), 4)
|
||||
b["premium_total"] = round(float(b["premium_total"]), 4)
|
||||
b["sick_count"] = 0
|
||||
b["sick_pct"] = 0.0
|
||||
b["pnl_ex_sick"] = b["pnl_total"]
|
||||
b["avg_win"] = 0.0
|
||||
b["avg_loss"] = 0.0
|
||||
b["max_win"] = 0.0
|
||||
b["max_loss"] = 0.0
|
||||
b["win_rate"] = (
|
||||
round(b["win_count"] / b["open_count"] * 100, 1) if b["open_count"] else 0.0
|
||||
)
|
||||
b["profit_loss_ratio"] = 0.0
|
||||
b["turnover_total"] = 0.0
|
||||
b["commission_total"] = 0.0
|
||||
for src, b in by_src.items():
|
||||
b["pnl_total"] = round(float(b["pnl_total"]), 4)
|
||||
st["by_exchange"] = by_ex
|
||||
st["by_source_type"] = by_src
|
||||
return st
|
||||
|
||||
|
||||
def list_daily_options_trades(
|
||||
trading_day: str = "",
|
||||
*,
|
||||
period: str = "",
|
||||
date_from: str = "",
|
||||
date_to: str = "",
|
||||
exchange_key: str = "",
|
||||
filter_profit: bool = False,
|
||||
filter_loss: bool = False,
|
||||
search: str = "",
|
||||
source_type: str = "",
|
||||
db_path: Path | None = None,
|
||||
) -> dict[str, Any]:
|
||||
init_options_archive_db(db_path)
|
||||
p = (period or "today").strip().lower() or "today"
|
||||
start_ms, end_ms, df, dt, period_label = resolve_period_bounds(
|
||||
period=p,
|
||||
trading_day=trading_day,
|
||||
date_from=date_from,
|
||||
date_to=date_to,
|
||||
)
|
||||
ex_filter = (exchange_key or "").strip().lower()
|
||||
src_filter = (source_type or "").strip().lower()
|
||||
conn = _connect(db_path)
|
||||
try:
|
||||
params: list[Any] = [start_ms, end_ms]
|
||||
where = "closed_at_ms IS NOT NULL AND closed_at_ms >= ? AND closed_at_ms < ?"
|
||||
where += " AND COALESCE(excluded_as_hedge_leg,0)=0"
|
||||
if ex_filter:
|
||||
where += " AND exchange_key=?"
|
||||
params.append(ex_filter)
|
||||
if src_filter:
|
||||
where += " AND LOWER(COALESCE(source_type,''))=?"
|
||||
params.append(src_filter)
|
||||
rows = conn.execute(
|
||||
f"""
|
||||
SELECT * FROM archive_options_trade_cache
|
||||
WHERE {where}
|
||||
ORDER BY closed_at_ms DESC, history_key DESC
|
||||
""",
|
||||
params,
|
||||
).fetchall()
|
||||
trades: list[dict[str, Any]] = []
|
||||
q = (search or "").strip().lower()
|
||||
for r in rows:
|
||||
td = _options_row_to_dict(r)
|
||||
pnl = float(td.get("pnl_amount") or 0)
|
||||
if filter_profit and pnl <= 0.0001:
|
||||
continue
|
||||
if filter_loss and pnl >= -0.0001:
|
||||
continue
|
||||
if q:
|
||||
blob = " ".join(
|
||||
str(td.get(k) or "")
|
||||
for k in (
|
||||
"underlying",
|
||||
"inst_id",
|
||||
"exchange_key",
|
||||
"source_type",
|
||||
"source_label",
|
||||
"opt_type",
|
||||
"strategy_tag",
|
||||
"result_tag",
|
||||
"direction",
|
||||
)
|
||||
).lower()
|
||||
if q not in blob:
|
||||
continue
|
||||
trades.append(td)
|
||||
return {
|
||||
"period": p,
|
||||
"period_label": period_label,
|
||||
"trading_day": dt,
|
||||
"date_from": df,
|
||||
"date_to": dt,
|
||||
"product": "options",
|
||||
"trades": trades,
|
||||
"stats": _compute_options_period_stats(trades),
|
||||
}
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def list_archive_options_calendar(
|
||||
year: int,
|
||||
month: int,
|
||||
*,
|
||||
exchange_key: str = "",
|
||||
db_path: Path | None = None,
|
||||
reset_hour: int = TRADING_DAY_RESET_HOUR,
|
||||
) -> dict[str, Any]:
|
||||
init_options_archive_db(db_path)
|
||||
y = int(year)
|
||||
m = int(month)
|
||||
if m < 1 or m > 12:
|
||||
raise ValueError("month 无效")
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
first = f"{y:04d}-{m:02d}-01"
|
||||
if m == 12:
|
||||
next_first = datetime(y + 1, 1, 1)
|
||||
else:
|
||||
next_first = datetime(y, m + 1, 1)
|
||||
last = (next_first - timedelta(days=1)).strftime("%Y-%m-%d")
|
||||
start_ms, _ = trading_day_bounds_ms(first, reset_hour=reset_hour)
|
||||
_, end_ms = trading_day_bounds_ms(last, reset_hour=reset_hour)
|
||||
ex_filter = (exchange_key or "").strip().lower()
|
||||
conn = _connect(db_path)
|
||||
try:
|
||||
params: list[Any] = [start_ms, end_ms]
|
||||
where = (
|
||||
"closed_at_ms IS NOT NULL AND closed_at_ms >= ? AND closed_at_ms < ?"
|
||||
" AND COALESCE(excluded_as_hedge_leg,0)=0"
|
||||
)
|
||||
if ex_filter:
|
||||
where += " AND exchange_key=?"
|
||||
params.append(ex_filter)
|
||||
rows = conn.execute(
|
||||
f"SELECT * FROM archive_options_trade_cache WHERE {where}",
|
||||
params,
|
||||
).fetchall()
|
||||
days: dict[str, dict[str, Any]] = {}
|
||||
for r in rows:
|
||||
td = _options_row_to_dict(r)
|
||||
closed_ms = td.get("closed_at_ms") or parse_wall_clock_ms(td.get("closed_at"))
|
||||
if not closed_ms:
|
||||
continue
|
||||
day = ms_to_trading_day(int(closed_ms), reset_hour=reset_hour)
|
||||
if not day or day < first or day > last:
|
||||
continue
|
||||
bucket = days.setdefault(
|
||||
day,
|
||||
{
|
||||
"trading_day": day,
|
||||
"open_count": 0,
|
||||
"sick_count": 0,
|
||||
"pnl_total": 0.0,
|
||||
"turnover_total": 0.0,
|
||||
"commission_total": 0.0,
|
||||
"has_sick": False,
|
||||
},
|
||||
)
|
||||
bucket["open_count"] += 1
|
||||
bucket["pnl_total"] += float(td.get("pnl_amount") or 0)
|
||||
for d in days.values():
|
||||
d["pnl_total"] = round(float(d["pnl_total"]), 4)
|
||||
month_pnl = sum(float(d["pnl_total"]) for d in days.values())
|
||||
month_count = sum(int(d["open_count"]) for d in days.values())
|
||||
return {
|
||||
"year": y,
|
||||
"month": m,
|
||||
"date_from": first,
|
||||
"date_to": last,
|
||||
"product": "options",
|
||||
"days": days,
|
||||
"month_pnl_total": round(month_pnl, 4),
|
||||
"month_open_count": month_count,
|
||||
}
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def sync_options_exchange_archive(
|
||||
exchange_key: str,
|
||||
trades: list[dict[str, Any]],
|
||||
*,
|
||||
db_path: Path | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""仅缓存期权交易,不做 K 线."""
|
||||
r = upsert_options_trades_cache(
|
||||
exchange_key, trades, db_path=db_path, prune_missing=True
|
||||
)
|
||||
return {
|
||||
"ok": True,
|
||||
"exchange_key": (exchange_key or "").strip().lower(),
|
||||
"product": "options",
|
||||
"trades_upserted": r.get("upserted", 0),
|
||||
"trades_removed": r.get("removed", 0),
|
||||
"trade_count": len(trades or []),
|
||||
}
|
||||
@@ -0,0 +1,341 @@
|
||||
"""中控永期对冲计算器:永续 1 币 + 按目标盈利反推期权仓位/波动点数(纯函数)."""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Optional, Tuple
|
||||
|
||||
from lib.trade.trade_fee_lib import estimate_roundtrip_fee_usdt, taker_fee_rate
|
||||
|
||||
DEFAULT_CT_MULT = 0.01
|
||||
PERP_COINS = 1.0
|
||||
|
||||
|
||||
def _f(v: Any) -> Optional[float]:
|
||||
if v is None or v == "":
|
||||
return None
|
||||
try:
|
||||
return float(v)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def _parse_base_common(
|
||||
*,
|
||||
base: str,
|
||||
spot: Any,
|
||||
capital_usdt: Any,
|
||||
target_profit_u: Any,
|
||||
perp_leverage: Any,
|
||||
option_leverage: Any,
|
||||
ct_mult: Any,
|
||||
) -> Tuple[Optional[dict[str, float]], Optional[str]]:
|
||||
b = (base or "ETH").strip().upper()
|
||||
if b not in ("ETH", "BTC"):
|
||||
return None, "币种仅支持 BTC / ETH"
|
||||
s = _f(spot)
|
||||
capital = _f(capital_usdt)
|
||||
target = _f(target_profit_u)
|
||||
p_lev = _f(perp_leverage)
|
||||
o_lev = _f(option_leverage)
|
||||
ct = _f(ct_mult)
|
||||
if s is None or capital is None or target is None or p_lev is None or o_lev is None:
|
||||
return None, "参数格式错误"
|
||||
if ct is None or ct <= 0:
|
||||
ct = DEFAULT_CT_MULT
|
||||
if s <= 0 or capital <= 0 or p_lev <= 0 or o_lev <= 0:
|
||||
return None, "现价、资金、杠杆须大于 0"
|
||||
if target < 0:
|
||||
return None, "目标盈利不能为负"
|
||||
prem_per_coin = s / o_lev
|
||||
if prem_per_coin <= 0:
|
||||
return None, "单币权利金无效"
|
||||
margin = (s * PERP_COINS) / p_lev
|
||||
return {
|
||||
"base_ok": 1.0,
|
||||
"spot": s,
|
||||
"capital": capital,
|
||||
"target": target,
|
||||
"p_lev": p_lev,
|
||||
"o_lev": o_lev,
|
||||
"ct": ct,
|
||||
"prem_per_coin": prem_per_coin,
|
||||
"margin": margin,
|
||||
"fee_rate": taker_fee_rate(),
|
||||
}, None
|
||||
|
||||
|
||||
def _move_for_perp_correct(*, spot: float, target: float, premium: float, fee_rate: float) -> float:
|
||||
"""净利 = move − premium − fee(move) = target → 解 move.
|
||||
|
||||
fee = (2*spot + move) * fee_rate
|
||||
move*(1-fee_rate) = target + premium + 2*spot*fee_rate
|
||||
"""
|
||||
denom = 1.0 - float(fee_rate)
|
||||
if denom <= 0:
|
||||
return 0.0
|
||||
return (float(target) + float(premium) + 2.0 * float(spot) * float(fee_rate)) / denom
|
||||
|
||||
|
||||
def calc_perp_options_hedge(
|
||||
*,
|
||||
base: str = "ETH",
|
||||
spot: float,
|
||||
capital_usdt: float,
|
||||
target_profit_u: float,
|
||||
move_mode: str = "points",
|
||||
move_value: float,
|
||||
perp_leverage: float,
|
||||
option_leverage: float,
|
||||
ct_mult: float = DEFAULT_CT_MULT,
|
||||
) -> Tuple[Optional[dict[str, Any]], Optional[str]]:
|
||||
"""由波动反推期权开仓币数/张数(calc_mode=size)."""
|
||||
common, err = _parse_base_common(
|
||||
base=base,
|
||||
spot=spot,
|
||||
capital_usdt=capital_usdt,
|
||||
target_profit_u=target_profit_u,
|
||||
perp_leverage=perp_leverage,
|
||||
option_leverage=option_leverage,
|
||||
ct_mult=ct_mult,
|
||||
)
|
||||
if err or not common:
|
||||
return None, err
|
||||
|
||||
s = common["spot"]
|
||||
capital = common["capital"]
|
||||
target = common["target"]
|
||||
p_lev = common["p_lev"]
|
||||
o_lev = common["o_lev"]
|
||||
ct = common["ct"]
|
||||
prem_per_coin = common["prem_per_coin"]
|
||||
margin = common["margin"]
|
||||
fee_rate = common["fee_rate"]
|
||||
b = (base or "ETH").strip().upper()
|
||||
|
||||
move = _f(move_value)
|
||||
mode = (move_mode or "points").strip().lower()
|
||||
if mode not in ("points", "pct", "percent", "rate"):
|
||||
return None, "波动模式须为 points 或 pct"
|
||||
if mode in ("percent", "rate"):
|
||||
mode = "pct"
|
||||
if move is None:
|
||||
return None, "参数格式错误"
|
||||
if move <= 0:
|
||||
return None, "现价、资金、波动、杠杆须大于 0"
|
||||
|
||||
if mode == "pct":
|
||||
move_points = s * (move / 100.0)
|
||||
else:
|
||||
move_points = move
|
||||
if move_points <= 0:
|
||||
return None, "波动对应价格变动须大于 0"
|
||||
|
||||
exit_px = s + move_points
|
||||
perp_gross = move_points * PERP_COINS
|
||||
fee = estimate_roundtrip_fee_usdt(s, exit_px, qty=PERP_COINS, contract_size=1.0)
|
||||
|
||||
premium_budget = perp_gross - target - fee
|
||||
if premium_budget <= 0:
|
||||
return None, "波动收益不足以覆盖目标盈利+手续费,无法开期权"
|
||||
|
||||
opt_coins = premium_budget / prem_per_coin
|
||||
opt_sheets = opt_coins / ct
|
||||
premium_total = opt_coins * prem_per_coin
|
||||
|
||||
case_a_net = perp_gross - premium_total - fee
|
||||
opt_intrinsic = opt_coins * move_points
|
||||
opt_net = opt_intrinsic - premium_total
|
||||
perp_loss = -perp_gross
|
||||
portfolio_net = opt_net + perp_loss
|
||||
|
||||
return {
|
||||
"calc_mode": "size",
|
||||
"base": b,
|
||||
"spot": round(s, 8),
|
||||
"capital_usdt": round(capital, 8),
|
||||
"target_profit_u": round(target, 8),
|
||||
"move_mode": mode,
|
||||
"move_value": round(move, 8),
|
||||
"move_points": round(move_points, 8),
|
||||
"exit_price": round(exit_px, 8),
|
||||
"perp_coins": PERP_COINS,
|
||||
"perp_leverage": round(p_lev, 8),
|
||||
"option_leverage": round(o_lev, 8),
|
||||
"ct_mult": ct,
|
||||
"prem_per_coin": round(prem_per_coin, 8),
|
||||
"perp_gross_u": round(perp_gross, 8),
|
||||
"perp_fee_u": round(fee, 8),
|
||||
"fee_rate": fee_rate,
|
||||
"premium_budget_u": round(premium_budget, 8),
|
||||
"opt_coins": round(opt_coins, 8),
|
||||
"opt_sheets": round(opt_sheets, 8),
|
||||
"premium_total_u": round(premium_total, 8),
|
||||
"perp_margin_u": round(margin, 8),
|
||||
"capital_ok": bool(capital >= margin),
|
||||
"case_a": {
|
||||
"label": "永续方向对",
|
||||
"perp_pnl_u": round(perp_gross, 8),
|
||||
"premium_u": round(premium_total, 8),
|
||||
"fee_u": round(fee, 8),
|
||||
"net_u": round(case_a_net, 8),
|
||||
},
|
||||
"case_b": {
|
||||
"label": "期权方向对",
|
||||
"opt_intrinsic_u": round(opt_intrinsic, 8),
|
||||
"premium_u": round(premium_total, 8),
|
||||
"opt_net_u": round(opt_net, 8),
|
||||
"perp_pnl_u": round(perp_loss, 8),
|
||||
"portfolio_net_u": round(portfolio_net, 8),
|
||||
},
|
||||
}, None
|
||||
|
||||
|
||||
def calc_perp_options_points(
|
||||
*,
|
||||
base: str = "ETH",
|
||||
spot: float,
|
||||
capital_usdt: float,
|
||||
target_profit_u: float,
|
||||
perp_leverage: float,
|
||||
option_leverage: float,
|
||||
ratio_perp: float = 1.0,
|
||||
ratio_opt: float = 2.0,
|
||||
ct_mult: float = DEFAULT_CT_MULT,
|
||||
) -> Tuple[Optional[dict[str, Any]], Optional[str]]:
|
||||
"""按永续:期权比例 + 目标盈利,反推两套情景所需波动点数.
|
||||
|
||||
永续币数固定为 ratio 归一后的 1 币侧(perp_coins = PERP_COINS).
|
||||
期权币数 = PERP_COINS * (ratio_opt / ratio_perp),例 1:2 → 2 币.
|
||||
|
||||
A 永续方向对: move − premium − fee(move) = 目标盈利
|
||||
B 期权方向对:
|
||||
- 期权净利达目标: opt_coins*move − premium = 目标
|
||||
- 组合净利达目标: move*(opt_coins − perp_coins) − premium = 目标
|
||||
"""
|
||||
common, err = _parse_base_common(
|
||||
base=base,
|
||||
spot=spot,
|
||||
capital_usdt=capital_usdt,
|
||||
target_profit_u=target_profit_u,
|
||||
perp_leverage=perp_leverage,
|
||||
option_leverage=option_leverage,
|
||||
ct_mult=ct_mult,
|
||||
)
|
||||
if err or not common:
|
||||
return None, err
|
||||
|
||||
rp = _f(ratio_perp)
|
||||
ro = _f(ratio_opt)
|
||||
if rp is None or ro is None or rp <= 0 or ro <= 0:
|
||||
return None, "永续:期权比例须大于 0"
|
||||
|
||||
s = common["spot"]
|
||||
capital = common["capital"]
|
||||
target = common["target"]
|
||||
p_lev = common["p_lev"]
|
||||
o_lev = common["o_lev"]
|
||||
ct = common["ct"]
|
||||
prem_per_coin = common["prem_per_coin"]
|
||||
margin = common["margin"]
|
||||
fee_rate = common["fee_rate"]
|
||||
b = (base or "ETH").strip().upper()
|
||||
|
||||
opt_coins = PERP_COINS * (ro / rp)
|
||||
premium_total = opt_coins * prem_per_coin
|
||||
opt_sheets = opt_coins / ct
|
||||
|
||||
move_a = _move_for_perp_correct(spot=s, target=target, premium=premium_total, fee_rate=fee_rate)
|
||||
if move_a <= 0:
|
||||
return None, "无法解出永续方向对所需点数"
|
||||
|
||||
fee_a = estimate_roundtrip_fee_usdt(s, s + move_a, qty=PERP_COINS, contract_size=1.0)
|
||||
net_a = move_a * PERP_COINS - premium_total - fee_a
|
||||
|
||||
# 期权净利 = 目标
|
||||
move_b_opt = (target + premium_total) / opt_coins
|
||||
opt_net_at_b_opt = opt_coins * move_b_opt - premium_total
|
||||
portfolio_at_b_opt = opt_net_at_b_opt - move_b_opt * PERP_COINS
|
||||
|
||||
# 组合净利 = 目标
|
||||
edge = opt_coins - PERP_COINS
|
||||
if edge <= 0:
|
||||
move_b_port = None
|
||||
port_err = "期权币数须大于永续币数,组合才能在方向对时赚到目标盈利"
|
||||
else:
|
||||
move_b_port = (target + premium_total) / edge
|
||||
port_err = None
|
||||
if move_b_port is not None:
|
||||
opt_net_at_b_port = opt_coins * move_b_port - premium_total
|
||||
portfolio_at_b_port = opt_net_at_b_port - move_b_port * PERP_COINS
|
||||
else:
|
||||
opt_net_at_b_port = None
|
||||
portfolio_at_b_port = None
|
||||
|
||||
return {
|
||||
"calc_mode": "points",
|
||||
"base": b,
|
||||
"spot": round(s, 8),
|
||||
"capital_usdt": round(capital, 8),
|
||||
"target_profit_u": round(target, 8),
|
||||
"ratio_perp": round(rp, 8),
|
||||
"ratio_opt": round(ro, 8),
|
||||
"ratio_label": f"{_fmt_ratio(rp)}:{_fmt_ratio(ro)}",
|
||||
"perp_coins": PERP_COINS,
|
||||
"opt_coins": round(opt_coins, 8),
|
||||
"opt_sheets": round(opt_sheets, 8),
|
||||
"perp_leverage": round(p_lev, 8),
|
||||
"option_leverage": round(o_lev, 8),
|
||||
"ct_mult": ct,
|
||||
"prem_per_coin": round(prem_per_coin, 8),
|
||||
"premium_total_u": round(premium_total, 8),
|
||||
"fee_rate": fee_rate,
|
||||
"perp_margin_u": round(margin, 8),
|
||||
"capital_ok": bool(capital >= margin),
|
||||
"case_a": {
|
||||
"label": "永续方向对",
|
||||
"move_points": round(move_a, 8),
|
||||
"move_pct": round(move_a / s * 100.0, 8),
|
||||
"perp_pnl_u": round(move_a * PERP_COINS, 8),
|
||||
"premium_u": round(premium_total, 8),
|
||||
"fee_u": round(fee_a, 8),
|
||||
"net_u": round(net_a, 8),
|
||||
},
|
||||
"case_b": {
|
||||
"label": "期权方向对",
|
||||
"move_points_opt_net": round(move_b_opt, 8),
|
||||
"move_pct_opt_net": round(move_b_opt / s * 100.0, 8),
|
||||
"opt_net_u": round(opt_net_at_b_opt, 8),
|
||||
"portfolio_net_at_opt_target_u": round(portfolio_at_b_opt, 8),
|
||||
"move_points_portfolio": None if move_b_port is None else round(move_b_port, 8),
|
||||
"move_pct_portfolio": None
|
||||
if move_b_port is None
|
||||
else round(move_b_port / s * 100.0, 8),
|
||||
"opt_net_at_portfolio_target_u": None
|
||||
if opt_net_at_b_port is None
|
||||
else round(opt_net_at_b_port, 8),
|
||||
"portfolio_net_u": None if portfolio_at_b_port is None else round(portfolio_at_b_port, 8),
|
||||
"portfolio_error": port_err,
|
||||
"premium_u": round(premium_total, 8),
|
||||
},
|
||||
}, None
|
||||
|
||||
|
||||
def _fmt_ratio(v: float) -> str:
|
||||
if abs(v - round(v)) < 1e-9:
|
||||
return str(int(round(v)))
|
||||
s = f"{v:.4f}".rstrip("0").rstrip(".")
|
||||
return s
|
||||
|
||||
|
||||
def calc_perp_options(
|
||||
*,
|
||||
calc_mode: str = "size",
|
||||
**kwargs: Any,
|
||||
) -> Tuple[Optional[dict[str, Any]], Optional[str]]:
|
||||
"""统一入口:size=由波动推仓位;points=由比例推点数."""
|
||||
mode = (calc_mode or "size").strip().lower()
|
||||
if mode in ("points", "ratio", "move"):
|
||||
return calc_perp_options_points(**kwargs)
|
||||
# size mode: ignore ratio kwargs if present
|
||||
kwargs.pop("ratio_perp", None)
|
||||
kwargs.pop("ratio_opt", None)
|
||||
return calc_perp_options_hedge(**kwargs)
|
||||
@@ -10,9 +10,32 @@ from typing import Any
|
||||
|
||||
from lib.paths import REPO_ROOT
|
||||
|
||||
STRATEGY_EXCHANGES: tuple[str, ...] = ("binance", "okx", "gate")
|
||||
STRATEGY_EXCHANGES: tuple[str, ...] = (
|
||||
"playbook_v2",
|
||||
"playbook",
|
||||
"behavior",
|
||||
"binance",
|
||||
"okx",
|
||||
"gate",
|
||||
)
|
||||
|
||||
STRATEGY_META: dict[str, dict[str, str]] = {
|
||||
"playbook_v2": {
|
||||
"label": "执行手册v2",
|
||||
"title": "交易执行手册 v2(期权 / 合约 · 无对冲)",
|
||||
"md_rel": "docs/交易执行手册-v2-期权与合约.md",
|
||||
},
|
||||
"playbook": {
|
||||
"label": "执行手册v1",
|
||||
"title": "交易执行手册 v1(期权为主 · Gate 为辅 · 含对冲)",
|
||||
# 相对仓库根;其余条目用 md_file 相对 docs/strategy
|
||||
"md_rel": "docs/交易执行手册-期权与Gate.md",
|
||||
},
|
||||
"behavior": {
|
||||
"label": "行为准则",
|
||||
"title": "交易行为准则(开单三检)",
|
||||
"md_rel": "docs/交易行为准则-开单三检.md",
|
||||
},
|
||||
"binance": {
|
||||
"label": "币安",
|
||||
"title": "币安·山寨多头趋势",
|
||||
@@ -43,6 +66,9 @@ def _md_path(exchange_key: str) -> Path:
|
||||
meta = STRATEGY_META.get((exchange_key or "").strip().lower())
|
||||
if not meta:
|
||||
raise KeyError(exchange_key)
|
||||
md_rel = (meta.get("md_rel") or "").strip()
|
||||
if md_rel:
|
||||
return REPO_ROOT / md_rel
|
||||
return _strategy_dir() / meta["md_file"]
|
||||
|
||||
|
||||
@@ -210,11 +236,30 @@ def load_strategy_payload(exchange_key: str) -> dict[str, Any]:
|
||||
}
|
||||
|
||||
|
||||
def strategy_meta_payload() -> dict[str, Any]:
|
||||
tabs = [
|
||||
{"key": k, "label": STRATEGY_META[k]["label"], "title": STRATEGY_META[k]["title"]}
|
||||
for k in STRATEGY_EXCHANGES
|
||||
]
|
||||
_STRATEGY_TAB_DISPLAY_PREF: dict[str, str] = {
|
||||
"playbook_v2": "show_strategy_playbook_v2",
|
||||
"playbook": "show_strategy_playbook",
|
||||
"behavior": "show_strategy_behavior",
|
||||
"binance": "show_strategy_binance",
|
||||
"okx": "show_strategy_okx",
|
||||
"gate": "show_strategy_gate",
|
||||
}
|
||||
|
||||
|
||||
def strategy_meta_payload(display: dict[str, Any] | None = None) -> dict[str, Any]:
|
||||
prefs = display if isinstance(display, dict) else {}
|
||||
tabs = []
|
||||
for k in STRATEGY_EXCHANGES:
|
||||
pref_key = _STRATEGY_TAB_DISPLAY_PREF.get(k)
|
||||
if pref_key and prefs.get(pref_key) is False:
|
||||
continue
|
||||
tabs.append(
|
||||
{
|
||||
"key": k,
|
||||
"label": STRATEGY_META[k]["label"],
|
||||
"title": STRATEGY_META[k]["title"],
|
||||
}
|
||||
)
|
||||
return {"ok": True, "exchanges": tabs}
|
||||
|
||||
|
||||
|
||||
@@ -87,14 +87,15 @@ OPTIONS_SOURCE_LABELS = {
|
||||
HEDGE_ACTIVE_STATUSES = frozenset({"opening", "active", "partial"})
|
||||
|
||||
|
||||
def _resolve_options_source(conn, inst_id: str) -> tuple[str, str]:
|
||||
"""根据进行中对冲计划腿判定来源;默认纯期权."""
|
||||
def _resolve_options_source(conn, inst_id: str) -> tuple[str, str, int | None]:
|
||||
"""根据进行中对冲计划腿判定来源;默认纯期权. 返回 (source, label, plan_id)."""
|
||||
default = ("option", OPTIONS_SOURCE_LABELS["option"], None)
|
||||
if not inst_id or not _table_exists(conn, "hedge_plans") or not _table_exists(conn, "hedge_plan_legs"):
|
||||
return "option", OPTIONS_SOURCE_LABELS["option"]
|
||||
return default
|
||||
try:
|
||||
row = conn.execute(
|
||||
"""
|
||||
SELECT p.plan_type
|
||||
SELECT p.plan_type, p.id
|
||||
FROM hedge_plans p
|
||||
JOIN hedge_plan_legs l ON l.plan_id = p.id
|
||||
WHERE p.status IN ('opening', 'active', 'partial')
|
||||
@@ -106,13 +107,18 @@ def _resolve_options_source(conn, inst_id: str) -> tuple[str, str]:
|
||||
(inst_id,),
|
||||
).fetchone()
|
||||
except Exception:
|
||||
return "option", OPTIONS_SOURCE_LABELS["option"]
|
||||
return default
|
||||
if not row:
|
||||
return "option", OPTIONS_SOURCE_LABELS["option"]
|
||||
pt = str((_row_dict(row).get("plan_type") if isinstance(row, dict) else row[0]) or "").strip()
|
||||
if pt in OPTIONS_SOURCE_LABELS:
|
||||
return pt, OPTIONS_SOURCE_LABELS[pt]
|
||||
return "option", OPTIONS_SOURCE_LABELS["option"]
|
||||
return default
|
||||
d = _row_dict(row)
|
||||
pt = str(d.get("plan_type") or "").strip()
|
||||
try:
|
||||
plan_id = int(d["id"]) if d.get("id") is not None else None
|
||||
except (TypeError, ValueError):
|
||||
plan_id = None
|
||||
if pt in OPTIONS_SOURCE_LABELS and pt != "option":
|
||||
return pt, OPTIONS_SOURCE_LABELS[pt], plan_id
|
||||
return default
|
||||
|
||||
|
||||
def _format_options_target(p: dict[str, Any]) -> str:
|
||||
@@ -152,9 +158,10 @@ def _format_options_item(p: dict[str, Any], *, conn=None) -> dict[str, Any]:
|
||||
exp_ms = int(float(exp_ms)) if exp_ms not in (None, "") else None
|
||||
except (TypeError, ValueError):
|
||||
exp_ms = None
|
||||
source_key, source_label = (
|
||||
_resolve_options_source(conn, inst) if conn is not None else ("option", OPTIONS_SOURCE_LABELS["option"])
|
||||
)
|
||||
if conn is not None:
|
||||
source_key, source_label, source_plan_id = _resolve_options_source(conn, inst)
|
||||
else:
|
||||
source_key, source_label, source_plan_id = "option", OPTIONS_SOURCE_LABELS["option"], None
|
||||
return {
|
||||
"id": inst,
|
||||
"kind": "options",
|
||||
@@ -166,6 +173,7 @@ def _format_options_item(p: dict[str, Any], *, conn=None) -> dict[str, Any]:
|
||||
"opt_type_label": label,
|
||||
"source": source_key,
|
||||
"source_label": source_label,
|
||||
"source_plan_id": source_plan_id,
|
||||
"pos": pos,
|
||||
"exp_time_ms": exp_ms,
|
||||
"target_monitor": _format_options_target(p),
|
||||
|
||||
@@ -9,11 +9,14 @@ DISPLAY_RUNTIME_PREFIX = "display."
|
||||
|
||||
DEFAULT_INSTANCE_DISPLAY: dict[str, bool] = {
|
||||
"show_nav_dashboard": False,
|
||||
"show_nav_key_monitor": True,
|
||||
"show_nav_trade": True,
|
||||
"show_nav_strategy": True,
|
||||
"show_nav_strategy_records": True,
|
||||
"show_nav_records": True,
|
||||
"show_nav_stats": True,
|
||||
"show_nav_risk_policy": True,
|
||||
"show_nav_system_guide": False,
|
||||
"show_nav_env_config": True,
|
||||
"show_nav_options": True,
|
||||
"show_nav_options_review": True,
|
||||
@@ -27,11 +30,14 @@ DEFAULT_INSTANCE_DISPLAY: dict[str, bool] = {
|
||||
|
||||
DISPLAY_LABELS: dict[str, str] = {
|
||||
"show_nav_dashboard": "数据看板",
|
||||
"show_nav_key_monitor": "关键位监控",
|
||||
"show_nav_trade": "实盘下单",
|
||||
"show_nav_strategy": "策略交易",
|
||||
"show_nav_strategy_records": "策略交易记录",
|
||||
"show_nav_records": "交易记录与复盘",
|
||||
"show_nav_stats": "统计分析",
|
||||
"show_nav_risk_policy": "风控说明",
|
||||
"show_nav_system_guide": "系统说明",
|
||||
"show_nav_env_config": "env配置",
|
||||
"show_nav_options": "期权",
|
||||
"show_nav_options_review": "期权复盘",
|
||||
@@ -45,11 +51,14 @@ DISPLAY_LABELS: dict[str, str] = {
|
||||
|
||||
NAV_TAB_ALLOWED: dict[str, str] = {
|
||||
"dashboard": "show_nav_dashboard",
|
||||
"key_monitor": "show_nav_key_monitor",
|
||||
"trade": "show_nav_trade",
|
||||
"strategy": "show_nav_strategy",
|
||||
"strategy_records": "show_nav_strategy_records",
|
||||
"records": "show_nav_records",
|
||||
"stats": "show_nav_stats",
|
||||
"risk_policy": "show_nav_risk_policy",
|
||||
"system_guide": "show_nav_system_guide",
|
||||
"env_config": "show_nav_env_config",
|
||||
"options": "show_nav_options",
|
||||
"options_review": "show_nav_options_review",
|
||||
@@ -107,11 +116,14 @@ def tab_allowed(tab: str, display: Optional[dict[str, bool]] = None) -> bool:
|
||||
def display_meta_for_ui() -> list[dict[str, Any]]:
|
||||
nav_keys = [
|
||||
"show_nav_dashboard",
|
||||
"show_nav_key_monitor",
|
||||
"show_nav_trade",
|
||||
"show_nav_strategy",
|
||||
"show_nav_strategy_records",
|
||||
"show_nav_records",
|
||||
"show_nav_stats",
|
||||
"show_nav_risk_policy",
|
||||
"show_nav_system_guide",
|
||||
"show_nav_env_config",
|
||||
"show_nav_options",
|
||||
"show_nav_options_review",
|
||||
|
||||
@@ -22,6 +22,7 @@ EMBED_TABS: tuple[str, ...] = (
|
||||
"records",
|
||||
"stats",
|
||||
"risk_policy",
|
||||
"system_guide",
|
||||
"env_config",
|
||||
"settings",
|
||||
)
|
||||
@@ -41,6 +42,7 @@ PATH_TO_EMBED_TAB: dict[str, str] = {
|
||||
"/records": "records",
|
||||
"/stats": "stats",
|
||||
"/risk_policy": "risk_policy",
|
||||
"/system_guide": "system_guide",
|
||||
"/env_config": "env_config",
|
||||
"/settings": "settings",
|
||||
}
|
||||
@@ -82,6 +84,11 @@ def embed_shell_enabled() -> bool:
|
||||
return (os.getenv("HUB_EMBED_SHELL") or "1").strip().lower() in ("1", "true", "yes", "on")
|
||||
|
||||
|
||||
_SETTINGS_SUB_TABS = frozenset(
|
||||
{"nav", "password", "transfer", "export", "options_swap", "options_transfer"}
|
||||
)
|
||||
|
||||
|
||||
def redirect_to_embed_shell_if_enabled(page: str):
|
||||
"""直连 /trade 等整页路由时,重定向到 embed 壳(顶栏常驻,tab 软切换)."""
|
||||
if not embed_shell_enabled():
|
||||
@@ -91,6 +98,12 @@ def redirect_to_embed_shell_if_enabled(page: str):
|
||||
if (request.path or "").rstrip("/") == "/embed":
|
||||
return None
|
||||
q = {k: v for k, v in request.args.items()}
|
||||
# embed 的 tab=页面名;系统设置内页签用 settings_tab,避免 /settings?tab=transfer 被覆盖成 tab=settings
|
||||
if (page or "").strip() == "settings":
|
||||
sub = (q.get("settings_tab") or "").strip()
|
||||
legacy = (q.get("tab") or "").strip()
|
||||
if not sub and legacy in _SETTINGS_SUB_TABS:
|
||||
q["settings_tab"] = legacy
|
||||
q["tab"] = page
|
||||
q["embed"] = "1"
|
||||
return redirect("/embed?" + urlencode(q))
|
||||
@@ -113,6 +126,11 @@ def rewrite_embed_dest(path: str, hub_theme: str | None = None) -> str:
|
||||
tab = path_to_embed_tab(split.path)
|
||||
q = dict(parse_qsl(split.query, keep_blank_values=True))
|
||||
if tab:
|
||||
if tab == "settings":
|
||||
sub = (q.get("settings_tab") or "").strip()
|
||||
legacy = (q.get("tab") or "").strip()
|
||||
if not sub and legacy in _SETTINGS_SUB_TABS:
|
||||
q["settings_tab"] = legacy
|
||||
q["tab"] = tab
|
||||
q["embed"] = "1"
|
||||
ht = (hub_theme or q.get("hub_theme") or "").strip().lower()
|
||||
|
||||
@@ -8,6 +8,7 @@ from lib.key_monitor.key_auto_order_lib import load_key_auto_order_enabled
|
||||
from lib.trade.account_risk_lib import (
|
||||
cooling_hours_manual,
|
||||
cooling_hours_manual_journal,
|
||||
daily_loss_limit,
|
||||
manual_close_daily_limit,
|
||||
max_active_positions_from_env,
|
||||
mood_issues_daily_freeze_enabled,
|
||||
@@ -53,6 +54,7 @@ def build_instance_settings_view(
|
||||
risk_status: Optional[dict[str, Any]] = None,
|
||||
trade_policy: Optional[TradePolicy] = None,
|
||||
data_export_version: int = 3,
|
||||
open_guard_enabled: Optional[bool] = None,
|
||||
) -> dict[str, Any]:
|
||||
rs = risk_status or {}
|
||||
sizing_mode = load_position_sizing_mode()
|
||||
@@ -63,6 +65,11 @@ def build_instance_settings_view(
|
||||
force_close_on = _env_bool("FORCE_CLOSE_ENABLED", False)
|
||||
force_close_hour = _env_int("FORCE_CLOSE_BJ_HOUR", 0)
|
||||
auto_transfer_on = _env_bool("AUTO_TRANSFER_ENABLED", False)
|
||||
guard_on = (
|
||||
bool(open_guard_enabled)
|
||||
if open_guard_enabled is not None
|
||||
else _env_bool("TRADING_DAY_RESET_OPEN_GUARD_ENABLED", True)
|
||||
)
|
||||
|
||||
sections: list[dict[str, Any]] = []
|
||||
|
||||
@@ -79,6 +86,12 @@ def build_instance_settings_view(
|
||||
f"北京时间 {reset_hour}:00",
|
||||
"新交易日统计与部分开仓限制以此为准",
|
||||
),
|
||||
_row(
|
||||
"允许北京时间切点前开仓",
|
||||
"已放开(允许开仓)" if not guard_on else "已限制(禁止开仓)",
|
||||
f"关闭限制后,{reset_hour}:00 前也可斐波成交登记与人工下单;"
|
||||
"环境配置「切点前禁止新开仓」(TRADING_DAY_RESET_OPEN_GUARD_ENABLED)",
|
||||
),
|
||||
_row(
|
||||
"单日开仓提醒",
|
||||
f"第 {alert_threshold} 次",
|
||||
@@ -101,6 +114,15 @@ def build_instance_settings_view(
|
||||
_row("手动平仓冷静", f"{cooling_hours_manual():g} 小时"),
|
||||
_row("复盘后冷静", f"{cooling_hours_manual_journal():g} 小时", "手动平仓且填写说明后可缩短"),
|
||||
_row("日手动平仓上限", f"{manual_close_daily_limit()} 次", "超限当日冻结"),
|
||||
_row(
|
||||
"日亏损次数上限",
|
||||
(
|
||||
f"{daily_loss_limit()} 次"
|
||||
if daily_loss_limit() > 0
|
||||
else "未启用"
|
||||
),
|
||||
"平仓亏损达限后当日冻结开仓;0=不启用" if daily_loss_limit() > 0 else "RISK_DAILY_LOSS_LIMIT=0",
|
||||
),
|
||||
_row(
|
||||
"复盘情绪日冻结",
|
||||
_on_off(mood_issues_daily_freeze_enabled()),
|
||||
@@ -202,6 +224,10 @@ def build_settings_tabs(display: dict[str, Any] | None, instance_settings: dict[
|
||||
|
||||
def settings_page_context(page: str, *, instance_base_dir: str | None = None, **kwargs: Any) -> dict[str, Any]:
|
||||
p = (page or "").strip()
|
||||
if p == "system_guide":
|
||||
from lib.instance.instance_system_guide_lib import system_guide_template_context
|
||||
|
||||
return system_guide_template_context()
|
||||
if p not in ("settings", "risk_policy", "env_config"):
|
||||
return {}
|
||||
display = kwargs.pop("display", None)
|
||||
|
||||
@@ -11,6 +11,7 @@ from lib.env.env_file_lib import apply_env_updates, env_get, read_env_lines
|
||||
from lib.env.env_ui_manifest import (
|
||||
build_env_ui_payload,
|
||||
filter_updates_for_ui,
|
||||
coerce_hedge_partial_close_with_manual,
|
||||
validate_env_ui_updates,
|
||||
)
|
||||
from lib.env.env_schema import parse_env_example_schema
|
||||
@@ -102,6 +103,7 @@ def register_instance_settings_routes(
|
||||
clean, errors = validate_env_ui_updates(exchange_key, example_path, updates)
|
||||
if errors:
|
||||
return jsonify({"ok": False, "msg": "; ".join(errors)}), 400
|
||||
clean = coerce_hedge_partial_close_with_manual(clean, env_path=env_path)
|
||||
if not clean:
|
||||
return jsonify({"ok": True, "changed_keys": [], "restart_required": False})
|
||||
changed = apply_env_updates(env_path, clean)
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
"""实例「系统说明」:加载 Markdown,生成 h2 目录与带锚点正文."""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from functools import lru_cache
|
||||
from html import escape
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from lib.hub.hub_strategy_lib import render_markdown_html
|
||||
from lib.paths import REPO_ROOT
|
||||
|
||||
|
||||
def system_guide_md_path() -> Path:
|
||||
return REPO_ROOT / "docs" / "系统说明.md"
|
||||
|
||||
|
||||
def _slugify(text: str) -> str:
|
||||
raw = re.sub(r"<[^>]+>", "", text or "")
|
||||
raw = re.sub(r"\s+", "-", raw.strip())
|
||||
raw = re.sub(r"[^\w\u4e00-\u9fff\-]+", "", raw)
|
||||
return raw[:80] or "section"
|
||||
|
||||
|
||||
def _inject_h2_ids(html: str) -> tuple[str, list[dict[str, str]]]:
|
||||
"""为 h2 注入 id,并收集目录(仅 h2)."""
|
||||
toc: list[dict[str, str]] = []
|
||||
used: dict[str, int] = {}
|
||||
|
||||
def repl(m: re.Match[str]) -> str:
|
||||
inner = m.group(1)
|
||||
base = _slugify(inner)
|
||||
n = used.get(base, 0) + 1
|
||||
used[base] = n
|
||||
hid = base if n == 1 else f"{base}-{n}"
|
||||
toc.append({"id": hid, "title": re.sub(r"<[^>]+>", "", inner).strip()})
|
||||
return f'<h2 id="{escape(hid)}">{inner}</h2>'
|
||||
|
||||
out = re.sub(r"<h2>(.*?)</h2>", repl, html, flags=re.I | re.S)
|
||||
return out, toc
|
||||
|
||||
|
||||
@lru_cache(maxsize=4)
|
||||
def _load_payload_cached(mtime_ns: int, path_str: str) -> dict[str, Any]:
|
||||
path = Path(path_str)
|
||||
try:
|
||||
md_text = path.read_text(encoding="utf-8")
|
||||
except OSError:
|
||||
md_text = "# 系统说明缺失\n\n未找到 `docs/系统说明.md`。"
|
||||
body = render_markdown_html(md_text)
|
||||
body, toc = _inject_h2_ids(body)
|
||||
return {"html": body, "toc": toc, "mtime_ns": mtime_ns}
|
||||
|
||||
|
||||
def load_system_guide_payload() -> dict[str, Any]:
|
||||
path = system_guide_md_path()
|
||||
try:
|
||||
mtime_ns = path.stat().st_mtime_ns
|
||||
except OSError:
|
||||
mtime_ns = 0
|
||||
return dict(_load_payload_cached(mtime_ns, str(path)))
|
||||
|
||||
|
||||
def system_guide_template_context() -> dict[str, Any]:
|
||||
payload = load_system_guide_payload()
|
||||
return {
|
||||
"system_guide_html": payload.get("html") or "",
|
||||
"system_guide_toc": payload.get("toc") or [],
|
||||
}
|
||||
@@ -19,7 +19,12 @@ def register_trade_records_api(
|
||||
filter_trade_records_excluding_miss: Callable[[list], list],
|
||||
app_tz: Any,
|
||||
format_price_fn: Callable[[Any, Any], str] | None = None,
|
||||
sync_exchange_pnl_fn: Callable[[Any], Any] | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
sync_exchange_pnl_fn(conn): 可选,列表前节流回填交易所已实现盈亏.
|
||||
中控只走本 API,不经实例整页渲染,必须在此触发,否则盈亏U会一直显示「估」.
|
||||
"""
|
||||
from lib.instance.records_list_lib import list_trade_records_page
|
||||
|
||||
@app.route("/api/trade_records")
|
||||
@@ -40,6 +45,11 @@ def register_trade_records_api(
|
||||
offset = 0
|
||||
conn = get_db()
|
||||
try:
|
||||
if sync_exchange_pnl_fn is not None:
|
||||
try:
|
||||
sync_exchange_pnl_fn(conn)
|
||||
except Exception:
|
||||
pass
|
||||
payload = list_trade_records_page(
|
||||
conn,
|
||||
start_bj,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{# 系统设置 · 导航显示开关(SSR 预渲染,保存仍走 API) #}
|
||||
<div class="settings-tab-inner" id="display-prefs-card">
|
||||
<h2>导航显示</h2>
|
||||
<p class="settings-env-hint">以下开关控制顶栏导航与系统设置内区块是否显示,保存后立即生效.关键位监控,实盘下单,系统设置为固定项.</p>
|
||||
<p class="settings-env-hint">以下开关控制顶栏导航与系统设置内区块是否显示,保存后立即生效.系统设置为固定项.</p>
|
||||
<div id="display-prefs-form" class="display-prefs-form" data-prefs-ssr="1">
|
||||
{% if display_meta %}
|
||||
{% for group in display_meta %}
|
||||
@@ -10,7 +10,7 @@
|
||||
<div class="display-prefs-checks">
|
||||
{% for item in group.entries %}
|
||||
<label class="chk-label">
|
||||
<input type="checkbox" data-pref-key="{{ item.key }}"{% if display.get(item.key, true) %} checked{% endif %}>
|
||||
<input type="checkbox" data-pref-key="{{ item.key }}"{% if item.key in ('show_nav_dashboard', 'show_nav_system_guide') %}{% if display.get(item.key) %} checked{% endif %}{% elif display.get(item.key, true) %} checked{% endif %}>
|
||||
{{ item.label }}
|
||||
</label>
|
||||
{% endfor %}
|
||||
|
||||
@@ -314,6 +314,10 @@
|
||||
{% include 'risk_policy_panel.html' %}
|
||||
{% endif %}
|
||||
|
||||
{% if page == 'system_guide' %}
|
||||
{% include 'system_guide_panel.html' %}
|
||||
{% endif %}
|
||||
|
||||
{% if page == 'settings' %}
|
||||
{% include 'settings_panel.html' %}
|
||||
{% endif %}
|
||||
|
||||
@@ -4,10 +4,11 @@
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
|
||||
<script src="/static/instance_theme.js?v=50"></script>
|
||||
<script src="/static/autofill_guard.js?v=1"></script>
|
||||
<link rel="stylesheet" href="/static/instance_theme_early.css?v=4">
|
||||
<link rel="stylesheet" href="/static/account_risk_badge.css?v=4">
|
||||
<link rel="stylesheet" href="/static/instance_page.css?v=10">
|
||||
<link rel="stylesheet" href="/static/instance_theme.css?v=97">
|
||||
<link rel="stylesheet" href="/static/instance_page.css?v=11">
|
||||
<link rel="stylesheet" href="/static/instance_theme.css?v=108">
|
||||
<script src="/static/account_risk_badge.js?v=4"></script>
|
||||
<meta name="theme-color" content="#0b0d14">
|
||||
<title>{{ pwa_app_name }}</title>
|
||||
@@ -30,8 +31,8 @@
|
||||
</div>
|
||||
<nav class="top-nav embed-top-nav" aria-label="实例导航">
|
||||
<a href="/dashboard" data-embed-tab="dashboard" class="{% if initial_tab == 'dashboard' %}active{% endif %}"{% if not display.show_nav_dashboard %} style="display:none"{% endif %}>数据看板</a>
|
||||
<a href="/key_monitor" data-embed-tab="key_monitor" class="{% if initial_tab == 'key_monitor' %}active{% endif %}">关键位监控</a>
|
||||
<a href="/trade" data-embed-tab="trade" class="{% if initial_tab == 'trade' %}active{% endif %}">实盘下单</a>
|
||||
<a href="/key_monitor" data-embed-tab="key_monitor" class="{% if initial_tab == 'key_monitor' %}active{% endif %}"{% if not display.show_nav_key_monitor %} style="display:none"{% endif %}>关键位监控</a>
|
||||
<a href="/trade" data-embed-tab="trade" class="{% if initial_tab == 'trade' %}active{% endif %}"{% if not display.show_nav_trade %} style="display:none"{% endif %}>实盘下单</a>
|
||||
{% if not intraday_discipline and display.show_nav_strategy %}
|
||||
<a href="/strategy" data-embed-tab="strategy" class="{% if initial_tab == 'strategy' %}active{% endif %}">策略交易</a>
|
||||
{% endif %}
|
||||
@@ -56,6 +57,7 @@
|
||||
{% if display.show_nav_risk_policy %}
|
||||
<a href="/risk_policy" data-embed-tab="risk_policy" class="{% if initial_tab == 'risk_policy' %}active{% endif %}">风控说明</a>
|
||||
{% endif %}
|
||||
<a href="/system_guide" data-embed-tab="system_guide" class="{% if initial_tab == 'system_guide' %}active{% endif %}"{% if not display.show_nav_system_guide %} style="display:none"{% endif %}>系统说明</a>
|
||||
{% if display.show_nav_env_config %}
|
||||
<a href="/env_config" data-embed-tab="env_config" class="{% if initial_tab == 'env_config' %}active{% endif %}">env配置</a>
|
||||
{% endif %}
|
||||
@@ -64,7 +66,7 @@
|
||||
<div id="embed-flash" class="flash" style="display:none" role="status"></div>
|
||||
|
||||
{% include 'instance_header_panel.html' %}
|
||||
{% if initial_tab not in ('settings', 'risk_policy', 'env_config') and include_transfer_block %}
|
||||
{% if initial_tab not in ('settings', 'risk_policy', 'system_guide', 'env_config') and include_transfer_block %}
|
||||
{% include 'instance_top_bar.html' %}
|
||||
{% endif %}
|
||||
|
||||
@@ -91,8 +93,56 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 手机端主导航(≤720px);桌面不显示 -->
|
||||
<nav id="inst-mobile-tabbar" class="inst-mobile-tabbar" aria-label="手机主导航">
|
||||
<a href="/trade" class="inst-m-tab{% if initial_tab == 'trade' %} active{% endif %}" data-embed-tab="trade"{% if not display.show_nav_trade %} style="display:none"{% endif %}>下单</a>
|
||||
<a href="/key_monitor" class="inst-m-tab{% if initial_tab == 'key_monitor' %} active{% endif %}" data-embed-tab="key_monitor"{% if not display.show_nav_key_monitor %} style="display:none"{% endif %}>关键位</a>
|
||||
{% if options_nav_visible and display.show_nav_options %}
|
||||
<a href="/options" class="inst-m-tab{% if initial_tab == 'options' %} active{% endif %}" data-embed-tab="options">期权</a>
|
||||
{% endif %}
|
||||
<button type="button" class="inst-m-tab" data-embed-tab="more" id="inst-m-tab-more" aria-haspopup="dialog" aria-expanded="false">更多</button>
|
||||
</nav>
|
||||
<div id="inst-mobile-more" class="inst-mobile-more" aria-hidden="true">
|
||||
<div class="inst-mobile-more-backdrop" id="inst-mobile-more-backdrop"></div>
|
||||
<div class="inst-mobile-more-sheet" role="dialog" aria-modal="true" aria-labelledby="inst-mobile-more-title">
|
||||
<div class="inst-mobile-more-handle" aria-hidden="true"></div>
|
||||
<h2 id="inst-mobile-more-title" class="inst-mobile-more-title">更多</h2>
|
||||
<p class="inst-mobile-more-hint">次要页面 · 完整界面请用电脑</p>
|
||||
<nav class="inst-mobile-more-nav" aria-label="更多页面">
|
||||
<a href="/dashboard" data-embed-tab="dashboard"{% if not display.show_nav_dashboard %} style="display:none"{% endif %}>数据看板</a>
|
||||
{% if display.show_nav_records %}
|
||||
<a href="/records" data-embed-tab="records">交易记录</a>
|
||||
{% endif %}
|
||||
{% if not intraday_discipline and display.show_nav_strategy %}
|
||||
<a href="/strategy" data-embed-tab="strategy">策略交易</a>
|
||||
{% endif %}
|
||||
{% if not intraday_discipline and display.show_nav_strategy_records %}
|
||||
<a href="/strategy/records" data-embed-tab="strategy_records">策略记录</a>
|
||||
{% endif %}
|
||||
{% if display.show_nav_stats %}
|
||||
<a href="/stats" data-embed-tab="stats">统计分析</a>
|
||||
{% endif %}
|
||||
{% if options_nav_visible and display.show_nav_options_review %}
|
||||
<a href="/options/review" data-embed-tab="options_review">期权复盘</a>
|
||||
{% endif %}
|
||||
{% if hedge_plan_nav_visible and display.show_nav_hedge_plan %}
|
||||
<a href="/hedge-plan" data-embed-tab="hedge_plan">对冲计划</a>
|
||||
{% endif %}
|
||||
{% if display.show_nav_risk_policy %}
|
||||
<a href="/risk_policy" data-embed-tab="risk_policy">风控说明</a>
|
||||
{% endif %}
|
||||
<a href="/system_guide" data-embed-tab="system_guide"{% if not display.show_nav_system_guide %} style="display:none"{% endif %}>系统说明</a>
|
||||
{% if display.show_nav_env_config %}
|
||||
<a href="/env_config" data-embed-tab="env_config">env配置</a>
|
||||
{% endif %}
|
||||
<a href="/settings" data-embed-tab="settings">系统设置</a>
|
||||
</nav>
|
||||
<button type="button" class="inst-mobile-more-close" id="inst-mobile-more-close">关闭</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="/static/instance_ui.js?v=10"></script>
|
||||
<script src="/static/journal_upload_slots.js?v=3"></script>
|
||||
<script src="/static/journal_upload_slots.js?v=4"></script>
|
||||
<script src="/static/instance_records_mobile.js?v=2"></script>
|
||||
<script src="/static/time_close_ui.js?v=3"></script>
|
||||
<script src="/static/ai_review_render.js?v=2"></script>
|
||||
@@ -116,8 +166,9 @@ const ORDER_ENTRY_MODEL_CODE_TO_CATEGORY = {{ entry_model_code_to_category | toj
|
||||
<script>
|
||||
window.__INSTANCE_DISPLAY__ = {{ display | tojson }};
|
||||
</script>
|
||||
<script src="/static/instance_settings_prefs.js?v=14"></script>
|
||||
<script src="/static/instance_settings_prefs.js?v=16"></script>
|
||||
<script src="/static/instance_live.js?v=6"></script>
|
||||
<script src="/static/instance_embed.js?v=27"></script>
|
||||
<script src="/static/instance_embed.js?v=29"></script>
|
||||
<script src="/static/instance_mobile_nav.js?v=2"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -64,7 +64,13 @@
|
||||
type="password"
|
||||
data-env-key="{{ field.key }}"
|
||||
placeholder="{% if field.has_value %}修改时填写新值,留空不修改{% else %}请输入{% endif %}"
|
||||
autocomplete="off"
|
||||
autocomplete="new-password"
|
||||
data-lpignore="true"
|
||||
data-1p-ignore="true"
|
||||
data-bwignore="true"
|
||||
data-form-type="other"
|
||||
readonly
|
||||
onfocus="this.removeAttribute('readonly')"
|
||||
>
|
||||
{% else %}
|
||||
<input
|
||||
@@ -73,6 +79,14 @@
|
||||
type="text"
|
||||
data-env-key="{{ field.key }}"
|
||||
value="{{ field.current or field.default or '' }}"
|
||||
autocomplete="off"
|
||||
autocorrect="off"
|
||||
autocapitalize="off"
|
||||
spellcheck="false"
|
||||
data-lpignore="true"
|
||||
data-1p-ignore="true"
|
||||
data-bwignore="true"
|
||||
data-form-type="other"
|
||||
>
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
|
||||
<script src="/static/instance_theme.js?v=50"></script>
|
||||
<script src="/static/autofill_guard.js?v=1"></script>
|
||||
<link rel="stylesheet" href="/static/instance_theme_early.css?v=4">
|
||||
<link rel="stylesheet" href="/static/account_risk_badge.css?v=4">
|
||||
<script src="/static/account_risk_badge.js?v=4"></script>
|
||||
@@ -16,8 +17,8 @@
|
||||
<link rel="apple-touch-icon" href="/static/icons/apple-touch-icon.png">
|
||||
<link rel="manifest" href="/static/icons/manifest.webmanifest">
|
||||
<title>{{ pwa_app_name }}</title>
|
||||
<link rel="stylesheet" href="/static/instance_page.css?v=10">
|
||||
<link rel="stylesheet" href="/static/instance_theme.css?v=97">
|
||||
<link rel="stylesheet" href="/static/instance_page.css?v=11">
|
||||
<link rel="stylesheet" href="/static/instance_theme.css?v=105">
|
||||
|
||||
</head>
|
||||
<body
|
||||
@@ -117,8 +118,8 @@
|
||||
</div>
|
||||
<div class="top-nav">
|
||||
<a href="/dashboard" data-embed-tab="dashboard" class="{% if page == 'dashboard' %}active{% endif %}"{% if not display.show_nav_dashboard %} style="display:none"{% endif %}>数据看板</a>
|
||||
<a href="/key_monitor" class="{% if page == 'key_monitor' %}active{% endif %}">关键位监控</a>
|
||||
<a href="/trade" class="{% if page == 'trade' %}active{% endif %}">实盘下单</a>
|
||||
<a href="/key_monitor" class="{% if page == 'key_monitor' %}active{% endif %}"{% if not display.show_nav_key_monitor %} style="display:none"{% endif %}>关键位监控</a>
|
||||
<a href="/trade" class="{% if page == 'trade' %}active{% endif %}"{% if not display.show_nav_trade %} style="display:none"{% endif %}>实盘下单</a>
|
||||
{% if not intraday_discipline and display.show_nav_strategy %}
|
||||
<a href="/strategy" class="{% if page in ('strategy', 'strategy_trend', 'strategy_roll') %}active{% endif %}">策略交易</a>
|
||||
{% endif %}
|
||||
@@ -143,6 +144,7 @@
|
||||
{% if display.show_nav_risk_policy %}
|
||||
<a href="/risk_policy" class="{% if page == 'risk_policy' %}active{% endif %}">风控说明</a>
|
||||
{% endif %}
|
||||
<a href="/system_guide" class="{% if page == 'system_guide' %}active{% endif %}"{% if not display.show_nav_system_guide %} style="display:none"{% endif %}>系统说明</a>
|
||||
{% if display.show_nav_env_config %}
|
||||
<a href="/env_config" class="{% if page == 'env_config' %}active{% endif %}">env配置</a>
|
||||
{% endif %}
|
||||
@@ -151,7 +153,7 @@
|
||||
{% with msg=get_flashed_messages() %}{% if msg %}<div class="flash">{{ msg[0] }}</div>{% endif %}{% endwith %}
|
||||
|
||||
{% include 'instance_header_panel.html' %}
|
||||
{% if page not in ('settings', 'risk_policy', 'env_config', 'options', 'options_review', 'hedge_plan') %}
|
||||
{% if page not in ('settings', 'risk_policy', 'system_guide', 'env_config', 'options', 'options_review', 'hedge_plan') %}
|
||||
{% include 'instance_top_bar.html' %}
|
||||
{% endif %}
|
||||
|
||||
@@ -390,6 +392,10 @@
|
||||
{% include 'risk_policy_panel.html' %}
|
||||
{% endif %}
|
||||
|
||||
{% if page == 'system_guide' %}
|
||||
{% include 'system_guide_panel.html' %}
|
||||
{% endif %}
|
||||
|
||||
{% if page == 'settings' %}
|
||||
{% include 'settings_panel.html' %}
|
||||
{% endif %}
|
||||
@@ -451,7 +457,7 @@
|
||||
</div>
|
||||
|
||||
<script src="/static/instance_ui.js?v=10"></script>
|
||||
<script src="/static/journal_upload_slots.js?v=3"></script>
|
||||
<script src="/static/journal_upload_slots.js?v=4"></script>
|
||||
<script src="/static/instance_records_mobile.js?v=2"></script>
|
||||
<script src="/static/time_close_ui.js?v=3"></script>
|
||||
<script src="/static/ai_review_render.js?v=2"></script>
|
||||
@@ -2014,6 +2020,6 @@ document.addEventListener("DOMContentLoaded", function () {
|
||||
});
|
||||
{% endif %}
|
||||
</script>
|
||||
<script src="/static/instance_settings_prefs.js?v=14"></script>
|
||||
<script src="/static/instance_settings_prefs.js?v=15"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,7 +1,7 @@
|
||||
{# 统一顶栏:状态 + 筛选(上)· 统计条(下) #}
|
||||
<div class="instance-header-panel card">
|
||||
<div class="instance-header-toolbar">
|
||||
<div class="instance-header-toolbar-filter">
|
||||
<div class="instance-header-toolbar-filter instance-desktop-only">
|
||||
<span class="list-window-label" title="列表按 UTC 时间筛选,默认本月">UTC {{ list_window.label }}</span>
|
||||
<label class="list-window-preset">预设
|
||||
<select id="win-preset-select" onchange="toggleListWindowCustom()">
|
||||
@@ -37,4 +37,18 @@
|
||||
<div class="instance-header-stats-wrap instance-desktop-only">
|
||||
{% include 'instance_header_stats.html' %}
|
||||
</div>
|
||||
<div class="instance-header-phone-strip instance-phone-only" aria-label="手机资金摘要">
|
||||
<span class="inst-phone-chip">
|
||||
<em>交易</em>
|
||||
<b data-funds-field="current-capital">{{ funds_fmt(current_capital) }}U</b>
|
||||
</span>
|
||||
<span class="inst-phone-chip">
|
||||
<em>资金</em>
|
||||
<b data-funds-field="total-capital">{% if funding_usdt is not none %}{{ funds_fmt(funding_usdt) }}U{% else %}—{% endif %}</b>
|
||||
</span>
|
||||
<span class="inst-phone-chip">
|
||||
<em>总资</em>
|
||||
<b data-funds-field="total-funds">{% if total_funds is not none %}{{ funds_fmt(total_funds) }}U{% else %}—{% endif %}</b>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,15 +1,4 @@
|
||||
{# 三所统一顶栏:实时价 + 可选整点前开仓开关(划转已移至系统设置) #}
|
||||
{# 三所统一顶栏:实时价(划转已移至系统设置;切点前开仓说明见风控说明·交易执行) #}
|
||||
<div class="rule-tip instance-price-bar">
|
||||
实时价格更新:<span id="price-last-updated">--</span>(北京时间 UTC+8)
|
||||
</div>
|
||||
{% if ui_open_guard_enabled %}
|
||||
<div class="rule-tip" id="open-guard-bar" style="display:flex;align-items:center;gap:10px;flex-wrap:wrap">
|
||||
<label style="display:flex;align-items:center;gap:6px;cursor:pointer;color:#cfd3ef">
|
||||
<input type="checkbox" id="allow-open-before-reset" {% if not open_guard_enabled %}checked{% endif %}>
|
||||
允许北京时间 {{ reset_hour }}:00 前开仓(斐波成交登记,人工下单)
|
||||
</label>
|
||||
<span id="open-guard-status" style="color:#8892b0;font-size:.75rem">
|
||||
{% if open_guard_enabled %}已限制:{{ reset_hour }}:00 前不可开仓{% else %}已放开:{{ reset_hour }}:00 前允许开仓{% endif %}
|
||||
</span>
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
@@ -8,14 +8,17 @@
|
||||
不足从 <code>{{ auto_transfer_from }}</code> 划入,超出划回 <code>{{ auto_transfer_from }}</code>;
|
||||
<strong>持仓中不划转</strong>并微信通知.
|
||||
</p>
|
||||
<form action="/manual_transfer" method="post" class="form-row gate-transfer-form settings-transfer-form">
|
||||
<input name="amount" type="number" min="0.01" step="0.01" placeholder="手动划转金额 U" required>
|
||||
<select name="from_account" aria-label="划出账户">
|
||||
<form action="/manual_transfer" method="post" class="form-row gate-transfer-form settings-transfer-form" autocomplete="off">
|
||||
<input type="text" name="username" autocomplete="username" tabindex="-1" aria-hidden="true"
|
||||
style="position:absolute;left:-9999px;width:1px;height:1px;opacity:0" value="">
|
||||
<input name="amount" id="manual-xfer-amount" type="number" min="0.01" step="0.01" placeholder="手动划转金额 U" required
|
||||
autocomplete="off" inputmode="decimal" data-lpignore="true" data-1p-ignore="true" data-bwignore="true" data-form-type="other" readonly>
|
||||
<select name="from_account" aria-label="划出账户" autocomplete="off">
|
||||
<option value="funding" {% if auto_transfer_from == 'funding' %}selected{% endif %}>from: funding</option>
|
||||
<option value="swap" {% if auto_transfer_from == 'swap' %}selected{% endif %}>from: swap</option>
|
||||
<option value="spot" {% if auto_transfer_from == 'spot' %}selected{% endif %}>from: spot</option>
|
||||
</select>
|
||||
<select name="to_account" aria-label="划入账户">
|
||||
<select name="to_account" aria-label="划入账户" autocomplete="off">
|
||||
<option value="swap" {% if auto_transfer_to == 'swap' %}selected{% endif %}>to: swap</option>
|
||||
<option value="funding" {% if auto_transfer_to == 'funding' %}selected{% endif %}>to: funding</option>
|
||||
<option value="spot" {% if auto_transfer_to == 'spot' %}selected{% endif %}>to: spot</option>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{# 系统设置 · 账户密码(外层 card 由 settings_panel 提供) #}
|
||||
<h2>账户密码修改</h2>
|
||||
<p class="settings-subcard-desc">修改网页登录账号密码,写入 <code>.env</code> 后需重启实例生效.</p>
|
||||
<div class="settings-password-form">
|
||||
<div class="settings-password-form password-settings" data-password-settings="1">
|
||||
<label>当前密码 <input type="password" id="pwd-old" autocomplete="current-password"></label>
|
||||
<label>新用户名(可选) <input type="text" id="pwd-new-username" autocomplete="username"></label>
|
||||
<label>新密码 <input type="password" id="pwd-new" autocomplete="new-password"></label>
|
||||
|
||||
@@ -92,7 +92,7 @@
|
||||
<label><input type="checkbox" name="mood_issues" value="扛单">扛单</label>
|
||||
<label><input type="checkbox" name="mood_issues" value="重仓违规">重仓违规</label>
|
||||
</div>
|
||||
<textarea name="note" rows="2" placeholder="备注"></textarea>
|
||||
<textarea name="note" rows="2" placeholder="备注" autocomplete="off" data-lpignore="true" data-1p-ignore="true" data-form-type="other"></textarea>
|
||||
<button type="submit" style="margin-top:8px">保存复盘记录</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
@@ -6,9 +6,21 @@
|
||||
</div>
|
||||
|
||||
{% if settings_tabs %}
|
||||
<div class="env-config-body card settings-config-body">
|
||||
{% set _sub = (request.args.get('settings_tab') or '').strip() %}
|
||||
{% set _legacy_tab = (request.args.get('tab') or '').strip() %}
|
||||
{% set ns = namespace(active_idx=0, active_key='') %}
|
||||
{% for tab in settings_tabs %}
|
||||
{% if _sub and tab.key == _sub %}
|
||||
{% set ns.active_idx = loop.index0 %}
|
||||
{% set ns.active_key = tab.key %}
|
||||
{% elif (not _sub) and _legacy_tab and tab.key == _legacy_tab %}
|
||||
{% set ns.active_idx = loop.index0 %}
|
||||
{% set ns.active_key = tab.key %}
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
<div class="env-config-body card settings-config-body" data-settings-active-tab="{{ ns.active_key }}">
|
||||
{% for tab in settings_tabs %}
|
||||
<input type="radio" name="settings-section" id="settings-sec-{{ loop.index0 }}" class="env-tab-radio"{% if loop.first %} checked{% endif %}>
|
||||
<input type="radio" name="settings-section" id="settings-sec-{{ loop.index0 }}" class="env-tab-radio" data-settings-tab="{{ tab.key }}"{% if loop.index0 == ns.active_idx %} checked{% endif %}>
|
||||
{% endfor %}
|
||||
<div class="env-config-tabs" role="tablist" aria-label="系统设置分类">
|
||||
{% for tab in settings_tabs %}
|
||||
@@ -52,3 +64,14 @@
|
||||
{% include 'options_settings_panel.html' %}
|
||||
{% endif %}
|
||||
</div>
|
||||
<script>
|
||||
(function () {
|
||||
try {
|
||||
var q = new URLSearchParams(window.location.search || "");
|
||||
var key = (q.get("settings_tab") || "").trim();
|
||||
if (!key) return;
|
||||
var radio = document.querySelector('input.env-tab-radio[data-settings-tab="' + key + '"]');
|
||||
if (radio) radio.checked = true;
|
||||
} catch (e) {}
|
||||
})();
|
||||
</script>
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
{# 系统说明: docs/系统说明.md + h2 目录 #}
|
||||
<div class="system-guide-page full">
|
||||
<div class="card system-guide-card">
|
||||
<div class="system-guide-head">
|
||||
<h2 style="margin:0">系统说明</h2>
|
||||
<p class="muted" style="margin:6px 0 0;font-size:.85rem">操作与逻辑按章节混排。默认不在顶栏显示;可在系统设置 → 导航显示中打开。</p>
|
||||
</div>
|
||||
<div class="system-guide-layout">
|
||||
{% if system_guide_toc %}
|
||||
<aside class="system-guide-toc" aria-label="章节目录">
|
||||
<div class="system-guide-toc-title">目录</div>
|
||||
<nav>
|
||||
{% for item in system_guide_toc %}
|
||||
<a href="#{{ item.id }}">{{ item.title }}</a>
|
||||
{% endfor %}
|
||||
</nav>
|
||||
</aside>
|
||||
{% endif %}
|
||||
<article class="system-guide-body prose">
|
||||
{{ system_guide_html|safe }}
|
||||
</article>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<style>
|
||||
.system-guide-page { grid-column: 1 / -1; }
|
||||
.system-guide-card { padding: 16px 18px 28px; }
|
||||
.system-guide-layout {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(160px, 220px) minmax(0, 1fr);
|
||||
gap: 18px;
|
||||
margin-top: 14px;
|
||||
align-items: start;
|
||||
}
|
||||
.system-guide-toc {
|
||||
position: sticky;
|
||||
top: 8px;
|
||||
padding: 10px 12px;
|
||||
border: 1px solid rgba(127,127,127,.25);
|
||||
border-radius: 8px;
|
||||
background: rgba(127,127,127,.06);
|
||||
max-height: calc(100vh - 120px);
|
||||
overflow: auto;
|
||||
}
|
||||
.system-guide-toc-title {
|
||||
font-size: .78rem;
|
||||
font-weight: 600;
|
||||
opacity: .75;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
.system-guide-toc a {
|
||||
display: block;
|
||||
font-size: .84rem;
|
||||
line-height: 1.35;
|
||||
padding: 5px 0;
|
||||
text-decoration: none;
|
||||
color: inherit;
|
||||
opacity: .9;
|
||||
}
|
||||
.system-guide-toc a:hover { opacity: 1; text-decoration: underline; }
|
||||
.system-guide-body { min-width: 0; line-height: 1.65; font-size: .92rem; }
|
||||
.system-guide-body h1 { font-size: 1.35rem; margin: 0 0 12px; }
|
||||
.system-guide-body h2 { font-size: 1.12rem; margin: 22px 0 10px; padding-top: 4px; scroll-margin-top: 12px; }
|
||||
.system-guide-body h3 { font-size: 1rem; margin: 16px 0 8px; }
|
||||
.system-guide-body p, .system-guide-body li { margin: 0 0 8px; }
|
||||
.system-guide-body ul, .system-guide-body ol { padding-left: 1.35em; margin: 0 0 10px; }
|
||||
.system-guide-body table { border-collapse: collapse; width: 100%; margin: 10px 0 14px; font-size: .86rem; }
|
||||
.system-guide-body th, .system-guide-body td {
|
||||
border: 1px solid rgba(127,127,127,.35);
|
||||
padding: 7px 9px;
|
||||
text-align: left;
|
||||
vertical-align: top;
|
||||
}
|
||||
.system-guide-body code {
|
||||
font-family: ui-monospace, Consolas, monospace;
|
||||
font-size: .86em;
|
||||
padding: 1px 4px;
|
||||
border-radius: 4px;
|
||||
background: rgba(127,127,127,.12);
|
||||
}
|
||||
.system-guide-body hr { border: 0; border-top: 1px solid rgba(127,127,127,.28); margin: 18px 0; }
|
||||
@media (max-width: 820px) {
|
||||
.system-guide-layout { grid-template-columns: 1fr; }
|
||||
.system-guide-toc { position: static; max-height: none; }
|
||||
.system-guide-toc nav { display: flex; flex-wrap: wrap; gap: 4px 12px; }
|
||||
}
|
||||
</style>
|
||||
@@ -95,6 +95,14 @@ def init_options_tables(conn: sqlite3.Connection) -> None:
|
||||
ON options_target_monitors(status)
|
||||
"""
|
||||
)
|
||||
for ddl in (
|
||||
"ALTER TABLE options_trades ADD COLUMN wechat_open_sent INTEGER DEFAULT 0",
|
||||
"ALTER TABLE options_trades ADD COLUMN wechat_close_sent INTEGER DEFAULT 0",
|
||||
):
|
||||
try:
|
||||
conn.execute(ddl)
|
||||
except Exception:
|
||||
pass
|
||||
init_options_review_tables(conn)
|
||||
|
||||
|
||||
|
||||
@@ -52,12 +52,14 @@ def build_options_hub_snapshot(cfg: dict[str, Any]) -> dict[str, Any]:
|
||||
)
|
||||
|
||||
inst = str(p.get("inst_id") or "")
|
||||
source_key, source_label = _resolve_options_source(conn, inst)
|
||||
source_key, source_label, source_plan_id = _resolve_options_source(conn, inst)
|
||||
p["source"] = source_key
|
||||
p["source_label"] = source_label
|
||||
p["source_plan_id"] = source_plan_id
|
||||
p["target_monitor_text"] = _format_options_target(p)
|
||||
except Exception:
|
||||
p.setdefault("source_label", "—")
|
||||
p.setdefault("source_plan_id", None)
|
||||
p.setdefault("target_monitor_text", "—")
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
@@ -1,13 +1,17 @@
|
||||
"""期权持仓监控:浮盈翻倍微信提醒 + 平仓/到期状态同步."""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sqlite3
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, Callable
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from lib.exchange.okx_options_lib import normalize_option_exp_ms, resolve_option_close_from_history
|
||||
|
||||
_APP_TZ = ZoneInfo((os.getenv("APP_TIMEZONE") or os.getenv("TZ") or "Asia/Shanghai").strip() or "Asia/Shanghai")
|
||||
|
||||
|
||||
def _safe_float(v: Any) -> float | None:
|
||||
if v is None:
|
||||
@@ -121,25 +125,119 @@ def run_options_profit_alerts(
|
||||
|
||||
|
||||
def _created_at_ms(created_at: Any) -> int | None:
|
||||
"""墙钟 created_at → UTC ms.库内时间为业务时区(默认 Asia/Shanghai),不可当 UTC."""
|
||||
if not created_at:
|
||||
return None
|
||||
raw = str(created_at).strip()
|
||||
if not raw:
|
||||
return None
|
||||
for fmt in ("%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M:%f"):
|
||||
for fmt, ln in (("%Y-%m-%d %H:%M:%S", 19), ("%Y-%m-%d %H:%M:%f", 26), ("%Y-%m-%d %H:%M", 16)):
|
||||
try:
|
||||
dt = datetime.strptime(raw[:26], fmt).replace(tzinfo=timezone.utc)
|
||||
dt = datetime.strptime(raw[:ln], fmt).replace(tzinfo=_APP_TZ)
|
||||
return int(dt.timestamp() * 1000)
|
||||
except ValueError:
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def _group_key_for_closed_trade(row: Any) -> str:
|
||||
inst = str(row["inst_id"] or "").strip()
|
||||
ord_id = str(row["close_ord_id"] or "").strip() if "close_ord_id" in row.keys() else ""
|
||||
if ord_id:
|
||||
return f"{inst}|ord:{ord_id}"
|
||||
closed = str(row["closed_at"] or "").strip()
|
||||
return f"{inst}|close:{(closed[:16] if closed else '')}"
|
||||
|
||||
|
||||
def backfill_closed_options_realized_pnl_from_history(
|
||||
conn: sqlite3.Connection,
|
||||
hist_rows: list[dict[str, Any]],
|
||||
*,
|
||||
trade_limit: int = 200,
|
||||
) -> int:
|
||||
"""
|
||||
用 OKX positions-history 的 realizedPnl 覆盖本地已平记录.
|
||||
同一次平仓多笔本地 open(加仓)按权利金占比分摊交易所总盈亏.
|
||||
"""
|
||||
by_inst: dict[str, list[dict[str, Any]]] = {}
|
||||
for raw in hist_rows or []:
|
||||
if not isinstance(raw, dict):
|
||||
continue
|
||||
inst = str(raw.get("instId") or "").strip()
|
||||
if not inst:
|
||||
continue
|
||||
by_inst.setdefault(inst, []).append(raw)
|
||||
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT id, inst_id, sheets, premium_paid, realized_pnl, created_at, closed_at, close_ord_id
|
||||
FROM options_trades
|
||||
WHERE status = 'closed'
|
||||
ORDER BY id DESC
|
||||
LIMIT ?
|
||||
""",
|
||||
(int(trade_limit),),
|
||||
).fetchall()
|
||||
if not rows:
|
||||
return 0
|
||||
|
||||
groups: dict[str, list[Any]] = {}
|
||||
for row in rows:
|
||||
inst = str(row["inst_id"] or "").strip()
|
||||
if not inst or inst not in by_inst:
|
||||
continue
|
||||
groups.setdefault(_group_key_for_closed_trade(row), []).append(row)
|
||||
|
||||
updated = 0
|
||||
for group in groups.values():
|
||||
inst = str(group[0]["inst_id"] or "").strip()
|
||||
open_candidates = [_created_at_ms(r["created_at"]) for r in group]
|
||||
open_ms = min((x for x in open_candidates if x is not None), default=None)
|
||||
close_info = resolve_option_close_from_history(by_inst.get(inst) or [], open_ms=open_ms)
|
||||
if not close_info:
|
||||
continue
|
||||
ex_pnl = _safe_float(close_info.get("realized_pnl"))
|
||||
if ex_pnl is None:
|
||||
continue
|
||||
close_quote = _safe_float(close_info.get("close_quote"))
|
||||
total_paid = 0.0
|
||||
for r in group:
|
||||
total_paid += float(_safe_float(r["premium_paid"]) or 0.0)
|
||||
allocated = 0.0
|
||||
for i, r in enumerate(group):
|
||||
paid = float(_safe_float(r["premium_paid"]) or 0.0)
|
||||
if i == len(group) - 1:
|
||||
share = round(float(ex_pnl) - allocated, 4)
|
||||
elif total_paid > 0:
|
||||
share = round(float(ex_pnl) * (paid / total_paid), 4)
|
||||
allocated += share
|
||||
else:
|
||||
share = round(float(ex_pnl) / len(group), 4)
|
||||
allocated += share
|
||||
local = _safe_float(r["realized_pnl"])
|
||||
if local is not None and abs(local - share) < 1e-6:
|
||||
continue
|
||||
prem_recv = round(paid + share, 4)
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE options_trades
|
||||
SET realized_pnl = ?,
|
||||
premium_received = ?,
|
||||
close_quote = COALESCE(?, close_quote)
|
||||
WHERE id = ?
|
||||
""",
|
||||
(share, prem_recv, close_quote, int(r["id"])),
|
||||
)
|
||||
updated += 1
|
||||
return updated
|
||||
|
||||
|
||||
def sync_open_options_trades(
|
||||
conn: sqlite3.Connection,
|
||||
*,
|
||||
live_inst_ids: set[str],
|
||||
fetch_history_fn: Callable[[str], list[dict[str, Any]]],
|
||||
notify_cfg: dict[str, Any] | None = None,
|
||||
) -> int:
|
||||
"""
|
||||
交易所已无持仓时,将本地 open 记录同步为 closed.
|
||||
@@ -222,6 +320,24 @@ def sync_open_options_trades(
|
||||
),
|
||||
)
|
||||
updated += 1
|
||||
if notify_cfg is not None:
|
||||
try:
|
||||
from lib.options.options_notify_lib import notify_options_close
|
||||
|
||||
reason = "到期结算" if close_reason == "expired" else "交易所平仓"
|
||||
notify_options_close(
|
||||
notify_cfg,
|
||||
conn,
|
||||
inst_id=inst_id,
|
||||
reason=reason,
|
||||
trade_id=int(row["id"]),
|
||||
premium_paid=paid,
|
||||
premium_received=prem_recv,
|
||||
realized_pnl=realized_pnl,
|
||||
close_quote=close_quote,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return updated
|
||||
|
||||
|
||||
@@ -317,6 +433,7 @@ def options_monitor_loop(
|
||||
close_fn=target_close_fn,
|
||||
send_wechat=send_wechat,
|
||||
account_label=account_label,
|
||||
cfg={"send_wechat": send_wechat, "account_label": account_label},
|
||||
)
|
||||
if sync_trades_fn is not None:
|
||||
sync_trades_fn(conn)
|
||||
|
||||
@@ -0,0 +1,330 @@
|
||||
"""OKX 期权开仓/平仓企业微信推送(必发,幂等落库标记)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlite3
|
||||
from typing import Any, Callable, Optional
|
||||
|
||||
|
||||
def _fmt(v: Any, d: int = 4) -> str:
|
||||
try:
|
||||
if v is None or v == "":
|
||||
return "—"
|
||||
return f"{float(v):.{d}f}"
|
||||
except (TypeError, ValueError):
|
||||
return str(v)
|
||||
|
||||
|
||||
def _opt_type_label(opt_type: Any) -> str:
|
||||
t = str(opt_type or "").strip().upper()
|
||||
if t in ("C", "CALL"):
|
||||
return "Call"
|
||||
if t in ("P", "PUT"):
|
||||
return "Put"
|
||||
return t or "—"
|
||||
|
||||
|
||||
def ensure_options_notify_columns(conn: sqlite3.Connection) -> None:
|
||||
for ddl in (
|
||||
"ALTER TABLE options_trades ADD COLUMN wechat_open_sent INTEGER DEFAULT 0",
|
||||
"ALTER TABLE options_trades ADD COLUMN wechat_close_sent INTEGER DEFAULT 0",
|
||||
):
|
||||
try:
|
||||
conn.execute(ddl)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def notify_options_send(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 build_options_open_message(
|
||||
*,
|
||||
account_label: str,
|
||||
inst_id: str,
|
||||
underlying: str = "",
|
||||
opt_type: Any = None,
|
||||
sheets: Any = None,
|
||||
premium_paid: Any = None,
|
||||
open_quote: Any = None,
|
||||
target_index: Any = None,
|
||||
signal_note: str = "",
|
||||
trade_id: Any = None,
|
||||
) -> str:
|
||||
lines = [
|
||||
"【OKX期权·开仓】",
|
||||
f"账户:{account_label or 'OKX期权'}",
|
||||
]
|
||||
if trade_id is not None:
|
||||
lines.append(f"本地单号:#{trade_id}")
|
||||
lines.extend(
|
||||
[
|
||||
f"合约:{inst_id}",
|
||||
f"标的:{(underlying or '—')} · {_opt_type_label(opt_type)}",
|
||||
f"张数:{sheets if sheets is not None else '—'}",
|
||||
f"开仓报价:{_fmt(open_quote)} USDC",
|
||||
f"权利金:{_fmt(premium_paid)} USDC",
|
||||
]
|
||||
)
|
||||
if target_index is not None and str(target_index).strip() != "":
|
||||
try:
|
||||
lines.append(f"目标指数:{float(target_index):g}")
|
||||
except (TypeError, ValueError):
|
||||
lines.append(f"目标指数:{target_index}")
|
||||
if signal_note:
|
||||
lines.append(f"备注:{signal_note[:200]}")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def build_options_close_message(
|
||||
*,
|
||||
account_label: str,
|
||||
inst_id: str,
|
||||
reason: str = "",
|
||||
underlying: str = "",
|
||||
opt_type: Any = None,
|
||||
sheets: Any = None,
|
||||
premium_paid: Any = None,
|
||||
premium_received: Any = None,
|
||||
realized_pnl: Any = None,
|
||||
close_quote: Any = None,
|
||||
target_index: Any = None,
|
||||
trigger_idx: Any = None,
|
||||
trade_id: Any = None,
|
||||
) -> str:
|
||||
lines = [
|
||||
"【OKX期权·平仓】",
|
||||
f"账户:{account_label or 'OKX期权'}",
|
||||
]
|
||||
if trade_id is not None:
|
||||
lines.append(f"本地单号:#{trade_id}")
|
||||
lines.extend(
|
||||
[
|
||||
f"合约:{inst_id}",
|
||||
f"标的:{(underlying or '—')} · {_opt_type_label(opt_type)}",
|
||||
f"原因:{(reason or '平仓').strip()}",
|
||||
f"张数:{sheets if sheets is not None else '—'}",
|
||||
f"平仓报价:{_fmt(close_quote)} USDC",
|
||||
f"已付/收回:{_fmt(premium_paid)} / {_fmt(premium_received)} USDC",
|
||||
f"实现盈亏:{_fmt(realized_pnl, 4)} USDC",
|
||||
]
|
||||
)
|
||||
if target_index is not None and str(target_index).strip() != "":
|
||||
try:
|
||||
lines.append(f"目标指数:{float(target_index):g}")
|
||||
except (TypeError, ValueError):
|
||||
lines.append(f"目标指数:{target_index}")
|
||||
if trigger_idx is not None and str(trigger_idx).strip() != "":
|
||||
try:
|
||||
lines.append(f"触发指数:{float(trigger_idx):g}")
|
||||
except (TypeError, ValueError):
|
||||
lines.append(f"触发指数:{trigger_idx}")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def notify_options_open(
|
||||
cfg: dict[str, Any],
|
||||
conn: sqlite3.Connection | None,
|
||||
*,
|
||||
trade_id: int | None,
|
||||
inst_id: str,
|
||||
underlying: str = "",
|
||||
opt_type: Any = None,
|
||||
sheets: Any = None,
|
||||
premium_paid: Any = None,
|
||||
open_quote: Any = None,
|
||||
target_index: Any = None,
|
||||
signal_note: str = "",
|
||||
) -> bool:
|
||||
ensure_options_notify_columns(conn) if conn is not None else None
|
||||
if conn is not None and trade_id is not None:
|
||||
row = conn.execute(
|
||||
"SELECT wechat_open_sent FROM options_trades WHERE id=?",
|
||||
(int(trade_id),),
|
||||
).fetchone()
|
||||
if row and int(row["wechat_open_sent"] or 0):
|
||||
return False
|
||||
msg = build_options_open_message(
|
||||
account_label=str(cfg.get("account_label") or "OKX期权"),
|
||||
inst_id=inst_id,
|
||||
underlying=underlying,
|
||||
opt_type=opt_type,
|
||||
sheets=sheets,
|
||||
premium_paid=premium_paid,
|
||||
open_quote=open_quote,
|
||||
target_index=target_index,
|
||||
signal_note=signal_note,
|
||||
trade_id=trade_id,
|
||||
)
|
||||
ok = notify_options_send(cfg, msg)
|
||||
if ok and conn is not None and trade_id is not None:
|
||||
conn.execute(
|
||||
"UPDATE options_trades SET wechat_open_sent=1 WHERE id=?",
|
||||
(int(trade_id),),
|
||||
)
|
||||
try:
|
||||
conn.commit()
|
||||
except Exception:
|
||||
pass
|
||||
return ok
|
||||
|
||||
|
||||
def _load_trade_row(conn: sqlite3.Connection, trade_id: int) -> dict[str, Any] | None:
|
||||
row = conn.execute("SELECT * FROM options_trades WHERE id=?", (int(trade_id),)).fetchone()
|
||||
return dict(row) if row else None
|
||||
|
||||
|
||||
def notify_options_close(
|
||||
cfg: dict[str, Any],
|
||||
conn: sqlite3.Connection | None,
|
||||
*,
|
||||
inst_id: str,
|
||||
reason: str = "平仓",
|
||||
trade_id: int | None = None,
|
||||
underlying: str = "",
|
||||
opt_type: Any = None,
|
||||
sheets: Any = None,
|
||||
premium_paid: Any = None,
|
||||
premium_received: Any = None,
|
||||
realized_pnl: Any = None,
|
||||
close_quote: Any = None,
|
||||
target_index: Any = None,
|
||||
trigger_idx: Any = None,
|
||||
force: bool = False,
|
||||
) -> bool:
|
||||
"""平仓必发.默认按 trade_id / 同合约未标记行幂等."""
|
||||
if conn is not None:
|
||||
ensure_options_notify_columns(conn)
|
||||
rows: list[dict[str, Any]] = []
|
||||
if conn is not None and trade_id is not None:
|
||||
r = _load_trade_row(conn, int(trade_id))
|
||||
if r:
|
||||
rows = [r]
|
||||
elif conn is not None and inst_id:
|
||||
q = conn.execute(
|
||||
"""
|
||||
SELECT * FROM options_trades
|
||||
WHERE inst_id=? AND status='closed'
|
||||
AND COALESCE(wechat_close_sent,0)=0
|
||||
ORDER BY id DESC
|
||||
LIMIT 20
|
||||
""",
|
||||
(inst_id,),
|
||||
).fetchall()
|
||||
rows = [dict(x) for x in q]
|
||||
if not rows and force:
|
||||
q2 = conn.execute(
|
||||
"""
|
||||
SELECT * FROM options_trades
|
||||
WHERE inst_id=? AND status='closed'
|
||||
ORDER BY id DESC LIMIT 1
|
||||
""",
|
||||
(inst_id,),
|
||||
).fetchone()
|
||||
if q2:
|
||||
rows = [dict(q2)]
|
||||
|
||||
if rows:
|
||||
# 同次平仓可能多腿:合并一条推送,逐条标记
|
||||
total_paid = sum(float(r.get("premium_paid") or 0) for r in rows)
|
||||
total_recv = sum(float(r.get("premium_received") or 0) for r in rows if r.get("premium_received") is not None)
|
||||
pnls = [float(r["realized_pnl"]) for r in rows if r.get("realized_pnl") is not None]
|
||||
total_pnl = sum(pnls) if pnls else None
|
||||
if total_pnl is None and (premium_received is not None or realized_pnl is not None):
|
||||
total_pnl = realized_pnl
|
||||
total_recv = premium_received if premium_received is not None else total_recv
|
||||
total_paid = premium_paid if premium_paid is not None else total_paid
|
||||
head = rows[0]
|
||||
pending = [r for r in rows if not int(r.get("wechat_close_sent") or 0)]
|
||||
if not pending and not force:
|
||||
return False
|
||||
msg = build_options_close_message(
|
||||
account_label=str(cfg.get("account_label") or "OKX期权"),
|
||||
inst_id=inst_id or str(head.get("inst_id") or ""),
|
||||
reason=reason,
|
||||
underlying=underlying or str(head.get("underlying") or ""),
|
||||
opt_type=opt_type or head.get("opt_type"),
|
||||
sheets=sheets if sheets is not None else sum(int(r.get("sheets") or 0) for r in rows),
|
||||
premium_paid=total_paid,
|
||||
premium_received=total_recv if rows else premium_received,
|
||||
realized_pnl=total_pnl,
|
||||
close_quote=close_quote if close_quote is not None else head.get("close_quote"),
|
||||
target_index=target_index,
|
||||
trigger_idx=trigger_idx,
|
||||
trade_id=head.get("id") if len(rows) == 1 else None,
|
||||
)
|
||||
ok = notify_options_send(cfg, msg)
|
||||
if ok and conn is not None:
|
||||
for r in pending or rows:
|
||||
conn.execute(
|
||||
"UPDATE options_trades SET wechat_close_sent=1 WHERE id=?",
|
||||
(int(r["id"]),),
|
||||
)
|
||||
try:
|
||||
conn.commit()
|
||||
except Exception:
|
||||
pass
|
||||
return ok
|
||||
|
||||
# 无库行时仍发一条(尽量不丢提醒)
|
||||
msg = build_options_close_message(
|
||||
account_label=str(cfg.get("account_label") or "OKX期权"),
|
||||
inst_id=inst_id,
|
||||
reason=reason,
|
||||
underlying=underlying,
|
||||
opt_type=opt_type,
|
||||
sheets=sheets,
|
||||
premium_paid=premium_paid,
|
||||
premium_received=premium_received,
|
||||
realized_pnl=realized_pnl,
|
||||
close_quote=close_quote,
|
||||
target_index=target_index,
|
||||
trigger_idx=trigger_idx,
|
||||
trade_id=trade_id,
|
||||
)
|
||||
return notify_options_send(cfg, msg)
|
||||
|
||||
|
||||
def notify_options_close_trade_ids(
|
||||
cfg: dict[str, Any],
|
||||
conn: sqlite3.Connection,
|
||||
trade_ids: list[int],
|
||||
*,
|
||||
reason: str,
|
||||
) -> bool:
|
||||
ids = [int(x) for x in trade_ids if x is not None]
|
||||
if not ids:
|
||||
return False
|
||||
ensure_options_notify_columns(conn)
|
||||
placeholders = ",".join("?" for _ in ids)
|
||||
rows = conn.execute(
|
||||
f"""
|
||||
SELECT * FROM options_trades
|
||||
WHERE id IN ({placeholders}) AND COALESCE(wechat_close_sent,0)=0
|
||||
""",
|
||||
ids,
|
||||
).fetchall()
|
||||
if not rows:
|
||||
return False
|
||||
first = dict(rows[0])
|
||||
return notify_options_close(
|
||||
cfg,
|
||||
conn,
|
||||
inst_id=str(first.get("inst_id") or ""),
|
||||
reason=reason,
|
||||
trade_id=int(first["id"]) if len(rows) == 1 else None,
|
||||
underlying=str(first.get("underlying") or ""),
|
||||
opt_type=first.get("opt_type"),
|
||||
sheets=sum(int(r["sheets"] or 0) for r in rows),
|
||||
premium_paid=sum(float(r["premium_paid"] or 0) for r in rows),
|
||||
premium_received=sum(float(r["premium_received"] or 0) for r in rows if r["premium_received"] is not None),
|
||||
realized_pnl=sum(float(r["realized_pnl"]) for r in rows if r["realized_pnl"] is not None),
|
||||
close_quote=first.get("close_quote"),
|
||||
)
|
||||
@@ -259,6 +259,11 @@ def eth_amount_from_sheets(sheets: int, ct_mult: float = 0.01) -> float:
|
||||
return round(int(sheets) * float(ct_mult), 8)
|
||||
|
||||
|
||||
def resolve_budget_full_usdc(trading_usdc: float, trade_budget_usdc: float) -> float:
|
||||
"""按可用余额打满:余额大于预算用预算,否则用余额."""
|
||||
return min(float(trading_usdc), float(trade_budget_usdc))
|
||||
|
||||
|
||||
def calc_order_size(
|
||||
*,
|
||||
quote_per_unit: float,
|
||||
|
||||
@@ -108,6 +108,7 @@ def _build_cfg(app_module: Any) -> dict[str, Any]:
|
||||
"default_underly": (os.getenv("OKX_OPTIONS_DEFAULT_UNDERLY") or "ETH").strip().upper(),
|
||||
"max_dte_days": _env_float("OKX_OPTIONS_MAX_DTE_DAYS", 2.0),
|
||||
"chain_max_dte_days": _env_float("OKX_OPTIONS_CHAIN_MAX_DTE_DAYS", 14.0),
|
||||
"chain_ask_liq_filter": _env_bool("OKX_OPTIONS_CHAIN_ASK_LIQ_FILTER_ENABLED", True),
|
||||
"itm_max_dist": _env_float("OKX_OPTIONS_ITM_MAX_DIST_USD", 30.0),
|
||||
"td_mode": (os.getenv("OKX_OPTIONS_TD_MODE") or "isolated").strip(),
|
||||
# 市价平仓已硬关闭(忽略 env),仅买一限价
|
||||
@@ -162,13 +163,18 @@ def _require_options_ex(cfg: dict[str, Any]):
|
||||
|
||||
|
||||
def _budget_full_usdc(cfg: dict[str, Any], ex: Any) -> tuple[float | None, str]:
|
||||
"""交易账户 USDC 可用余额(由 calc_order_size 再乘 budget_buffer 留余量)."""
|
||||
"""打满可用额度 = min(交易户可用 USDC, 单笔预算);calc_order_size 再乘 budget_buffer."""
|
||||
from lib.exchange.okx_options_lib import fetch_options_trading_usdc
|
||||
from lib.options.options_pricing_lib import resolve_budget_full_usdc
|
||||
|
||||
raw = fetch_options_trading_usdc(ex)
|
||||
if raw is None or float(raw) <= 0:
|
||||
return None, "交易账户 USDC 可用余额不足"
|
||||
return float(raw), ""
|
||||
trading = float(raw)
|
||||
cap = _env_float("OKX_OPTIONS_TRADE_BUDGET_USDC", float(cfg.get("trade_budget") or 10.0))
|
||||
if cap <= 0:
|
||||
return None, "单笔预算无效(OKX_OPTIONS_TRADE_BUDGET_USDC)"
|
||||
return resolve_budget_full_usdc(trading, float(cap)), ""
|
||||
|
||||
|
||||
def _open_premium_paid(cfg: dict[str, Any], inst_id: str) -> float | None:
|
||||
@@ -262,8 +268,12 @@ def _sync_options_trades(
|
||||
if not force and now - _OPTIONS_SYNC_LAST_AT < _OPTIONS_SYNC_INTERVAL_SEC:
|
||||
return
|
||||
_OPTIONS_SYNC_LAST_AT = now
|
||||
from lib.exchange.okx_options_lib import fetch_option_position_history
|
||||
from lib.options.options_monitor_lib import reconcile_live_open_trades, sync_open_options_trades
|
||||
from lib.exchange.okx_options_lib import fetch_all_option_positions_history, fetch_option_position_history
|
||||
from lib.options.options_monitor_lib import (
|
||||
backfill_closed_options_realized_pnl_from_history,
|
||||
reconcile_live_open_trades,
|
||||
sync_open_options_trades,
|
||||
)
|
||||
|
||||
if raw_positions is None:
|
||||
raw = cfg["fetch_option_positions"](ex)
|
||||
@@ -281,6 +291,11 @@ def _sync_options_trades(
|
||||
init_options_tables(conn)
|
||||
reconcile_live_open_trades(conn, live_inst_ids=live_ids)
|
||||
sync_open_options_trades(conn, live_inst_ids=live_ids, fetch_history_fn=_hist)
|
||||
try:
|
||||
hist_all = fetch_all_option_positions_history(ex, limit=200)
|
||||
backfill_closed_options_realized_pnl_from_history(conn, hist_all)
|
||||
except Exception:
|
||||
pass
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
@@ -370,6 +385,9 @@ def register_options_routes(app: Flask, cfg: dict[str, Any]) -> None:
|
||||
return jsonify({"ok": False, "msg": f"加载期权链失败: {e}"})
|
||||
expiries = chain.get("expiries") or []
|
||||
chain_err = chain.get("chain_error")
|
||||
# 热更新:每次读 env,保存配置后刷新链即可生效
|
||||
ask_liq_filter = _env_bool("OKX_OPTIONS_CHAIN_ASK_LIQ_FILTER_ENABLED", True)
|
||||
budget_buffer = _env_float("OKX_OPTIONS_BUDGET_BUFFER", 0.95)
|
||||
if not expiries:
|
||||
return jsonify(
|
||||
{
|
||||
@@ -377,9 +395,21 @@ def register_options_routes(app: Flask, cfg: dict[str, Any]) -> None:
|
||||
"msg": chain_err or "暂无到期日,请稍后点「刷新链」",
|
||||
**chain,
|
||||
"chain_max_dte_days": cfg["chain_max_dte_days"],
|
||||
"ask_liq_filter_enabled": ask_liq_filter,
|
||||
"budget_buffer": budget_buffer,
|
||||
"trade_budget": cfg["trade_budget"],
|
||||
}
|
||||
)
|
||||
return jsonify({"ok": True, **chain, "chain_max_dte_days": cfg["chain_max_dte_days"]})
|
||||
return jsonify(
|
||||
{
|
||||
"ok": True,
|
||||
**chain,
|
||||
"chain_max_dte_days": cfg["chain_max_dte_days"],
|
||||
"ask_liq_filter_enabled": ask_liq_filter,
|
||||
"budget_buffer": budget_buffer,
|
||||
"trade_budget": cfg["trade_budget"],
|
||||
}
|
||||
)
|
||||
|
||||
@app.route("/api/options/quote")
|
||||
@lr
|
||||
@@ -509,6 +539,18 @@ def register_options_routes(app: Flask, cfg: dict[str, Any]) -> None:
|
||||
ex, err = _require_options_ex(cfg)
|
||||
if ex is None:
|
||||
return jsonify({"ok": False, "msg": err})
|
||||
try:
|
||||
from lib.hedge_plan.hedge_options_exclusive_lib import block_standalone_option_open_msg
|
||||
|
||||
conn_gate = cfg["get_db"]()
|
||||
try:
|
||||
block_msg = block_standalone_option_open_msg(conn_gate)
|
||||
finally:
|
||||
conn_gate.close()
|
||||
if block_msg:
|
||||
return jsonify({"ok": False, "msg": block_msg})
|
||||
except Exception:
|
||||
pass
|
||||
data = request.get_json(silent=True) or {}
|
||||
inst_id = (data.get("inst_id") or "").strip()
|
||||
mode = (data.get("mode") or "budget_full").strip()
|
||||
@@ -603,11 +645,15 @@ def register_options_routes(app: Flask, cfg: dict[str, Any]) -> None:
|
||||
conn = cfg["get_db"]()
|
||||
trade_id = None
|
||||
target_mon = None
|
||||
open_underlying = ""
|
||||
open_opt_type = None
|
||||
try:
|
||||
init_options_tables(conn)
|
||||
meta = q.get("meta") or {}
|
||||
u = str(meta.get("uly") or inst_id).split("-")[0]
|
||||
opt_type = meta.get("optType")
|
||||
open_underlying = u
|
||||
open_opt_type = opt_type
|
||||
cur = conn.execute(
|
||||
"""
|
||||
INSERT INTO options_trades
|
||||
@@ -646,9 +692,30 @@ def register_options_routes(app: Flask, cfg: dict[str, Any]) -> None:
|
||||
finally:
|
||||
conn.close()
|
||||
from lib.exchange.okx_options_lib import invalidate_option_positions_cache
|
||||
from lib.options.options_notify_lib import notify_options_open
|
||||
|
||||
invalidate_option_positions_cache()
|
||||
_sync_options_trades(cfg, force=True)
|
||||
try:
|
||||
conn_n = cfg["get_db"]()
|
||||
try:
|
||||
notify_options_open(
|
||||
cfg,
|
||||
conn_n,
|
||||
trade_id=trade_id,
|
||||
inst_id=inst_id,
|
||||
underlying=open_underlying,
|
||||
opt_type=open_opt_type,
|
||||
sheets=sheets,
|
||||
premium_paid=sizing.get("total_premium"),
|
||||
open_quote=float(ask) if ask is not None else None,
|
||||
target_index=target_index,
|
||||
signal_note=signal_note,
|
||||
)
|
||||
finally:
|
||||
conn_n.close()
|
||||
except Exception:
|
||||
pass
|
||||
return jsonify(
|
||||
{
|
||||
"ok": True,
|
||||
@@ -763,6 +830,17 @@ def register_options_routes(app: Flask, cfg: dict[str, Any]) -> None:
|
||||
hedge_target = hedge_target_map.get(inst)
|
||||
if hedge_target:
|
||||
row["hedge_plan_target"] = hedge_target
|
||||
try:
|
||||
from lib.instance.instance_dashboard_lib import _resolve_options_source
|
||||
|
||||
source_key, source_label, source_plan_id = _resolve_options_source(conn, inst)
|
||||
row["source"] = source_key
|
||||
row["source_label"] = source_label
|
||||
row["source_plan_id"] = source_plan_id
|
||||
except Exception:
|
||||
row.setdefault("source", "option")
|
||||
row.setdefault("source_label", "纯期权")
|
||||
row.setdefault("source_plan_id", None)
|
||||
rows.append(row)
|
||||
finally:
|
||||
conn.close()
|
||||
@@ -890,11 +968,21 @@ def register_options_routes(app: Flask, cfg: dict[str, Any]) -> None:
|
||||
if result.get("fully_closed"):
|
||||
try:
|
||||
from lib.options.options_target_lib import cancel_target_monitor
|
||||
from lib.options.options_notify_lib import notify_options_close
|
||||
|
||||
conn2 = cfg["get_db"]()
|
||||
try:
|
||||
cancel_target_monitor(conn2, inst_id=inst_id)
|
||||
conn2.commit()
|
||||
notify_options_close(
|
||||
cfg,
|
||||
conn2,
|
||||
inst_id=inst_id,
|
||||
reason="手动平仓",
|
||||
sheets=result.get("submitted_sheets"),
|
||||
premium_received=result.get("premium_received"),
|
||||
close_quote=result.get("locked_bid_px") or result.get("bid"),
|
||||
)
|
||||
finally:
|
||||
conn2.close()
|
||||
except Exception:
|
||||
@@ -1205,6 +1293,7 @@ def _start_monitor_thread(app: Flask, cfg: dict[str, Any]) -> None:
|
||||
conn,
|
||||
live_inst_ids=live_ids,
|
||||
fetch_history_fn=lambda inst_id: fetch_option_position_history(ex, inst_id),
|
||||
notify_cfg=cfg,
|
||||
)
|
||||
|
||||
def _target_close(inst_id: str) -> dict[str, Any]:
|
||||
|
||||
@@ -112,17 +112,23 @@ def images_json_dumps(items: Sequence[Mapping[str, str]]) -> Optional[str]:
|
||||
|
||||
|
||||
def options_review_image_paths(row: Any, upload_folder: str) -> List[str]:
|
||||
upload_folder = os.path.abspath(upload_folder or "")
|
||||
upload_root = os.path.abspath(upload_folder or "")
|
||||
options_dir = options_review_upload_dir(upload_root)
|
||||
paths: List[str] = []
|
||||
seen: set[str] = set()
|
||||
|
||||
def _add(name: Optional[str]) -> None:
|
||||
if not name:
|
||||
return
|
||||
p = os.path.abspath(os.path.join(upload_folder, str(name).strip()))
|
||||
if os.path.isfile(p) and p not in seen:
|
||||
seen.add(p)
|
||||
paths.append(p)
|
||||
base = os.path.basename(str(name).strip())
|
||||
if not base:
|
||||
return
|
||||
for folder in (options_dir, upload_root):
|
||||
p = os.path.abspath(os.path.join(folder, base))
|
||||
if os.path.isfile(p) and p not in seen:
|
||||
seen.add(p)
|
||||
paths.append(p)
|
||||
return
|
||||
|
||||
try:
|
||||
keys = row.keys() if hasattr(row, "keys") else ()
|
||||
|
||||
@@ -556,8 +556,28 @@ def sync_all_review_sources(
|
||||
return out
|
||||
|
||||
|
||||
def ensure_local_review_synced(conn: sqlite3.Connection) -> dict[str, Any]:
|
||||
"""列表/统计前轻量刷新本地源."""
|
||||
def ensure_local_review_synced(
|
||||
conn: sqlite3.Connection,
|
||||
*,
|
||||
ex: Any | None = None,
|
||||
backfill_exchange_pnl: bool = True,
|
||||
) -> dict[str, Any]:
|
||||
"""列表/统计前轻量刷新本地源;有交易所时先用历史仓位盈亏覆盖本地再导入复盘."""
|
||||
if backfill_exchange_pnl and ex is not None:
|
||||
try:
|
||||
from lib.exchange.okx_options_lib import fetch_all_option_positions_history
|
||||
from lib.hedge_plan.hedge_plan_settle_lib import (
|
||||
backfill_hedge_option_legs_realized_pnl,
|
||||
)
|
||||
from lib.options.options_monitor_lib import (
|
||||
backfill_closed_options_realized_pnl_from_history,
|
||||
)
|
||||
|
||||
hist = fetch_all_option_positions_history(ex, limit=200)
|
||||
backfill_closed_options_realized_pnl_from_history(conn, hist)
|
||||
backfill_hedge_option_legs_realized_pnl(conn, hist)
|
||||
except Exception:
|
||||
pass
|
||||
return sync_all_review_sources(conn, from_exchange=False)
|
||||
|
||||
|
||||
@@ -581,22 +601,43 @@ def enrich_trade_row(row: dict[str, Any], entry: dict[str, Any] | None = None) -
|
||||
out["entry"] = dict(entry)
|
||||
out["entry"]["images"] = parse_options_review_images_json(entry.get("images_json"))
|
||||
out["strategy_tag"] = entry.get("strategy_tag")
|
||||
out["direction_view"] = entry.get("direction_view")
|
||||
out["entry_logic"] = entry.get("entry_logic")
|
||||
out["result_tag"] = entry.get("result_tag")
|
||||
out["reviewed_at"] = entry.get("reviewed_at") or entry.get("updated_at")
|
||||
else:
|
||||
out["entry"] = None
|
||||
out["strategy_tag"] = None
|
||||
out["direction_view"] = None
|
||||
out["entry_logic"] = None
|
||||
out["result_tag"] = None
|
||||
out["reviewed_at"] = None
|
||||
return out
|
||||
|
||||
|
||||
def _review_search_tokens(q: str) -> list[str]:
|
||||
"""自由搜索词:BTCUSDT 同时匹配 BTC / BTCUSDT."""
|
||||
raw = str(q or "").strip()
|
||||
if not raw:
|
||||
return []
|
||||
tokens = [raw]
|
||||
u = raw.upper()
|
||||
for suf in ("-USDT", "-USD", "-USDC", "USDT", "USD", "USDC"):
|
||||
if u.endswith(suf) and len(u) > len(suf):
|
||||
base = u[: -len(suf)].rstrip("-_")
|
||||
if base and base not in {t.upper() for t in tokens}:
|
||||
tokens.append(base)
|
||||
break
|
||||
return tokens
|
||||
|
||||
|
||||
def _review_trades_filters(
|
||||
*,
|
||||
source_type: str | None = None,
|
||||
underlying: str | None = None,
|
||||
opt_type: str | None = None,
|
||||
strategy_tag: str | None = None,
|
||||
q: str | None = None,
|
||||
reviewed: str | None = None,
|
||||
include_hedge_legs: bool = False,
|
||||
closed_from: str | None = None,
|
||||
@@ -635,9 +676,26 @@ def _review_trades_filters(
|
||||
if closed_to:
|
||||
wheres.append("COALESCE(t.closed_at,'')<=?")
|
||||
args.append(closed_to)
|
||||
if strategy_tag:
|
||||
wheres.append("e.strategy_tag=?")
|
||||
# 兼容旧参数:精确策略标签;前端已改用 q 模糊搜索
|
||||
if strategy_tag and not q:
|
||||
wheres.append("UPPER(COALESCE(e.strategy_tag,''))=UPPER(?)")
|
||||
args.append(strategy_tag)
|
||||
search_tokens = _review_search_tokens(q or "")
|
||||
if search_tokens:
|
||||
token_ors: list[str] = []
|
||||
for tok in search_tokens:
|
||||
like = f"%{tok}%"
|
||||
token_ors.append(
|
||||
"""(
|
||||
UPPER(COALESCE(t.underlying,'')) LIKE UPPER(?)
|
||||
OR UPPER(COALESCE(t.inst_id,'')) LIKE UPPER(?)
|
||||
OR UPPER(COALESCE(t.legs_json,'')) LIKE UPPER(?)
|
||||
OR UPPER(COALESCE(e.strategy_tag,'')) LIKE UPPER(?)
|
||||
OR UPPER(COALESCE(e.result_tag,'')) LIKE UPPER(?)
|
||||
)"""
|
||||
)
|
||||
args.extend([like, like, like, like, like])
|
||||
wheres.append("(" + " OR ".join(token_ors) + ")")
|
||||
if reviewed == "1" or reviewed == "yes":
|
||||
wheres.append("e.id IS NOT NULL")
|
||||
elif reviewed == "0" or reviewed == "no":
|
||||
@@ -653,6 +711,7 @@ def count_review_trades(
|
||||
underlying: str | None = None,
|
||||
opt_type: str | None = None,
|
||||
strategy_tag: str | None = None,
|
||||
q: str | None = None,
|
||||
reviewed: str | None = None,
|
||||
include_hedge_legs: bool = False,
|
||||
closed_from: str | None = None,
|
||||
@@ -664,6 +723,7 @@ def count_review_trades(
|
||||
underlying=underlying,
|
||||
opt_type=opt_type,
|
||||
strategy_tag=strategy_tag,
|
||||
q=q,
|
||||
reviewed=reviewed,
|
||||
include_hedge_legs=include_hedge_legs,
|
||||
closed_from=closed_from,
|
||||
@@ -688,6 +748,7 @@ def list_review_trades(
|
||||
underlying: str | None = None,
|
||||
opt_type: str | None = None,
|
||||
strategy_tag: str | None = None,
|
||||
q: str | None = None,
|
||||
reviewed: str | None = None,
|
||||
include_hedge_legs: bool = False,
|
||||
closed_from: str | None = None,
|
||||
@@ -701,6 +762,7 @@ def list_review_trades(
|
||||
underlying=underlying,
|
||||
opt_type=opt_type,
|
||||
strategy_tag=strategy_tag,
|
||||
q=q,
|
||||
reviewed=reviewed,
|
||||
include_hedge_legs=include_hedge_legs,
|
||||
closed_from=closed_from,
|
||||
|
||||
@@ -26,7 +26,6 @@ from lib.options.options_review_lib import (
|
||||
hide_review_trade,
|
||||
list_review_trades,
|
||||
save_review_entry,
|
||||
sync_all_review_sources,
|
||||
)
|
||||
|
||||
|
||||
@@ -94,23 +93,30 @@ def register_options_review_routes(app: Flask, cfg: dict[str, Any], repo_root: s
|
||||
return send_file(path, mimetype="application/javascript; charset=utf-8")
|
||||
|
||||
@app.route("/static/images/options_journal/<path:filename>")
|
||||
@lr
|
||||
def static_options_review_image(filename: str):
|
||||
"""截图文件名含 32 位 draft id,按静态资源提供(不强制登录,避免 iframe img 偶发 401)."""
|
||||
folder = options_review_upload_dir(cfg["upload_folder"])
|
||||
safe = os.path.basename(filename or "")
|
||||
path = os.path.join(folder, safe)
|
||||
if not os.path.isfile(path):
|
||||
return ("not found", 404)
|
||||
# 兼容误走合约 journal 上传、落在 UPLOAD_FOLDER 根目录的文件
|
||||
root = os.path.abspath(cfg["upload_folder"] or "")
|
||||
alt = os.path.join(root, safe)
|
||||
if os.path.isfile(alt):
|
||||
path = alt
|
||||
else:
|
||||
return ("not found", 404)
|
||||
return send_file(path)
|
||||
|
||||
@app.route("/api/options/review/sync", methods=["POST"])
|
||||
@lr
|
||||
def api_options_review_sync():
|
||||
"""刷新本地 options_trades + 已结束对冲计划(不访问交易所)."""
|
||||
"""刷新本地 options_trades + 已结束对冲计划;尽量用交易所历史盈亏覆盖本地估算."""
|
||||
conn = cfg["get_db"]()
|
||||
try:
|
||||
init_options_review_tables(conn)
|
||||
result = sync_all_review_sources(conn, from_exchange=False)
|
||||
ex, _err = _require_ex(cfg)
|
||||
result = ensure_local_review_synced(conn, ex=ex if ex is not None else None)
|
||||
conn.commit()
|
||||
return jsonify(result)
|
||||
finally:
|
||||
@@ -128,13 +134,15 @@ def register_options_review_routes(app: Flask, cfg: dict[str, Any], repo_root: s
|
||||
"no",
|
||||
)
|
||||
if do_sync:
|
||||
ensure_local_review_synced(conn)
|
||||
ex, _err = _require_ex(cfg)
|
||||
ensure_local_review_synced(conn, ex=ex if ex is not None else None)
|
||||
conn.commit()
|
||||
filt = dict(
|
||||
source_type=(request.args.get("source_type") or "").strip() or None,
|
||||
underlying=(request.args.get("underlying") or "").strip() or None,
|
||||
opt_type=(request.args.get("opt_type") or "").strip() or None,
|
||||
strategy_tag=(request.args.get("strategy_tag") or "").strip() or None,
|
||||
q=(request.args.get("q") or "").strip() or None,
|
||||
reviewed=(request.args.get("reviewed") or "").strip() or None,
|
||||
include_hedge_legs=(request.args.get("include_hedge_legs") or "")
|
||||
.strip()
|
||||
@@ -259,7 +267,8 @@ def register_options_review_routes(app: Flask, cfg: dict[str, Any], repo_root: s
|
||||
def api_options_review_stats():
|
||||
conn = cfg["get_db"]()
|
||||
try:
|
||||
ensure_local_review_synced(conn)
|
||||
ex, _err = _require_ex(cfg)
|
||||
ensure_local_review_synced(conn, ex=ex if ex is not None else None)
|
||||
conn.commit()
|
||||
stats = compute_review_stats(
|
||||
conn,
|
||||
|
||||
@@ -292,6 +292,7 @@ def close_option_by_bid_depth(
|
||||
|
||||
|
||||
def _notify_target_close(
|
||||
cfg: dict[str, Any] | None,
|
||||
send_wechat: Callable[[str], None] | None,
|
||||
*,
|
||||
account_label: str,
|
||||
@@ -299,7 +300,28 @@ def _notify_target_close(
|
||||
target: float,
|
||||
idx: float,
|
||||
result: dict[str, Any],
|
||||
conn: Any = None,
|
||||
) -> None:
|
||||
"""目标位平仓推送:优先走统一平仓必发(幂等);无 cfg 时回退旧文案."""
|
||||
if result.get("fully_closed") or result.get("already_flat"):
|
||||
if cfg is not None:
|
||||
try:
|
||||
from lib.options.options_notify_lib import notify_options_close
|
||||
|
||||
notify_options_close(
|
||||
cfg,
|
||||
conn,
|
||||
inst_id=inst_id,
|
||||
reason="目标位平仓",
|
||||
sheets=result.get("submitted_sheets"),
|
||||
premium_received=result.get("premium_received"),
|
||||
close_quote=result.get("locked_bid_px") or result.get("bid"),
|
||||
target_index=target,
|
||||
trigger_idx=idx,
|
||||
)
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
if not send_wechat:
|
||||
return
|
||||
try:
|
||||
@@ -313,6 +335,7 @@ def _notify_target_close(
|
||||
f"触发指数:{idx:g}",
|
||||
f"提交张数:{result.get('submitted_sheets') or '—'}",
|
||||
f"预估收回:{result.get('premium_received') if result.get('premium_received') is not None else '—'} USDC",
|
||||
f"状态:{'已全平' if (result.get('fully_closed') or result.get('already_flat')) else '挂单中/部分'}",
|
||||
]
|
||||
)
|
||||
)
|
||||
@@ -339,6 +362,7 @@ def run_options_target_closes(
|
||||
index_fn: Callable[[dict[str, Any]], float | None] | None = None,
|
||||
send_wechat: Callable[[str], None] | None = None,
|
||||
account_label: str = "OKX期权",
|
||||
cfg: dict[str, Any] | None = None,
|
||||
) -> int:
|
||||
"""
|
||||
扫描 active 目标委托;指数到位后限价平仓.
|
||||
@@ -433,11 +457,13 @@ def run_options_target_closes(
|
||||
_commit_monitor(conn)
|
||||
triggered += 1
|
||||
_notify_target_close(
|
||||
cfg,
|
||||
send_wechat,
|
||||
account_label=account_label,
|
||||
inst_id=inst_id,
|
||||
target=target,
|
||||
idx=idx,
|
||||
result=result,
|
||||
conn=conn,
|
||||
)
|
||||
return triggered
|
||||
|
||||
@@ -1,13 +1,30 @@
|
||||
<div class="options-page-wrap" style="grid-column:1/-1" id="options-root"
|
||||
data-default-underly="{{ options_default_underly | default('ETH') }}">
|
||||
data-default-underly="{{ options_default_underly | default('ETH') }}"
|
||||
data-budget-buffer="{{ options_budget_buffer | default(0.95) }}"
|
||||
data-trade-budget="{{ options_trade_budget | default(10) }}"
|
||||
data-ask-liq-filter="{% if options_chain_ask_liq_filter is defined %}{{ '1' if options_chain_ask_liq_filter else '0' }}{% else %}1{% endif %}">
|
||||
{% if not options_enabled %}
|
||||
<div class="flash" style="margin-bottom:12px">期权 API 未启用:请在 <code>crypto_monitor_okx/.env</code> 设置 <code>OKX_OPTIONS_ENABLED=true</code> 及主账户 <code>OKX_OPTIONS_API_*</code>,然后 <code>pm2 restart crypto_okx --update-env</code>.</div>
|
||||
{% endif %}
|
||||
|
||||
<div class="options-dual-grid">
|
||||
<div class="card options-order-card">
|
||||
<h2>期权下单 <a class="muted" href="/options/guide" target="_blank" rel="noopener" style="font-size:13px;font-weight:500;margin-left:8px">开平仓与监控说明</a></h2>
|
||||
<p class="muted options-hint">报价单位为每 1 ETH/BTC;1 张 = 0.01.<strong>列表</strong>含卖一/买一;<strong>T 型</strong>仅卖一(买方开仓),中间为跨式双买测算.链上无卖一挂单时以标记价/内在价值估算并标 <strong>~</strong>(仅参考).<strong>开仓只认真实卖一价且卖一深度>0</strong>;无深度时面板显示参考标记价并禁用买入.链展示近 <span id="opt-chain-dte">14</span> 日到期.<strong>T 型</strong>默认 ATM ±5 档,可展开全部.平仓仅买一限价,见说明.</p>
|
||||
<h2>期权下单</h2>
|
||||
<details class="opt-close-rule opt-open-rule">
|
||||
<summary>开仓规则说明</summary>
|
||||
<div class="opt-close-rule-body">
|
||||
<p>报价单位为每 1 ETH/BTC;1 张 = 0.01。默认选中<strong>最近一期</strong>到期,可手动改。</p>
|
||||
<ul>
|
||||
<li><strong>列表</strong>含卖一/买一;<strong>T 型</strong>仅卖一(买方开仓),中间为跨式双买测算。</li>
|
||||
<li>环境配置「链上仅显示有卖一」开启时,隐藏无真实卖一或深度不足 1 张的合约(估算价 <strong>~</strong> 亦不显示)。</li>
|
||||
<li><strong>开仓只认真实卖一价且卖一深度≥1</strong>;无深度时面板显示参考标记价并禁用买入。</li>
|
||||
<li>链展示近 <span id="opt-chain-dte">14</span> 日到期;<strong>T 型</strong>默认 ATM ±5 档,可展开全部。</li>
|
||||
<li>「按可用余额打满」可用额度 = min(交易户可用 USDC, 单笔预算 <strong id="opt-trade-budget">{{ '%.2f'|format(options_trade_budget|default(10)|float) }}</strong>),再 × 预算缓冲 <strong id="opt-budget-buf">{{ '%.2f'|format(options_budget_buffer|default(0.95)|float) }}</strong> 算张数(env 可改)。</li>
|
||||
<li>平仓仅买一限价,详见说明文档。</li>
|
||||
</ul>
|
||||
<p><a href="/options/guide" target="_blank" rel="noopener">打开《期权开平仓与监控说明》</a></p>
|
||||
</div>
|
||||
</details>
|
||||
<div class="form-row options-chain-toolbar">
|
||||
<button type="button" class="btn-secondary opt-uly-btn active" data-uly="ETH">ETH</button>
|
||||
<button type="button" class="btn-secondary opt-uly-btn" data-uly="BTC">BTC</button>
|
||||
@@ -64,11 +81,14 @@
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div id="opt-order-panel-host" class="opt-order-panel-host" hidden aria-hidden="true">
|
||||
<div id="opt-order-panel" class="opt-order-panel-inner" style="display:none">
|
||||
<div id="opt-order-panel-host" class="opt-order-backdrop" hidden aria-hidden="true">
|
||||
<div id="opt-order-panel" class="opt-order-dialog" role="dialog" aria-modal="true" aria-labelledby="opt-order-dialog-title" style="display:none">
|
||||
<div class="opt-order-dialog-head">
|
||||
<h3 class="opt-order-title" id="opt-order-dialog-title">下单</h3>
|
||||
<button type="button" class="btn-secondary" id="opt-order-close-btn" style="font-size:.72rem;padding:2px 10px">取消</button>
|
||||
</div>
|
||||
<div class="opt-order-layout">
|
||||
<div class="opt-order-main">
|
||||
<h3 class="opt-order-title">下单</h3>
|
||||
<div id="opt-order-inst" class="options-order-inst"></div>
|
||||
<div class="options-order-grid">
|
||||
<div><span class="k">卖一/张</span><span id="opt-order-ask" class="v">—</span></div>
|
||||
@@ -82,37 +102,51 @@
|
||||
<div><span class="k">距平衡</span><span id="opt-order-dist-be" class="v">—</span></div>
|
||||
</div>
|
||||
<div class="options-estimate-row">
|
||||
<label class="opt-est-label" for="opt-target-idx">目标位(指数)</label>
|
||||
<input type="number" id="opt-target-idx" class="opt-target-idx" step="0.1" min="0" placeholder="达价限价平仓">
|
||||
<span class="k">预计价值</span>
|
||||
<span id="opt-est-value" class="v">—</span>
|
||||
<span class="k">盈利</span>
|
||||
<span id="opt-est-profit" class="v">—</span>
|
||||
<span class="k">目标杠杆</span>
|
||||
<span id="opt-est-leverage" class="v" title="目标位名义价值÷权利金">—</span>
|
||||
<div class="opt-est-main">
|
||||
<label class="btn-secondary opt-order-chip" for="opt-target-idx">目标位(指数)</label>
|
||||
<input type="number" id="opt-target-idx" class="opt-target-idx" step="0.1" min="0" placeholder="达价限价平仓"
|
||||
autocomplete="off" inputmode="decimal" data-lpignore="true" data-1p-ignore="true" data-form-type="other">
|
||||
<span class="k">预计价值</span>
|
||||
<span id="opt-est-value" class="v">—</span>
|
||||
<span class="k">盈利</span>
|
||||
<span id="opt-est-profit" class="v">—</span>
|
||||
<span class="k">目标杠杆</span>
|
||||
<span id="opt-est-leverage" class="v" title="目标位名义价值÷权利金">—</span>
|
||||
</div>
|
||||
<span class="muted opt-est-note">目标价=监控指数;到位后按买一限价平仓;无止损,到期即止损</span>
|
||||
</div>
|
||||
<div class="form-row options-order-mode-row">
|
||||
<label><input type="radio" name="opt-size-mode" value="sheets" checked> 指定张数</label>
|
||||
<input type="number" id="opt-sheets-amount" min="1" step="1" value="1" placeholder="张数">
|
||||
<label><input type="radio" name="opt-size-mode" value="budget_full"> 按可用余额打满</label>
|
||||
<label><input type="radio" name="opt-size-mode" value="eth_amount"> 指定币数量</label>
|
||||
<input type="number" id="opt-eth-amount" min="0.01" step="0.01" placeholder="如 0.5" style="display:none">
|
||||
<input type="text" id="opt-signal-note" placeholder="备注(关键位说明)">
|
||||
<div class="opt-size-mode-bar">
|
||||
<label class="btn-secondary opt-order-chip opt-size-mode-chip">
|
||||
<input type="radio" name="opt-size-mode" value="sheets" checked>
|
||||
<span>指定张数</span>
|
||||
</label>
|
||||
<input type="number" id="opt-sheets-amount" min="1" step="1" value="1" placeholder="张数"
|
||||
autocomplete="off" inputmode="numeric" data-lpignore="true" data-1p-ignore="true" data-form-type="other">
|
||||
<label class="btn-secondary opt-order-chip opt-size-mode-chip">
|
||||
<input type="radio" name="opt-size-mode" value="budget_full">
|
||||
<span>按可用余额打满</span>
|
||||
</label>
|
||||
<label class="btn-secondary opt-order-chip opt-size-mode-chip">
|
||||
<input type="radio" name="opt-size-mode" value="eth_amount" id="opt-size-mode-eth">
|
||||
<span>指定币数量</span>
|
||||
</label>
|
||||
<input type="number" id="opt-eth-amount" min="0.01" step="0.01" placeholder="如 0.5" style="display:none"
|
||||
autocomplete="off" inputmode="decimal" data-lpignore="true" data-1p-ignore="true" data-form-type="other">
|
||||
</div>
|
||||
<p class="muted opt-budget-full-hint" id="opt-budget-full-hint" style="display:none;margin:6px 0 0;font-size:.82rem;line-height:1.4">
|
||||
余额 > 单笔预算(<span id="opt-budget-full-cap">{{ '%.2f'|format(options_trade_budget|default(10)|float) }}</span>U)时按预算;余额不足时按余额;再乘预算缓冲算张数。
|
||||
</p>
|
||||
<input type="text" id="opt-signal-note" name="opt_signal_note" class="opt-signal-note" placeholder="备注(关键位说明)"
|
||||
autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false"
|
||||
data-lpignore="true" data-1p-ignore="true" data-form-type="other" readonly>
|
||||
</div>
|
||||
<div class="opt-order-dialog-actions">
|
||||
<button type="button" class="btn-primary" id="opt-open-btn">限价买入 @ 卖一</button>
|
||||
<button type="button" class="btn-secondary" id="opt-order-cancel-btn">取消</button>
|
||||
</div>
|
||||
<div id="opt-order-msg" class="muted"></div>
|
||||
</div>
|
||||
<aside class="opt-order-pending" aria-label="未成交委托">
|
||||
<div class="opt-order-pending-head">
|
||||
<h4 class="opt-order-pending-title">委托</h4>
|
||||
<button type="button" class="btn-secondary" id="opt-pending-refresh">刷新</button>
|
||||
</div>
|
||||
<p class="muted opt-pending-ttl-hint" id="opt-pending-ttl-hint">平仓限价超 10 分未成交将自动撤销</p>
|
||||
<div id="opt-pending-list" class="opt-pending-list">
|
||||
<div class="muted opt-pending-empty">暂无未成交委托</div>
|
||||
</div>
|
||||
</aside>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -125,6 +159,7 @@
|
||||
</div>
|
||||
<div class="options-pos-tabs" role="tablist" aria-label="持仓面板">
|
||||
<button type="button" class="btn-secondary opt-pos-tab active" data-opt-pos-tab="live" role="tab" aria-selected="true" id="opt-pos-tab-live">当前持仓</button>
|
||||
<button type="button" class="btn-secondary opt-pos-tab" data-opt-pos-tab="pending" role="tab" aria-selected="false" id="opt-pos-tab-pending">当前委托</button>
|
||||
<button type="button" class="btn-secondary opt-pos-tab" data-opt-pos-tab="stats" role="tab" aria-selected="false" id="opt-pos-tab-stats">数据统计</button>
|
||||
<button type="button" class="btn-secondary opt-pos-tab" data-opt-pos-tab="history" role="tab" aria-selected="false" id="opt-pos-tab-history">期权历史</button>
|
||||
</div>
|
||||
@@ -152,6 +187,17 @@
|
||||
</div>
|
||||
</details>
|
||||
</div>
|
||||
<div class="options-pos-pane" data-opt-pos-pane="pending" role="tabpanel" aria-labelledby="opt-pos-tab-pending" hidden>
|
||||
<div class="opt-pos-pending-pane">
|
||||
<div class="opt-order-pending-head">
|
||||
<p class="muted opt-pending-ttl-hint" id="opt-pending-ttl-hint" style="margin:0;flex:1">平仓限价超 10 分未成交将自动撤销</p>
|
||||
<button type="button" class="btn-secondary" id="opt-pending-refresh">刷新</button>
|
||||
</div>
|
||||
<div id="opt-pending-list" class="opt-pending-list opt-pending-list--tab">
|
||||
<div class="muted opt-pending-empty">暂无未成交委托</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="options-pos-pane" data-opt-pos-pane="stats" role="tabpanel" aria-labelledby="opt-pos-tab-stats" hidden>
|
||||
<div class="options-stats-panel">
|
||||
<div class="options-stats-pnl-summary" id="opt-stats-pnl-summary">
|
||||
@@ -274,4 +320,4 @@
|
||||
</div>
|
||||
</div>
|
||||
<script src="/static/options_expiry_countdown.js?v=1"></script>
|
||||
<script src="/static/options_panel.js?v=39"></script>
|
||||
<script src="/static/options_panel.js?v=50"></script>
|
||||
|
||||
@@ -1,20 +1,110 @@
|
||||
{# OKX 期权复盘:交易记录(5行) → 点复盘出表单 → 复盘记录 → 统计 #}
|
||||
{# OKX 期权复盘:交易记录 → 复盘表单 → 复盘记录 → 统计 #}
|
||||
<div class="options-review-wrap" id="options-review-root" style="grid-column:1/-1">
|
||||
{% if not options_enabled %}
|
||||
<div class="flash" style="margin-bottom:12px;font-size:.82rem">期权未启用:请设置 <code>OKX_OPTIONS_ENABLED=true</code> 后重启.</div>
|
||||
{% endif %}
|
||||
|
||||
<style>
|
||||
.options-review-wrap{font-size:.82rem}
|
||||
.options-review-wrap h2{font-size:1rem;margin:0 0 8px}
|
||||
.options-review-wrap h3{font-size:.9rem;margin:0 0 8px}
|
||||
.options-review-wrap{font-size:.82rem;display:flex;flex-direction:column;gap:14px}
|
||||
.options-review-wrap h2,.options-review-wrap h3{margin:0}
|
||||
.or-page-head{
|
||||
display:flex;align-items:center;gap:10px;flex-wrap:wrap;
|
||||
padding:2px 2px 0;
|
||||
}
|
||||
.or-page-head h2{font-size:1.05rem;font-weight:650;margin-right:auto;letter-spacing:.02em}
|
||||
.or-section{
|
||||
margin:0;padding:14px 16px 16px;
|
||||
border:1px solid var(--or-border, rgba(127,127,127,.28));
|
||||
border-radius:12px;
|
||||
background:var(--or-section-bg, rgba(18,23,38,.55));
|
||||
box-shadow:var(--or-section-shadow, 0 1px 0 rgba(255,255,255,.03) inset);
|
||||
color:var(--or-text, inherit);
|
||||
}
|
||||
.or-section-head{
|
||||
display:flex;align-items:flex-start;gap:10px;flex-wrap:wrap;
|
||||
margin-bottom:12px;padding-bottom:10px;
|
||||
border-bottom:1px solid var(--or-border-soft, rgba(127,127,127,.22));
|
||||
}
|
||||
.or-section-head > div{min-width:0;flex:1}
|
||||
.or-step{
|
||||
flex-shrink:0;width:1.55rem;height:1.55rem;border-radius:999px;
|
||||
display:inline-flex;align-items:center;justify-content:center;
|
||||
font-size:.72rem;font-weight:700;
|
||||
background:var(--or-accent-bg, rgba(99,102,241,.28));
|
||||
color:var(--or-accent-fg, #c7c9ff);
|
||||
border:1px solid var(--or-accent-border, rgba(129,140,248,.45));
|
||||
}
|
||||
.or-section-title{font-size:.95rem;font-weight:650;line-height:1.3;color:var(--or-title, inherit)}
|
||||
.or-section-desc{margin:4px 0 0;font-size:.72rem;opacity:.72;line-height:1.45;color:var(--or-muted, inherit)}
|
||||
.or-tabs{display:flex;gap:6px;flex-wrap:wrap;margin-bottom:8px}
|
||||
.or-tab{border:1px solid rgba(127,127,127,.35);background:transparent;color:inherit;padding:5px 10px;border-radius:6px;cursor:pointer;font-size:.78rem}
|
||||
.or-tab.active{background:rgba(59,130,246,.25);border-color:rgba(59,130,246,.55)}
|
||||
.or-badge{display:inline-block;padding:1px 6px;border-radius:999px;background:rgba(127,127,127,.2);font-size:.7rem}
|
||||
.or-stat-card{border:1px solid rgba(127,127,127,.25);border-radius:8px;padding:8px;font-size:.78rem}
|
||||
.or-trades-table{font-size:.78rem}
|
||||
.or-trades-table tr.or-row-active{outline:1px solid rgba(59,130,246,.55);background:rgba(59,130,246,.08)}
|
||||
.or-toolbar{display:flex;flex-direction:column;gap:0;margin:0}
|
||||
.or-tab{
|
||||
border:1px solid var(--or-border, rgba(127,127,127,.35));background:transparent;color:inherit;
|
||||
padding:6px 12px;border-radius:8px;cursor:pointer;font-size:.78rem;
|
||||
}
|
||||
.or-tab.active{
|
||||
background:var(--or-accent-bg, rgba(99,102,241,.28));
|
||||
border-color:var(--or-accent-border, rgba(129,140,248,.55));
|
||||
color:var(--or-accent-fg, #e8e9ff);font-weight:600;
|
||||
}
|
||||
.or-filters{
|
||||
display:flex;flex-wrap:wrap;gap:8px;align-items:center;
|
||||
margin:0;padding:10px 12px;border-radius:10px;
|
||||
background:var(--or-filters-bg, rgba(0,0,0,.22));
|
||||
border:1px solid var(--or-border-soft, rgba(127,127,127,.18));
|
||||
}
|
||||
.or-filters select,.or-filters input[type="search"],.or-filters input[type="datetime-local"]{
|
||||
font-size:.76rem;min-height:2rem;
|
||||
}
|
||||
.or-filters #or-filter-q{max-width:168px}
|
||||
.or-filters label{display:flex;align-items:center;gap:5px;font-size:.72rem;opacity:.85}
|
||||
.or-badge{
|
||||
display:inline-block;padding:1px 7px;border-radius:999px;
|
||||
background:var(--or-badge-bg, rgba(127,127,127,.22));font-size:.7rem;vertical-align:middle;
|
||||
}
|
||||
.or-list-title{display:none}
|
||||
.or-trades-table,.or-reviewed-table{font-size:.78rem}
|
||||
.or-trades-table tr.or-row-active{
|
||||
outline:1px solid var(--or-accent-border, rgba(129,140,248,.55));
|
||||
background:var(--or-row-active-bg, rgba(99,102,241,.1));
|
||||
}
|
||||
.or-reviewed-table tbody tr{cursor:pointer}
|
||||
.or-reviewed-table tbody tr:hover{background:var(--or-row-hover-bg, rgba(99,102,241,.08))}
|
||||
.or-pager{
|
||||
display:flex;align-items:center;gap:8px;margin-top:10px;
|
||||
padding-top:8px;border-top:1px dashed var(--or-border-soft, rgba(127,127,127,.2));font-size:.74rem;
|
||||
}
|
||||
.or-list-loading{opacity:.55;pointer-events:none;transition:opacity .12s ease}
|
||||
.or-trades-table-wrap,.or-reviewed-table-wrap{min-height:9.5rem;overflow-x:auto}
|
||||
.or-reviewed-table{min-width:980px}
|
||||
.or-kpi-row{
|
||||
display:grid;grid-template-columns:repeat(6,minmax(0,1fr));
|
||||
gap:8px;margin-bottom:12px;
|
||||
}
|
||||
.or-kpi-tile{
|
||||
border:1px solid var(--or-border-soft, rgba(127,127,127,.22));border-radius:10px;
|
||||
padding:10px 12px;background:var(--or-tile-bg, rgba(0,0,0,.2));min-width:0;
|
||||
}
|
||||
.or-kpi-label{font-size:.7rem;opacity:.7;margin-bottom:4px}
|
||||
.or-kpi-value{font-size:.95rem;font-weight:650;letter-spacing:.01em;word-break:break-all}
|
||||
.or-stats-grid{
|
||||
display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:10px;
|
||||
}
|
||||
.or-stat-card{
|
||||
border:1px solid var(--or-border-soft, rgba(127,127,127,.22));border-radius:10px;
|
||||
padding:10px 12px;background:var(--or-tile-bg, rgba(0,0,0,.16));font-size:.76rem;
|
||||
}
|
||||
.or-stat-card-title{
|
||||
font-weight:650;margin-bottom:8px;font-size:.78rem;
|
||||
padding-bottom:6px;border-bottom:1px solid var(--or-border-soft, rgba(127,127,127,.18));
|
||||
}
|
||||
.or-stat-row{
|
||||
display:flex;justify-content:space-between;align-items:baseline;gap:10px;
|
||||
padding:5px 0;border-bottom:1px solid var(--or-border-faint, rgba(127,127,127,.1));
|
||||
}
|
||||
.or-stat-row:last-child{border-bottom:none;padding-bottom:0}
|
||||
.or-stat-key{opacity:.9;min-width:0;overflow:hidden;text-overflow:ellipsis}
|
||||
.or-stat-val{flex-shrink:0;font-variant-numeric:tabular-nums;opacity:.85}
|
||||
.or-journal-card{font-size:.78rem}
|
||||
.or-journal-card h2{font-size:.92rem}
|
||||
.or-journal-card input,
|
||||
@@ -22,56 +112,117 @@
|
||||
.or-journal-card textarea,
|
||||
.or-journal-card button{font-size:.76rem}
|
||||
.or-journal-card .or-form-grid,
|
||||
.or-journal-card .or-form-grid2{display:grid;grid-template-columns:repeat(auto-fit,minmax(120px,1fr));gap:6px;margin-bottom:6px}
|
||||
.or-journal-card .or-form-grid2{
|
||||
display:grid;grid-template-columns:repeat(auto-fit,minmax(120px,1fr));gap:6px;margin-bottom:6px;
|
||||
}
|
||||
.or-journal-card .or-mood-grid{display:flex;flex-wrap:wrap;gap:6px 12px;margin:8px 0;font-size:.74rem}
|
||||
.or-journal-card .muted,
|
||||
.or-journal-card .sub{font-size:.7rem}
|
||||
.or-journal-card .muted,.or-journal-card .sub{font-size:.7rem}
|
||||
.or-journal-card.hidden{display:none!important}
|
||||
.or-reviewed-table tbody tr{cursor:pointer}
|
||||
.or-detail-panel{margin-top:10px;padding-top:10px;border-top:1px solid rgba(127,127,127,.25)}
|
||||
.or-detail-panel.hidden{display:none!important}
|
||||
.or-detail-backdrop{
|
||||
position:fixed;inset:0;z-index:1300;
|
||||
display:flex;align-items:center;justify-content:center;
|
||||
padding:16px;background:var(--or-backdrop, rgba(0,0,0,.72));
|
||||
}
|
||||
.or-detail-backdrop[hidden]{display:none!important}
|
||||
.or-img-lightbox{
|
||||
position:fixed;inset:0;z-index:2200;
|
||||
display:flex;align-items:center;justify-content:center;
|
||||
padding:16px;background:rgba(0,0,0,.86);cursor:zoom-out;
|
||||
}
|
||||
.or-img-lightbox[hidden]{display:none!important}
|
||||
.or-img-lightbox img{
|
||||
max-width:min(96vw,1200px);max-height:92vh;
|
||||
object-fit:contain;border-radius:8px;
|
||||
box-shadow:0 12px 40px rgba(0,0,0,.55);
|
||||
}
|
||||
.or-detail-modal{
|
||||
width:min(96vw,920px);max-height:90vh;overflow:auto;
|
||||
background:var(--or-modal-bg, var(--card-bg, #121726));color:var(--or-text, inherit);
|
||||
border:1px solid var(--or-border, rgba(127,127,127,.35));border-radius:10px;
|
||||
padding:14px 16px 18px;box-shadow:var(--or-modal-shadow, 0 12px 40px rgba(0,0,0,.45));
|
||||
}
|
||||
.or-detail-modal-head{display:flex;align-items:center;gap:8px;margin-bottom:10px}
|
||||
.or-detail-modal-head h3{margin:0;margin-right:auto;font-size:.95rem;color:var(--or-title, inherit)}
|
||||
.or-detail-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(140px,1fr));gap:6px 12px;font-size:.76rem;margin-bottom:8px}
|
||||
.or-detail-images{display:grid;grid-template-columns:repeat(auto-fit,minmax(140px,1fr));gap:8px;margin:8px 0}
|
||||
.or-detail-img-cell{border:1px solid rgba(127,127,127,.25);border-radius:6px;padding:6px;text-align:center}
|
||||
.or-detail-img-label{display:block;font-size:.7rem;margin-bottom:4px;opacity:.8}
|
||||
.or-detail-img-thumb{max-width:100%;max-height:160px;border-radius:4px;cursor:pointer}
|
||||
.or-pager{display:flex;align-items:center;gap:8px;margin-top:8px;font-size:.74rem}
|
||||
.or-list-loading{opacity:.55;pointer-events:none;transition:opacity .12s ease}
|
||||
.or-trades-table-wrap,.or-reviewed-table-wrap{min-height:9.5rem}
|
||||
.or-detail-images{
|
||||
display:grid;grid-template-columns:repeat(2,minmax(0,1fr));
|
||||
gap:10px;margin:10px 0 4px;
|
||||
}
|
||||
.or-detail-img-cell{
|
||||
min-width:0;border:1px solid var(--or-border-soft, rgba(127,127,127,.25));border-radius:8px;
|
||||
padding:8px;display:flex;flex-direction:column;gap:6px;
|
||||
background:var(--or-tile-bg, rgba(0,0,0,.18));
|
||||
}
|
||||
.or-detail-img-label{font-size:.72rem;opacity:.85;font-weight:600}
|
||||
.or-detail-img-thumb{
|
||||
width:100%;max-height:280px;object-fit:contain;
|
||||
border-radius:6px;cursor:zoom-in;background:var(--or-img-bg, rgba(0,0,0,.25));
|
||||
}
|
||||
.or-detail-img-miss{
|
||||
min-height:120px;display:flex;align-items:center;justify-content:center;
|
||||
font-size:.72rem;opacity:.65;border-radius:6px;background:rgba(127,127,127,.12);
|
||||
}
|
||||
.or-slot-thumb{
|
||||
display:block;margin-top:6px;max-width:160px;max-height:90px;
|
||||
object-fit:contain;border-radius:4px;border:1px solid var(--or-border, rgba(127,127,127,.3));
|
||||
background:var(--or-img-bg, rgba(0,0,0,.2));cursor:zoom-in;
|
||||
}
|
||||
@media (max-width:900px){
|
||||
.or-kpi-row{grid-template-columns:repeat(3,minmax(0,1fr))}
|
||||
}
|
||||
@media (max-width:640px){
|
||||
.or-kpi-row{grid-template-columns:repeat(2,minmax(0,1fr))}
|
||||
.or-detail-images{grid-template-columns:1fr}
|
||||
.or-detail-img-thumb{max-height:220px}
|
||||
}
|
||||
</style>
|
||||
|
||||
{# 1. 交易记录(含 Tab/筛选,固定约5行) #}
|
||||
<div class="card" style="margin-bottom:10px">
|
||||
<div class="form-row" style="flex-wrap:wrap;align-items:center;gap:8px;margin-bottom:6px">
|
||||
<h2 style="margin:0;margin-right:auto">期权复盘</h2>
|
||||
<span class="muted" id="or-sync-status" style="font-size:.72rem"></span>
|
||||
<button type="button" class="btn-secondary" id="or-reload-btn" style="font-size:.76rem;padding:4px 10px">刷新</button>
|
||||
</div>
|
||||
<div class="or-page-head">
|
||||
<h2>期权复盘</h2>
|
||||
<span class="muted" id="or-sync-status" style="font-size:.72rem"></span>
|
||||
<button type="button" class="btn-secondary" id="or-reload-btn" style="font-size:.76rem;padding:4px 10px">刷新</button>
|
||||
</div>
|
||||
|
||||
{# Tab + 筛选:放在各内容卡片上方,全局作用于下方列表/统计 #}
|
||||
<div class="or-toolbar">
|
||||
<div class="or-tabs" role="tablist" aria-label="复盘分类">
|
||||
<button type="button" class="or-tab active" data-source="option_spot" role="tab">期权交易记录</button>
|
||||
<button type="button" class="or-tab" data-source="options_options" role="tab">期期对冲记录</button>
|
||||
<button type="button" class="or-tab" data-source="perp_options" role="tab">永期对冲记录</button>
|
||||
</div>
|
||||
<p class="muted" style="margin:0 0 8px;font-size:.72rem">待复盘交易(每页5条).点「复盘」填写表单;保存后进入下方复盘记录.</p>
|
||||
<div class="form-row" style="flex-wrap:wrap;gap:6px;margin-bottom:8px">
|
||||
<select id="or-filter-uly" style="font-size:.76rem">
|
||||
<div class="or-filters">
|
||||
<select id="or-filter-uly" autocomplete="off">
|
||||
<option value="">标的:全部</option>
|
||||
<option value="ETH">ETH</option>
|
||||
<option value="BTC">BTC</option>
|
||||
</select>
|
||||
<select id="or-filter-opt" style="font-size:.76rem">
|
||||
<select id="or-filter-opt" autocomplete="off">
|
||||
<option value="">Call/Put:全部</option>
|
||||
<option value="C">Call</option>
|
||||
<option value="P">Put</option>
|
||||
</select>
|
||||
<input type="text" id="or-filter-strategy" placeholder="策略标签" style="max-width:110px;font-size:.76rem">
|
||||
<input type="datetime-local" id="or-filter-from" title="平仓起" style="font-size:.76rem">
|
||||
<input type="datetime-local" id="or-filter-to" title="平仓止" style="font-size:.76rem">
|
||||
<label class="muted" style="display:flex;align-items:center;gap:4px;font-size:.72rem">
|
||||
<input type="text" name="username" autocomplete="username" tabindex="-1" aria-hidden="true"
|
||||
style="position:absolute;left:-9999px;width:1px;height:1px;opacity:0" value="">
|
||||
<input type="search" id="or-filter-q" name="or_filter_q" placeholder="搜索标的/合约/策略"
|
||||
autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false"
|
||||
data-lpignore="true" data-1p-ignore="true" data-form-type="other" readonly>
|
||||
<input type="datetime-local" id="or-filter-from" title="平仓起" autocomplete="off">
|
||||
<input type="datetime-local" id="or-filter-to" title="平仓止" autocomplete="off">
|
||||
<label class="muted">
|
||||
<input type="checkbox" id="or-include-hedge-legs"> 含已归属对冲的期权腿
|
||||
</label>
|
||||
</div>
|
||||
<h3 id="or-list-title" style="margin-top:0">期权交易记录</h3>
|
||||
</div>
|
||||
|
||||
{# 1. 交易记录 #}
|
||||
<section class="or-section" aria-labelledby="or-list-title">
|
||||
<div class="or-section-head">
|
||||
<span class="or-step" aria-hidden="true">1</span>
|
||||
<div>
|
||||
<div class="or-section-title" id="or-list-title">期权交易记录</div>
|
||||
<p class="or-section-desc">点「复盘」填写表单;已复盘仍保留在此,也可在下方查看详情。</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="options-strike-table-wrap or-trades-table-wrap" id="or-trades-wrap">
|
||||
<table class="options-strike-table or-trades-table" id="or-trades-table">
|
||||
<thead>
|
||||
@@ -79,13 +230,14 @@
|
||||
<th>类型</th>
|
||||
<th>标的/合约</th>
|
||||
<th>盈亏</th>
|
||||
<th>开/平</th>
|
||||
<th>开仓时间</th>
|
||||
<th>平仓时间</th>
|
||||
<th>持有</th>
|
||||
<th>操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="or-trades-tbody">
|
||||
<tr><td colspan="6" class="muted">加载中…</td></tr>
|
||||
<tr><td colspan="7" class="muted">加载中…</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
@@ -94,23 +246,33 @@
|
||||
<span class="muted" id="or-trades-page-label">第 1 / 1 页</span>
|
||||
<button type="button" class="btn-secondary" id="or-trades-next" style="font-size:.72rem;padding:2px 8px">下一页</button>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{# 2. 复盘上传(默认隐藏,点交易「复盘」后显示) #}
|
||||
<div class="card journal-card or-journal-card hidden" id="or-journal-card" style="margin-bottom:10px">
|
||||
<h2>复盘记录上传(含截图)</h2>
|
||||
<p class="muted" id="or-journal-summary" style="margin-top:0">截图槽位与合约复盘相同(5m / 15m / 1h / 4h).</p>
|
||||
{# 2. 复盘上传(默认隐藏) #}
|
||||
<section class="or-section journal-card or-journal-card hidden" id="or-journal-card">
|
||||
<div class="or-section-head">
|
||||
<span class="or-step" aria-hidden="true">✎</span>
|
||||
<div>
|
||||
<div class="or-section-title">填写复盘</div>
|
||||
<p class="or-section-desc" id="or-journal-summary">截图槽位 5m / 15m / 1h / 4h,选文件后即时上传。</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="or-journal-body">
|
||||
<form id="or-journal-form" onsubmit="return false;">
|
||||
<input type="hidden" id="or-trade-id" value="">
|
||||
<input type="hidden" id="or-draft-id" value="">
|
||||
<div class="or-form-grid">
|
||||
<input type="datetime-local" id="or-f-open" title="开仓时间">
|
||||
<input type="datetime-local" id="or-f-close" title="平仓时间">
|
||||
<input type="text" id="or-f-coin" placeholder="标的(如 ETH)">
|
||||
<input type="text" id="or-f-inst" placeholder="合约/计划">
|
||||
<input type="text" id="or-f-pnl" placeholder="盈亏(U)">
|
||||
<input type="text" id="or-f-hold" placeholder="持有时长" readonly>
|
||||
<input type="datetime-local" id="or-f-open" title="开仓时间" autocomplete="off">
|
||||
<input type="datetime-local" id="or-f-close" title="平仓时间" autocomplete="off">
|
||||
<input type="text" id="or-f-coin" name="or_f_coin" placeholder="标的(如 ETH)"
|
||||
autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false"
|
||||
data-lpignore="true" data-1p-ignore="true" data-form-type="other">
|
||||
<input type="text" id="or-f-inst" name="or_f_inst" placeholder="合约/计划"
|
||||
autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false"
|
||||
data-lpignore="true" data-1p-ignore="true" data-form-type="other">
|
||||
<input type="text" id="or-f-pnl" name="or_f_pnl" placeholder="盈亏(U)"
|
||||
autocomplete="off" inputmode="decimal" data-lpignore="true" data-1p-ignore="true" data-form-type="other">
|
||||
<input type="text" id="or-f-hold" name="or_f_hold" placeholder="持有时长" readonly autocomplete="off">
|
||||
</div>
|
||||
<div class="or-form-grid2">
|
||||
<select id="or-f-strategy" title="策略标签" required>
|
||||
@@ -145,13 +307,12 @@
|
||||
<option value="">入场逻辑</option>
|
||||
</select>
|
||||
|
||||
<input type="hidden" id="journal-draft-id" value="">
|
||||
<div class="journal-upload-slots" id="or-upload-slots">
|
||||
{% for tf in ['5m', '15m', '1h', '4h'] %}
|
||||
<div class="journal-upload-row" data-tf="{{ tf }}">
|
||||
<span class="journal-upload-slot-label">{{ tf }}</span>
|
||||
<input type="file" accept="image/*" class="journal-upload-slot-input or-upload-input" data-tf="{{ tf }}">
|
||||
<input type="hidden" class="journal-upload-hidden-file or-upload-hidden" data-tf="{{ tf }}" value="">
|
||||
<input type="file" accept="image/*" class="or-upload-input" data-tf="{{ tf }}">
|
||||
<input type="hidden" class="or-upload-hidden" data-tf="{{ tf }}" value="">
|
||||
<span class="journal-upload-status or-upload-status" data-tf="{{ tf }}" aria-live="polite"></span>
|
||||
</div>
|
||||
{% endfor %}
|
||||
@@ -176,26 +337,36 @@
|
||||
<div id="or-legs-host" style="margin-top:10px;font-size:.74rem"></div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{# 3. 已复盘记录 + 详情 #}
|
||||
<div class="card" style="margin-bottom:10px">
|
||||
<h3>复盘记录</h3>
|
||||
<p class="muted" style="margin:0 0 8px;font-size:.72rem">已保存的复盘(每页5条).点一行查看详情.</p>
|
||||
{# 3. 已复盘记录 #}
|
||||
<section class="or-section" aria-labelledby="or-reviewed-heading">
|
||||
<div class="or-section-head">
|
||||
<span class="or-step" aria-hidden="true">2</span>
|
||||
<div>
|
||||
<div class="or-section-title" id="or-reviewed-heading">复盘记录</div>
|
||||
<p class="or-section-desc">已保存的复盘内容,点一行查看详情与截图。</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="options-strike-table-wrap or-reviewed-table-wrap" id="or-reviewed-wrap">
|
||||
<table class="options-strike-table or-reviewed-table" id="or-reviewed-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>类型</th>
|
||||
<th>标的/合约</th>
|
||||
<th>方向</th>
|
||||
<th>盈亏</th>
|
||||
<th>开仓时间</th>
|
||||
<th>平仓时间</th>
|
||||
<th>持仓时长</th>
|
||||
<th>策略</th>
|
||||
<th>入场逻辑</th>
|
||||
<th>结果</th>
|
||||
<th>复盘时间</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="or-reviewed-tbody">
|
||||
<tr><td colspan="6" class="muted">加载中…</td></tr>
|
||||
<tr><td colspan="11" class="muted">加载中…</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
@@ -204,24 +375,37 @@
|
||||
<span class="muted" id="or-reviewed-page-label">第 1 / 1 页</span>
|
||||
<button type="button" class="btn-secondary" id="or-reviewed-next" style="font-size:.72rem;padding:2px 8px">下一页</button>
|
||||
</div>
|
||||
<div class="or-detail-panel hidden" id="or-detail-panel">
|
||||
<div class="form-row" style="align-items:center;gap:8px;margin-bottom:6px">
|
||||
<h3 style="margin:0;margin-right:auto" id="or-detail-title">复盘详情</h3>
|
||||
</section>
|
||||
|
||||
{# 详情 / 放大 #}
|
||||
<div id="or-detail-backdrop" class="or-detail-backdrop" hidden>
|
||||
<div class="or-detail-modal" role="dialog" aria-modal="true" aria-labelledby="or-detail-title" id="or-detail-panel">
|
||||
<div class="or-detail-modal-head">
|
||||
<h3 id="or-detail-title">复盘详情</h3>
|
||||
<button type="button" class="btn-secondary" id="or-detail-edit-btn" style="font-size:.72rem;padding:2px 8px">编辑</button>
|
||||
<button type="button" class="btn-secondary" id="or-detail-close-btn" style="font-size:.72rem;padding:2px 8px">收起</button>
|
||||
<button type="button" class="btn-secondary" id="or-detail-close-btn" style="font-size:.72rem;padding:2px 8px">关闭</button>
|
||||
</div>
|
||||
<div class="or-detail-grid" id="or-detail-meta"></div>
|
||||
<div id="or-detail-text" style="font-size:.76rem;line-height:1.5;margin-bottom:8px"></div>
|
||||
<div class="or-detail-images" id="or-detail-images"></div>
|
||||
</div>
|
||||
</div>
|
||||
<div id="or-img-lightbox" class="or-img-lightbox" hidden>
|
||||
<img id="or-img-lightbox-img" src="" alt="截图放大">
|
||||
</div>
|
||||
|
||||
{# 4. 统计 #}
|
||||
<div class="card" style="margin-bottom:10px">
|
||||
<h3>统计</h3>
|
||||
<div id="or-kpi" class="form-row" style="flex-wrap:wrap;gap:10px"></div>
|
||||
<div id="or-stats-groups" style="margin-top:10px;display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:8px"></div>
|
||||
</div>
|
||||
<section class="or-section" aria-labelledby="or-stats-heading">
|
||||
<div class="or-section-head">
|
||||
<span class="or-step" aria-hidden="true">3</span>
|
||||
<div>
|
||||
<div class="or-section-title" id="or-stats-heading">统计</div>
|
||||
<p class="or-section-desc">跟随上方 Tab 与筛选条件汇总。</p>
|
||||
</div>
|
||||
</div>
|
||||
<div id="or-kpi" class="or-kpi-row"></div>
|
||||
<div id="or-stats-groups" class="or-stats-grid"></div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<script src="/static/options_review.js?v=10"></script>
|
||||
<script src="/static/options_review.js?v=22"></script>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
{# 期权设置脚本挂载点(卡片在 settings_panel 中拆分) #}
|
||||
<div id="options-settings-root" hidden
|
||||
data-sub-account="{{ instance_settings.options_sub_account | default('', true) }}"></div>
|
||||
<script src="/static/options_settings.js?v=8"></script>
|
||||
<script src="/static/options_settings.js?v=9"></script>
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
<div class="options-settings-section">
|
||||
<p class="options-settings-hint">主账户资金账户:USDT ↔ USDC 现货市价单.</p>
|
||||
<div class="form-row settings-transfer-form options-settings-row">
|
||||
<select id="opt-set-swap-dir" aria-label="兑换方向">
|
||||
<input type="text" name="username" autocomplete="username" tabindex="-1" aria-hidden="true"
|
||||
style="position:absolute;left:-9999px;width:1px;height:1px;opacity:0" value="">
|
||||
<select id="opt-set-swap-dir" aria-label="兑换方向" autocomplete="off">
|
||||
<option value="usdt_to_usdc" selected>USDT → USDC</option>
|
||||
<option value="usdc_to_usdt">USDC → USDT</option>
|
||||
</select>
|
||||
<input type="number" id="opt-set-swap-amount" min="0.01" step="0.01" placeholder="数量">
|
||||
<input type="number" id="opt-set-swap-amount" name="cm_opt_swap_amt" min="0.01" step="0.01" placeholder="数量"
|
||||
autocomplete="off" inputmode="decimal" data-lpignore="true" data-1p-ignore="true" data-bwignore="true" data-form-type="other" readonly>
|
||||
<button type="button" class="btn-secondary btn-sm" id="opt-set-swap-all-btn">全部兑换</button>
|
||||
<button type="button" class="btn-primary btn-sm" id="opt-set-swap-btn">市价兑换</button>
|
||||
</div>
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
<div class="options-settings-section">
|
||||
<div class="options-settings-subtitle">主账户内</div>
|
||||
<div class="form-row settings-transfer-form options-settings-row">
|
||||
<select id="opt-set-int-ccy" aria-label="币种">
|
||||
<input type="text" name="username" autocomplete="username" tabindex="-1" aria-hidden="true"
|
||||
style="position:absolute;left:-9999px;width:1px;height:1px;opacity:0" value="">
|
||||
<select id="opt-set-int-ccy" aria-label="币种" autocomplete="off">
|
||||
<option value="USDC" selected>USDC</option>
|
||||
<option value="USDT">USDT</option>
|
||||
</select>
|
||||
@@ -13,7 +15,8 @@
|
||||
<option value="trading" selected>to: 交易</option>
|
||||
<option value="funding">to: 资金</option>
|
||||
</select>
|
||||
<input type="number" id="opt-set-int-amount" min="0.01" step="0.01" placeholder="数量">
|
||||
<input type="number" id="opt-set-int-amount" name="cm_opt_int_amt" min="0.01" step="0.01" placeholder="数量"
|
||||
autocomplete="off" inputmode="decimal" data-lpignore="true" data-1p-ignore="true" data-bwignore="true" data-form-type="other" readonly>
|
||||
<button type="button" class="btn-secondary btn-sm" id="opt-set-int-all-btn">全部划转</button>
|
||||
<button type="button" class="btn-primary btn-sm" id="opt-set-int-btn">划转</button>
|
||||
</div>
|
||||
@@ -26,7 +29,9 @@
|
||||
<span class="muted">({{ instance_settings.options_sub_account or '未配置' }})</span>
|
||||
</div>
|
||||
<div class="form-row settings-transfer-form options-settings-row">
|
||||
<select id="opt-set-cross-dir" aria-label="主子方向">
|
||||
<input type="text" name="username" autocomplete="username" tabindex="-1" aria-hidden="true"
|
||||
style="position:absolute;left:-9999px;width:1px;height:1px;opacity:0" value="">
|
||||
<select id="opt-set-cross-dir" aria-label="主子方向" autocomplete="off">
|
||||
<option value="main_to_sub" selected>主 → 子</option>
|
||||
<option value="sub_to_main">子 → 主</option>
|
||||
</select>
|
||||
@@ -42,7 +47,8 @@
|
||||
<option value="trading" selected>to: 交易</option>
|
||||
<option value="funding">to: 资金</option>
|
||||
</select>
|
||||
<input type="number" id="opt-set-cross-amount" min="0.01" step="0.01" placeholder="数量">
|
||||
<input type="number" id="opt-set-cross-amount" name="cm_opt_cross_amt" min="0.01" step="0.01" placeholder="数量"
|
||||
autocomplete="off" inputmode="decimal" data-lpignore="true" data-1p-ignore="true" data-bwignore="true" data-form-type="other" readonly>
|
||||
<button type="button" class="btn-secondary btn-sm" id="opt-set-cross-all-btn">全部划转</button>
|
||||
<button type="button" class="btn-primary btn-sm" id="opt-set-cross-btn">划转</button>
|
||||
</div>
|
||||
|
||||
@@ -7,14 +7,17 @@
|
||||
划转:自动划转 {{ '开启' if auto_transfer_enabled else '关闭' }}(每天<strong>北京时间 {{ auto_transfer_bj_hour }}:00</strong>起该整点小时内尝试;账簿按 <strong>UTC 自然日</strong>去重;将 {{ auto_transfer_to }} 调整至 {{ transfer_amount_fmt|default(funds_fmt(auto_transfer_amount)) }}U:不足从 {{ auto_transfer_from }} 划入,超出划回 {{ auto_transfer_from }};<strong>持仓中不划转</strong>并微信通知)
|
||||
</div>
|
||||
</details>
|
||||
<form action="/manual_transfer" method="post" class="form-row gate-transfer-form">
|
||||
<input name="amount" type="number" min="0.01" step="0.01" placeholder="手动划转金额U" required>
|
||||
<select name="from_account">
|
||||
<form action="/manual_transfer" method="post" class="form-row gate-transfer-form" autocomplete="off">
|
||||
<input type="text" name="username" autocomplete="username" tabindex="-1" aria-hidden="true"
|
||||
style="position:absolute;left:-9999px;width:1px;height:1px;opacity:0" value="">
|
||||
<input name="amount" type="number" min="0.01" step="0.01" placeholder="手动划转金额U" required
|
||||
autocomplete="off" inputmode="decimal" data-lpignore="true" data-1p-ignore="true" data-bwignore="true" data-form-type="other" readonly>
|
||||
<select name="from_account" autocomplete="off">
|
||||
<option value="funding" {% if auto_transfer_from == 'funding' %}selected{% endif %}>from: funding</option>
|
||||
<option value="swap" {% if auto_transfer_from == 'swap' %}selected{% endif %}>from: swap</option>
|
||||
<option value="spot" {% if auto_transfer_from == 'spot' %}selected{% endif %}>from: spot</option>
|
||||
</select>
|
||||
<select name="to_account">
|
||||
<select name="to_account" autocomplete="off">
|
||||
<option value="swap" {% if auto_transfer_to == 'swap' %}selected{% endif %}>to: swap</option>
|
||||
<option value="funding" {% if auto_transfer_to == 'funding' %}selected{% endif %}>to: funding</option>
|
||||
<option value="spot" {% if auto_transfer_to == 'spot' %}selected{% endif %}>to: spot</option>
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
{# 复盘表单:首行按字段宽度比例;下单类型/开仓类型与离场触发同一行 #}
|
||||
{% macro journal_form_fields(entry_reason_options, order_type_options) -%}
|
||||
<div class="form-grid journal-form-row1">
|
||||
<input type="datetime-local" name="open_datetime" class="journal-field-datetime" required>
|
||||
<input type="datetime-local" name="close_datetime" class="journal-field-datetime" required>
|
||||
<input name="coin" class="journal-field-coin" placeholder="BTC" required>
|
||||
<input name="tf" class="journal-field-tf" placeholder="5m" required>
|
||||
<input name="pnl" class="journal-field-num" placeholder="盈亏(U)" required>
|
||||
<input name="expect_rr" class="journal-field-num" placeholder="预期RR">
|
||||
<input name="real_rr" class="journal-field-num" placeholder="实际RR">
|
||||
<input type="datetime-local" name="open_datetime" class="journal-field-datetime" required autocomplete="off">
|
||||
<input type="datetime-local" name="close_datetime" class="journal-field-datetime" required autocomplete="off">
|
||||
<input name="coin" class="journal-field-coin" placeholder="BTC" required autocomplete="off" data-lpignore="true" data-1p-ignore="true" data-form-type="other">
|
||||
<input name="tf" class="journal-field-tf" placeholder="5m" required autocomplete="off" data-lpignore="true" data-1p-ignore="true" data-form-type="other">
|
||||
<input name="pnl" class="journal-field-num" placeholder="盈亏(U)" required autocomplete="off" inputmode="decimal" data-lpignore="true" data-1p-ignore="true" data-form-type="other">
|
||||
<input name="expect_rr" class="journal-field-num" placeholder="预期RR" autocomplete="off" inputmode="decimal" data-lpignore="true" data-1p-ignore="true" data-form-type="other">
|
||||
<input name="real_rr" class="journal-field-num" placeholder="实际RR" autocomplete="off" inputmode="decimal" data-lpignore="true" data-1p-ignore="true" data-form-type="other">
|
||||
</div>
|
||||
<div class="form-grid journal-form-row2">
|
||||
<select name="direction" id="journal-direction" class="journal-field-direction" required title="做多/做空">
|
||||
@@ -38,7 +38,7 @@
|
||||
<option value="止损">止损</option>
|
||||
<option value="其他">其他</option>
|
||||
</select>
|
||||
<input name="early_exit_note" id="early-exit-note" placeholder="离场补充(仅手工平仓必填)">
|
||||
<input name="early_exit_note" id="early-exit-note" placeholder="离场补充(仅手工平仓必填)" autocomplete="off" data-lpignore="true" data-1p-ignore="true" data-form-type="other">
|
||||
<select name="post_breakeven_stare"><option value="否">保本后盯盘:否</option><option value="是">保本后盯盘:是</option></select>
|
||||
</div>
|
||||
{%- endmacro %}
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
{% endfor %}
|
||||
</select>
|
||||
{% else %}
|
||||
<input id="{{ id }}" name="{{ name }}" placeholder="{{ placeholder }}" {% if required %}required{% endif %} value="{{ value }}">
|
||||
<input id="{{ id }}" name="{{ name }}" placeholder="{{ placeholder }}" {% if required %}required{% endif %} value="{{ value }}" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" data-lpignore="true" data-1p-ignore="true" data-form-type="other">
|
||||
{% endif %}
|
||||
{%- endmacro %}
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user