5 Commits

Author SHA1 Message Date
dekun 40be3a5ab7 Fix snapshot tag commit hash in docs table.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-23 02:01:22 +08:00
dekun 4ccfb838f6 Record pre-amp-stats snapshot and freeze amp-stats plan.
Tag baseline before hub-only amplitude statistics feature work.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-23 02:01:21 +08:00
dekun 58e9c8f85e Feed options positions and playbook brief into trading coach.
Coach context previously omitted options_snapshot details; also inject a short 执行手册 summary each turn.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-22 23:28:16 +08:00
dekun eb0eddbc9d Tighten mobile monitor stats to two lines and hide ops fold.
Desktop refresh/emergency-close and expanded stats layout stay unchanged.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-22 22:17:14 +08:00
dekun c5f40cba2b Align snapshot/20260721-2 hash with tag target.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-21 22:24:02 +08:00
10 changed files with 588 additions and 15 deletions
+262
View File
@@ -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** |
| **振幅** | `(HO)+(OL)` = **`HL`** | **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 |
+3 -3
View File
@@ -6,7 +6,8 @@
| 标签 | 指向提交 | 说明 |
|------|----------|------|
| `snapshot/20260721-2` | `77f66bf` | 2026-07-21 晚:日亏损次数冻结、交易执行手册入中控策略说明、期权/Gate 执行手册文档等 |
| `snapshot/20260723-pre-amp-stats` | 4ccfb83 | 2026-07-23:振幅统计开发前;含执行手册进教练、日亏损冻结、手机监控 UI、振幅统计开发方案等 |
| `snapshot/20260721-2` | `a721642` | 2026-07-21 晚:日亏损次数冻结、交易执行手册入中控策略说明、期权/Gate 执行手册文档等 |
| `snapshot/20260721` | `1a163c0` | 2026-07-21:仓库代码统计文档、期权复盘亮色主题、对冲腿盈亏时区修复、本快照说明等 |
## 历史标签(节选)
@@ -26,11 +27,10 @@
git tag -l 'snapshot/*'
# 检出快照(只读查看,勿在此分支直接开发)
git checkout snapshot/20260721-2
git checkout snapshot/20260723-pre-amp-stats
# 回到主线
git checkout main
```
数据备份(SQLite / 中控 JSON)走中控备份或各所 `scripts/backup_data.sh`**不要**把含密钥的 `.env` 与库文件提交进 Git。
+1 -1
View File
@@ -6,7 +6,7 @@
| 功能 | 说明 |
|------|------|
| **交易教练** | 口语化陪聊;注入三户监控快照与今日总结摘要(后台自动生成,不在页面展示) |
| **交易教练** | 口语化陪聊;注入三户监控快照(**含 OKX 期权持仓明细**)、执行手册短摘要与今日总结摘要(后台自动生成,不在页面展示) |
| **普通聊天** | 不绑交易数据,适合闲聊,答疑 |
| **交易监管** | 今日长会话;手动/中控开平仓与新开仓自动推送 + 企业微信 + 可回聊(见 [交易监管说明.md](./交易监管说明.md)) |
| **会话历史** | 右侧列表:切换,删除;消息一键复制 |
+6
View File
@@ -25,6 +25,7 @@ from hub_ai.context import (
format_chat_context_for_chat,
format_chat_position_overview,
)
from hub_ai.playbook_brief import format_playbook_brief_for_chat
from hub_ai.prompts import (
CHAT_GENERAL_SYSTEM,
CHAT_SYSTEM,
@@ -217,6 +218,10 @@ def send_chat_message(
ctx = build_chat_context(exchanges, trading_day=day)
day = ctx["trading_day"]
brief_ctx, excerpt = _trading_context_bundle(ctx, prior_count=prior_count)
# 首轮带完整手册摘要;续聊缩短,避免挤占对话上下文
playbook = format_playbook_brief_for_chat(
max_chars=1200 if prior_count <= 0 else 700
)
user_prompt = build_chat_user_prompt(
context_text=brief_ctx,
trading_day=day,
@@ -225,6 +230,7 @@ def send_chat_message(
history_lines=history_tail,
user_message=user_for_prompt,
attachment_note=str(parsed.get("attachment_note") or ""),
playbook_brief=playbook,
)
if parsed.get("text_append"):
user_prompt += "\n\n【附件正文】\n" + _clip_text(parsed["text_append"], 3000)
+115 -9
View File
@@ -86,7 +86,81 @@ def _filter_open_positions(positions: list) -> list[dict]:
def _account_open_position_count(ac: dict) -> int:
return len(_filter_open_positions(ac.get("positions") or []))
perp = len(_filter_open_positions(ac.get("positions") or []))
opt = int(ac.get("options_open_position_count") or 0)
if opt <= 0:
opt = len(_iter_options_position_dicts(ac))
return perp + opt
def _iter_options_position_dicts(ac: dict) -> list[dict]:
snap = ac.get("options_snapshot")
if not isinstance(snap, dict):
return []
if snap.get("ok") is False or snap.get("enabled") is False:
return []
out: list[dict] = []
for p in snap.get("positions") or []:
if not isinstance(p, dict):
continue
inst = str(p.get("inst_id") or p.get("instId") or "").strip()
if not inst:
continue
out.append(p)
return out
def _format_options_position_detail_line(p: dict) -> str:
inst = p.get("inst_id") or p.get("instId") or "?"
opt_type = (p.get("opt_type") or p.get("optType") or "").upper()
label = "Call" if opt_type == "C" else "Put" if opt_type == "P" else (opt_type or "OPT")
src = _options_source_label(p)
sheets = p.get("pos")
if sheets is None:
sheets = p.get("sheets")
if sheets is None:
sheets = p.get("contracts")
if sheets is None:
sheets = "?"
parts = [f"期权 {inst} {label}", f"来源{src}", f"张数{sheets}"]
paid = _safe_float(p.get("premium_paid"))
if paid is not None:
parts.append(f"权利金{paid:g}U")
net: Optional[float] = None
try:
from lib.options.options_positions_lib import net_pnl_from_display_row
net = net_pnl_from_display_row(p)
except Exception:
net = None
if net is None:
net = _safe_float(p.get("net_pnl"))
if net is None:
net = _safe_float(p.get("upl"))
if net is not None:
parts.append(f"净盈亏{net:.4f}U")
tgt = _options_target_monitor_text(p)
if tgt and tgt not in ("", "-", ""):
parts.append(f"目标{tgt}")
return " - " + " ".join(parts)
def _append_options_position_lines(lines: list[str], ac: dict, *, limit: int = 6, indent: str = " - ") -> None:
rows = _iter_options_position_dicts(ac)
if not rows:
return
if indent.startswith(" "):
# chat slim: already under account bullet
for p in rows[:limit]:
lines.append(f" · {_format_options_position_detail_line(p).lstrip(' - ')}")
if len(rows) > limit:
lines.append(f" · …共{len(rows)}笔期权持仓")
return
lines.append("期权持仓明细(交易所实盘,含目标位若已挂):")
for p in rows[:limit]:
lines.append(_format_options_position_detail_line(p))
if len(rows) > limit:
lines.append(f" - …共{len(rows)}笔期权持仓")
def _monitor_counts(ac: dict) -> dict[str, int]:
@@ -788,7 +862,9 @@ def format_context_text(payload: dict) -> str:
lines.append(
f"【合计·今日 {day}】平仓盈亏 {totals.get('total_pnl_u')}U | "
f"笔数 {totals.get('closed_count')}(胜{totals.get('win_count')}/负{totals.get('loss_count')})| "
f"实盘持仓 {totals.get('open_position_count', 0)} | "
f"实盘持仓 {totals.get('open_position_count', 0)}"
f"(永续{totals.get('perpetual_open_position_count', totals.get('open_position_count', 0))}/"
f"期权{totals.get('options_open_position_count', 0)}) | "
f"浮盈亏 {totals.get('float_pnl_u')}U | "
f"资金账户合计 {_fmt_fund(totals.get('total_funding_usdt'))} | "
f"交易账户合计 {_fmt_fund(totals.get('total_trading_usdt'))}"
@@ -855,6 +931,7 @@ def format_context_text(payload: dict) -> str:
if not isinstance(p, dict):
continue
lines.append(_format_position_detail_line(p, hub_mon))
_append_options_position_lines(lines, ac, limit=8)
lines.append(
f"Agent合约余额:{ac.get('balance_usdt') if ac.get('balance_usdt') is not None else '未知'} USDT"
)
@@ -885,7 +962,9 @@ def format_summary_context_text(payload: dict) -> str:
lines.append(
f"【合计·今日 {day}】平仓盈亏 {totals.get('total_pnl_u')}U | "
f"笔数 {totals.get('closed_count')}(胜{totals.get('win_count')}/负{totals.get('loss_count')})| "
f"实盘持仓 {totals.get('open_position_count', 0)} | "
f"实盘持仓 {totals.get('open_position_count', 0)}"
f"(永续{totals.get('perpetual_open_position_count', totals.get('open_position_count', 0))}/"
f"期权{totals.get('options_open_position_count', 0)}) | "
f"浮盈亏 {totals.get('float_pnl_u')}U | "
f"资金账户合计 {_fmt_fund(totals.get('total_funding_usdt'))} | "
f"交易账户合计 {_fmt_fund(totals.get('total_trading_usdt'))}"
@@ -943,6 +1022,7 @@ def format_summary_context_text(payload: dict) -> str:
if not isinstance(p, dict):
continue
lines.append(_format_position_detail_line(p, hub_mon))
_append_options_position_lines(lines, ac, limit=8)
lines.append(
f"Agent合约余额:{ac.get('balance_usdt') if ac.get('balance_usdt') is not None else '未知'} USDT"
)
@@ -1289,21 +1369,30 @@ def collect_closed_trades_snapshot(
def format_chat_position_overview(payload: dict) -> str:
totals = payload.get("totals") or {}
total_open = int(totals.get("open_position_count") or 0)
opt_total = int(totals.get("options_open_position_count") or 0)
perp_total = int(
totals.get("perpetual_open_position_count")
if totals.get("perpetual_open_position_count") is not None
else max(0, total_open - opt_total)
)
if total_open <= 0:
head = f"【实盘持仓总览】当前空仓(监控户合计 0 仓).浮盈亏 0U 表示无持仓,不是「有仓但不动」."
else:
head = (
f"【实盘持仓总览】监控户合计 {total_open},"
f"【实盘持仓总览】监控户合计 {total_open}"
f"(永续{perp_total}/期权{opt_total}),"
f"浮盈亏合计 {totals.get('float_pnl_u')}U."
)
lines = [
head,
"【区分】只有带「持仓明细/交易所实盘」字样的才是已开仓;趋势回调,关键位,下单监控,顺势加仓是本地计划/监控,不算持仓.持仓明细若含止损/止盈价,表示已挂条件单或监控计划中有价位.",
"【区分】只有带「持仓明细/交易所实盘/期权持仓」字样的才是已开仓;趋势回调,关键位,下单监控,顺势加仓是本地计划/监控,不算持仓.持仓明细若含止损/止盈价,表示已挂条件单或监控计划中有价位.",
]
for ac in payload.get("accounts") or []:
if ac.get("status") == "未监控":
continue
n = int(ac.get("open_position_count") or _account_open_position_count(ac))
opt_n = int(ac.get("options_open_position_count") or len(_iter_options_position_dicts(ac)))
perp_n = len(_filter_open_positions(ac.get("positions") or []))
mc = _monitor_counts(ac)
mon_parts = []
if mc["trends"]:
@@ -1319,8 +1408,11 @@ def format_chat_position_overview(payload: dict) -> str:
lines.append(f"- {ac.get('name')}:空仓{mon_txt}")
else:
lines.append(
f"- {ac.get('name')}:{n} 浮盈亏{ac.get('float_pnl_u')}U{mon_txt}"
f"- {ac.get('name')}:{n}(永续{perp_n}/期权{opt_n}) "
f"浮盈亏{ac.get('float_pnl_u')}U{mon_txt}"
)
for p in _iter_options_position_dicts(ac)[:4]:
lines.append(f" · {_format_options_position_detail_line(p).lstrip(' - ')}")
return "\n".join(lines)
@@ -1328,11 +1420,19 @@ def format_chat_context_slim(payload: dict) -> str:
"""聊天专用:不含 180 日资金曲线与昨日平仓明细,避免挤占对话上下文."""
totals = payload.get("totals") or {}
day = totals.get("trading_day")
opt_total = int(totals.get("options_open_position_count") or 0)
perp_total = int(
totals.get("perpetual_open_position_count")
if totals.get("perpetual_open_position_count") is not None
else max(0, int(totals.get("open_position_count") or 0) - opt_total)
)
lines = [
f"【今日合计 {day}】平仓盈亏 {totals.get('total_pnl_u')}U | "
f"笔数 {totals.get('closed_count')}(胜{totals.get('win_count')}/负{totals.get('loss_count')})| "
f"实盘持仓 {totals.get('open_position_count', 0)} | 浮盈亏 {totals.get('float_pnl_u')}U",
"【说明】持仓=交易所实盘;趋势/关键位/监控单=本地计划,不等于已开仓.持仓行内「止损/止盈」= 交易所条件单或监控计划价(与监控页一致).",
f"实盘持仓 {totals.get('open_position_count', 0)}"
f"(永续{perp_total}/期权{opt_total}) | 浮盈亏 {totals.get('float_pnl_u')}U",
"【说明】持仓=交易所实盘(含期权);趋势/关键位/监控单=本地计划,不等于已开仓."
"永续行「止损/止盈」=条件单或监控计划价;期权行含合约/来源/权利金/净盈亏/目标位.",
]
for ac in payload.get("accounts") or []:
if ac.get("status") == "未监控":
@@ -1340,7 +1440,12 @@ def format_chat_context_slim(payload: dict) -> str:
continue
st = ac.get("trade_stats") or {}
open_n = int(ac.get("open_position_count") or _account_open_position_count(ac))
pos_txt = "空仓" if open_n <= 0 else f"{open_n}仓 浮盈亏{ac.get('float_pnl_u')}U"
opt_n = int(ac.get("options_open_position_count") or len(_iter_options_position_dicts(ac)))
perp_n = len(_filter_open_positions(ac.get("positions") or []))
if open_n <= 0:
pos_txt = "空仓"
else:
pos_txt = f"{open_n}仓(永续{perp_n}/期权{opt_n}) 浮盈亏{ac.get('float_pnl_u')}U"
mc = _monitor_counts(ac)
mon = []
if mc["trends"]:
@@ -1369,6 +1474,7 @@ def format_chat_context_slim(payload: dict) -> str:
if not isinstance(p, dict):
continue
lines.append(f" · {_format_position_detail_line(p, hub_mon).lstrip(' - ')}")
_append_options_position_lines(lines, ac, limit=6, indent=" · ")
return "\n".join(lines)
@@ -0,0 +1,28 @@
"""交易教练用的执行手册短摘要(来源 docs/交易执行手册-期权与Gate.md)."""
from __future__ import annotations
from pathlib import Path
from lib.paths import REPO_ROOT
# 控制 token:保持简短;手册大改时同步修订本摘要.
_PLAYBOOK_BRIEF = """【用户策略执行手册·摘要】(来源:docs/交易执行手册-期权与Gate.md)
一句话:横盘对冲(可偏置实值);突破用一天期权;假破确认后小仓合约加强;先过方向/空间/值不值得;期权不手平;一位置两次,错完收工;单笔小亏、组合回撤可控.
分工:OKX 期权=主业;Gate 合约=辅业;其它账户暂不做.同一时段尽量只让一边说话.
入场三类:①横盘较久→期期对冲(一天 Call+Put,总权利金约10U),期间一般不开 Gate;②方向/空间/值不值得过关且结构突破→一天期权方向单,默认不上合约;③已有突破期权后出现反向假破确认→Gate 小仓加强(加重暴露,按一笔故事控风险).
仓位(总资约800U):单笔期权约10U且一次一仓;期期对冲合计约10U;Gate 保证金约50U×约10x,止损约5U,单笔最亏约≤10U;日最坏约≤20U.
期权纪律:不手动平仓,只认规则止盈或到期(紧急手平非策略样本);默认一天期,尽量北京时间16:00后开次日到期.
Gate 纪律:只做很明确位置;同一位置最多两次机会(结构突破/假突破);两次都错→当日收工.
教练用法:对照上述纪律讨论执行与心态;勿另造策略或鼓励期权手平/超仓."""
def playbook_md_path() -> Path:
return REPO_ROOT / "docs" / "交易执行手册-期权与Gate.md"
def format_playbook_brief_for_chat(max_chars: int = 1200) -> str:
"""返回注入交易教练上下文的短摘要."""
text = _PLAYBOOK_BRIEF.strip()
if len(text) <= max_chars:
return text
return text[: max(200, max_chars - 1)].rstrip() + ""
+11 -1
View File
@@ -44,10 +44,12 @@ CHAT_SYSTEM = """
- 不要「第1点第2点你应该…」;不要「作为你的教练我必须…」.
- 不预测涨跌,不保证收益,不替用户做决定.
- 只能依据提供的监控与交易数据说话;看不到的就说「我这边看不到,你可以去 xx 实例页确认」.
- **持仓判定**:只有快照里「实盘持仓总览 / 持仓明细 / 交易所实盘」才算已开仓;「空仓 / 0 仓」就是没仓位.浮盈亏 0U 且空仓时,不要说「还有仓」「卡着不动」.
- **持仓判定**:只有快照里「实盘持仓总览 / 持仓明细 / 交易所实盘 / 期权持仓」才算已开仓;「空仓 / 0 仓」就是没仓位.浮盈亏 0U 且空仓时,不要说「还有仓」「卡着不动」.
- **期权持仓**:快照中「期权 …」行与永续同样是实盘;须分开提及.期权净盈亏/目标位以快照为准.
- **监控单 ≠ 持仓**:趋势回调,关键位,顺势加仓,下单监控是本地计划或挂单监控,用户说已平仓时,即使还有这些监控,也不要当成手里还有仓.
- 用户口述与快照冲突时,以快照为准并口语说明「我这边看到是空仓/有N仓」.
- 若附带「今日总结摘要」,那是较早生成的缓存,**实盘持仓以【当前多账户快照】里的「实盘持仓总览」为准**,摘要里若提到持仓可能已过时.
- 若附带【用户策略执行手册·摘要】,须按该纪律理解账户分工与离场规则(如期权通常不手平、Gate 一位置两次等);勿另造策略或鼓励违反摘要纪律.
- 若用户上传图片,可结合图中可见信息讨论,看不清的明确说看不清.
- **优先接住【用户现在说】和【对话核心摘要】**:用户聊心态,悔单,某笔操作时,先顺着这个话题回应,不要每句都复述账户资金数字.
- **接续对话**:有【对话核心摘要】时须接着聊,不要重复开场白;整段回复必须写完,以句号/问号/感叹号收尾,不得停在半句话;编号列表每条单独一行.
@@ -143,12 +145,20 @@ def build_chat_user_prompt(
history_lines: str = "",
user_message: str,
attachment_note: str = "",
playbook_brief: str = "",
) -> str:
parts = [f"【交易日】{trading_day}"]
if rolling_summary.strip():
parts.extend(["【对话核心摘要(须接续,勿重复开场)】", rolling_summary.strip()])
elif history_lines.strip():
parts.extend(["【最近对话】", history_lines.strip()])
if playbook_brief.strip():
parts.extend(
[
"【用户策略执行手册·摘要(须知悉分工与纪律)】",
playbook_brief.strip(),
]
)
parts.extend([
"【当前多账户快照(事实参考;持仓以「实盘持仓总览」为准)】",
context_text.strip() or "(无监控数据)",
+64
View File
@@ -4301,6 +4301,70 @@ body.login-page {
gap: 6px;
}
/* 手机:隐藏「操作·刷新/紧急全平」,桌面不变 */
body.hub-phone #monitor-ops-fold {
display: none !important;
}
/* 手机收起态:今日统计固定两行(左标题/交易日,右总浮盈亏) */
body.hub-phone .monitor-stats-card.is-collapsed {
padding: 0;
}
body.hub-phone .monitor-stats-card.is-collapsed .monitor-stats-head {
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
grid-template-rows: auto auto;
column-gap: 10px;
row-gap: 2px;
align-items: center;
padding: 10px 12px;
}
body.hub-phone .monitor-stats-card.is-collapsed .monitor-stats-head-main {
display: contents;
}
body.hub-phone .monitor-stats-card.is-collapsed .card-title-row {
grid-column: 1;
grid-row: 1;
flex-wrap: nowrap;
min-width: 0;
}
body.hub-phone .monitor-stats-card.is-collapsed .card-title {
font-size: 13px;
margin: 0;
}
body.hub-phone .monitor-stats-card.is-collapsed .card-sub {
grid-column: 1;
grid-row: 2;
margin: 0;
font-size: 10px;
line-height: 1.3;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
body.hub-phone .monitor-stats-card.is-collapsed .monitor-stats-float-summary {
grid-column: 2;
grid-row: 1 / span 2;
align-self: center;
padding: 0;
text-align: right;
}
body.hub-phone .monitor-stats-card.is-collapsed .monitor-stats-float-summary .monitor-stat-label {
margin-bottom: 0;
font-size: 10px;
}
body.hub-phone .monitor-stats-card.is-collapsed .monitor-stats-float-value {
font-size: 16px;
}
body.hub-phone .monitor-stat-cell {
padding: 8px 6px;
}
+1 -1
View File
@@ -16,7 +16,7 @@
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;500;600&family=Orbitron:wght@500;600;700&display=swap" rel="stylesheet" media="print" onload="this.media='all'" />
<noscript><link href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;500;600&family=Orbitron:wght@500;600;700&display=swap" rel="stylesheet" /></noscript>
<link rel="stylesheet" href="/assets/app.css?v=20260720-calc-equal-height" />
<link rel="stylesheet" href="/assets/app.css?v=20260722-monitor-m-stats" />
<link rel="stylesheet" href="/assets/trade_stats_calendar.css?v=4" />
<link rel="stylesheet" href="/assets/account_risk_badge.css?v=4" />
<script src="/assets/account_risk_badge.js?v=4"></script>
+97
View File
@@ -0,0 +1,97 @@
"""hub_ai:期权持仓进教练上下文 + 执行手册摘要."""
from __future__ import annotations
import unittest
from hub_ai.context import (
format_chat_context_for_chat,
format_chat_context_slim,
format_chat_position_overview,
)
from hub_ai.playbook_brief import format_playbook_brief_for_chat
from hub_ai.prompts import build_chat_user_prompt
def _sample_payload():
return {
"totals": {
"trading_day": "2026-07-22",
"total_pnl_u": 0,
"closed_count": 0,
"win_count": 0,
"loss_count": 0,
"float_pnl_u": 1.25,
"open_position_count": 1,
"options_open_position_count": 1,
"perpetual_open_position_count": 0,
},
"accounts": [
{
"name": "OKX_趋势",
"key": "okx",
"status": "已监控",
"open_position_count": 1,
"options_open_position_count": 1,
"float_pnl_u": 1.25,
"funding_usdt": 100,
"trading_usdt": 50,
"trade_stats": {"total_pnl_u": 0, "closed_count": 0, "win_count": 0, "loss_count": 0},
"positions": [],
"trades": [],
"monitor_lines": {},
"options_snapshot": {
"ok": True,
"enabled": True,
"positions": [
{
"inst_id": "ETH-USD-260723-3500-C",
"opt_type": "C",
"pos": 1,
"premium_paid": 8.5,
"source_label": "纯期权",
"source": "option",
"upl": 1.25,
"target_monitor_text": "目标 3600",
}
],
},
}
],
}
class HubAiOptionsPlaybookTests(unittest.TestCase):
def test_chat_slim_includes_options_line(self):
text = format_chat_context_slim(_sample_payload())
self.assertIn("期权 ETH-USD-260723-3500-C Call", text)
self.assertIn("永续0/期权1", text)
self.assertIn("权利金8.5U", text)
def test_overview_lists_options(self):
text = format_chat_position_overview(_sample_payload())
self.assertIn("期权1", text)
self.assertIn("ETH-USD-260723-3500-C", text)
def test_chat_bundle_keeps_options(self):
text = format_chat_context_for_chat(_sample_payload(), max_chars=8000)
self.assertIn("ETH-USD-260723-3500-C", text)
self.assertIn("期权", text)
def test_playbook_brief_injected(self):
brief = format_playbook_brief_for_chat()
self.assertIn("执行手册", brief)
self.assertIn("OKX", brief)
self.assertIn("不手动平仓", brief)
prompt = build_chat_user_prompt(
context_text="快照",
trading_day="2026-07-22",
summary_excerpt="",
user_message="今天怎么样",
playbook_brief=brief,
)
self.assertIn("用户策略执行手册", prompt)
self.assertIn("不手动平仓", prompt)
if __name__ == "__main__":
unittest.main()