Skip to content

修复网格连亏熔断数据流:GridManager 通过回调上报逐轮 PnL 至 ProtectionManager,并澄清网格风控适用范围、补齐测试。#96

Open
loadchange wants to merge 9 commits into
devfrom
feat/grid-per-trade-protection
Open

修复网格连亏熔断数据流:GridManager 通过回调上报逐轮 PnL 至 ProtectionManager,并澄清网格风控适用范围、补齐测试。#96
loadchange wants to merge 9 commits into
devfrom
feat/grid-per-trade-protection

Conversation

@loadchange

Copy link
Copy Markdown
Collaborator

No description provided.

…适用范围、补齐测试

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request implements a round-trip PnL callback mechanism for the grid trading system, connecting grid round-trip results to the account-level consecutive loss protection plugin. Specifically, GridManager now triggers an on_round_trip_close callback upon completing a round-trip, which main.py forwards to ProtectionManager.on_trade_close. This ensures consecutive loss protection is functional in pure grid mode. Additionally, a comprehensive test suite has been added to verify this dataflow and its error handling. There are no review comments to address, and I have no further feedback to provide.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

loadchange and others added 8 commits June 19, 2026 11:32
线上近10天网格净亏 -$8.4(realized -$6.4 + 手续费 -$2.1)。强制中性已消除 AI 方向
whipsaw,但中性网格在 ETH 单边上涨中机械累积逆势空头库存(平空累计 -$10.4、单笔最差
-$4.26、profit factor 0.67)。本提交针对该根因:

- 库存硬上限(grid_max_position_notional_usd,默认关):净持仓名义额达上限后禁止同向
  加仓,只放行减仓方向,堵死逆势无限累积。
- 趋势过滤(grid_trend_filter_*,默认关):多周期一致强势时本轮暂停加仓(合成 KEEP_GRID),
  可选市价平掉逆势库存(flatten_adverse)。
- Triple Barrier 每轮必查:从 sync_grid_incremental 窄分支提取为 check_barrier(),由
  grid_cycle 每轮无条件调用,KEEP_GRID/ERROR 周期也兜底止损。
- 紧急/市价平仓上报连亏熔断:_emergency_close_all 平仓前把持仓盈亏经 on_round_trip_close
  喂给 consecutive_loss(此前该插件对网格大额止损不可见,global_losses 恒 0)。

新增 tests/test_grid_loss_fixes.py(17 项);全量 611 passed/2 skipped,ruff 干净。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
线上实证(12.5 天):净值 $12.64 → $7.71(-39%),趋势过滤全量拆网 145 次,
连亏熔断 0 次触发,回撤熔断成为"下跌节拍器"(每级恰好 -10%)。防护体系
本身成为主要亏损来源。本次全部改造按宪法要求配置开关控制、默认关闭(保持
历史行为),测试网验证通过后逐项开启。

七项修复:
1. 手术式减仓(grid_trend_filter_surgical_flatten):趋势过滤只平超出库存
   上限的逆势层级(入场价最差优先),保留顺势挂单/层级状态/重建冷却,
   替代全量拆网 _emergency_close_all
2. 趋势过滤去噪+迟滞(grid_trend_filter_timeframes/confirm_cycles/
   flatten_min_cycles):计票周期白名单排除 1m 噪声;连续 N 周期同向确认
   才动作;暂停加仓先行、平逆势库存靠后
3. 连亏熔断 forced 语义(forced_close_no_reset):风控强平的净盈利不再
   重置连亏计数——145 次强平 0 次熔断的根因
4. 库存上限严格模式(grid_inventory_cap_strict):名义额计入同向未成交
   挂单(防一轮布单全成交超限数倍);取价/查单失败 fail-closed
5. 自适应仓位(grid_adaptive_sizing_enabled):单格金额与真实净值挂钩,
   资金不足减格数而非抬单格金额($15.5 硬下限曾把 $7.71 账户放大成 16 倍
   名义敞口);格数不足返回 INSUFFICIENT_CAPITAL 拒绝布单;补传 leverage
   (历史缺陷:恒用默认 10 与 config.max_leverage 脱钩)
6. 可观测性:trades jsonl 补 pnl+reason 归因(GRID_TP/紧急平仓/手术减仓);
   每周期净值快照写 logs/equity/*.jsonl(grid_equity_snapshot_enabled);
   净值停机线(grid_halt_below_usd)低于阈值且无持仓时跳过整周期不烧 LLM;
   KEEP_GRID 周期对账撤无主残单(grid_keep_grid_reconcile);保护插件
   暂停期重复告警降为 DEBUG(单次熔断曾刷 726 条重复 WARNING)
7. 回撤保护绝对额下限(min_drawdown_usd):防小账户上纯百分比线成为
   噪声级触发器

测试:新增 35 项测试(tests/test_grid_loss_refactor.py),全套 646 通过。
测试网冒烟验证:INSUFFICIENT_CAPITAL 拒绝布单、趋势迟滞 (1/2) 暂不动作、
强制中性覆盖、净值快照落盘均按预期工作。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
测试网实测(2026-07-04):新式统一账户 spot/perp 保证金合一,经典 perp
marginSummary 恒为 0,USDC 抵押显示在 spot 视图(balances[].total,挂单
占用在 hold),usdClassTransfer 被禁用("Action disabled when unified
account is active")。get_balance 只读 perp 视图会把有钱的账户误判为零
余额——$11 测试网账户被判 $0,自适应仓位随即 INSUFFICIENT_CAPITAL 拒绝
布单,机器人完全无法交易。

修复:perp 视图无资产时回退读取 spot USDC(total=抵押,hold=占用);
spot 查询失败时维持 perp 视图结果,不因兼容路径引入新故障;经典账户
(perp 有值)不多打一次 API。

主网账户目前仍是经典模式未受影响,但统一账户是官方演进方向,此为
前向兼容修复。新增 4 项单元测试,全套 650 通过。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
实测(测试网 2026-07-04):统一账户开仓后 perp marginSummary.accountValue
仅等于被占用抵押($11 账户只剩 $2.28 == spot hold),旧修复的
accountValue<=0 启发式不触发,净值被低估 80%。后果已在线上复现:
回撤保护把 11→2.28 判为 -79% 回撤,熔断平仓 + 撤光网格挂单。

- _is_unified_account(): 官方 userAbstraction 接口判定
  (unifiedAccount/portfolioMargin 以 spot 视图为准),结果缓存,
  经典账户零额外开销;判定失败退回原启发式兜底
- 测试 4→8 项:有持仓形态回归、模式缓存、判定失败双路径降级

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
线上实测(测试网 $1011 账户):重建入口的一次性布尔检查通过后
(空头敞口 $14.6 < 上限 $40),一轮批量挂出 4×$50 卖单,潜在同向
敞口 $214 达上限 5 倍——循环自己挂出的单不会被入口检查计入,
严格模式在逐单补格路径生效、在批量重建路径被'整轮稳定'优化抵消。

- 严格模式重建改额度制:_inventory_headroom_usd 预算,本轮已挂
  同向名义额累计扣减,耗尽即跳过剩余同向单(宽松模式行为不变)
- 抽出 _directional_exposure_usd 共用敞口计算,fail-closed 语义保持
- 快照补 position_notional:此前 log_equity_snapshot 从未传该字段,
  有持仓时恒记 0(uPnL 非零但名义额为 0 的矛盾即此)
- 新增 4 项额度制测试(每侧限额/不掐死/同向消耗/整侧拦截),全套 658 过

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
镜像构建此前不带 lock 文件重新解析依赖,装到删除了
pydantic_ai.models.gemini 模块路径的新版 pydantic-ai,容器启动即
ModuleNotFoundError 循环崩溃(测试网部署实测)。应用项目锁文件应入库,
构建用 --frozen 精确复现本地验证过的依赖版本(pydantic-ai 1.107.0)。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
旧 uv 0.1.45 生成的 lock 格式([[distribution]])镜像内 uv 0.10.5 无法
解析(SourceWire 解析错误)。用 0.10.5 重新生成,并在 pyproject 钉死
pydantic-ai==1.107.0(1.108+ 移除 gemini 模块路径)。隔离环境
--frozen 安装 + GeminiModel 导入已验证。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant