Skip to content

Fox/project takeover baseline - #1467

Open
huynhthiphuonghang321-oss wants to merge 488 commits into
NoFxAiOS:devfrom
MAX-LIUS:fox/project-takeover-baseline
Open

Fox/project takeover baseline#1467
huynhthiphuonghang321-oss wants to merge 488 commits into
NoFxAiOS:devfrom
MAX-LIUS:fox/project-takeover-baseline

Conversation

@huynhthiphuonghang321-oss

Copy link
Copy Markdown

Summary

  • Problem:
  • What changed:
  • What did NOT change (scope boundary):

Change Type

  • Bug fix
  • Feature
  • Refactoring
  • Docs
  • Security fix
  • Chore / infra

Scope

  • Trading engine / strategies
  • MCP / AI clients
  • API / server
  • Telegram bot / agent
  • Web UI / frontend
  • Config / deployment
  • CI/CD / infra

Linked Issues

  • Closes #
  • Related #

Testing

What you verified and how:

  • go build ./... passes
  • go test ./... passes
  • Manual testing done (describe below)

Security Impact

  • Secrets/keys handling changed? (Yes/No)
  • New/changed API endpoints? (Yes/No)
  • User input validation affected? (Yes/No)

Compatibility

  • Backward compatible? (Yes/No)
  • Config/env changes? (Yes/No)
  • Migration needed? (Yes/No)
  • If yes, upgrade steps:

@cla-assistant

cla-assistant Bot commented Apr 12, 2026

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

1 similar comment
@cla-assistant

cla-assistant Bot commented Apr 12, 2026

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

@huynhthiphuonghang321-oss

Copy link
Copy Markdown
Author

TP+SL

MAX-LIUS added 25 commits April 21, 2026 14:09
MAX-LIUS added 29 commits May 7, 2026 08:54
FindEntryDecisionCycleForPosition matched stale historical cycles because
the decision record is written 5-30s AFTER the order executes, so the
decision timestamp > position entry_time. The query 'timestamp <= entryTime'
missed the correct cycle and fell back to an older one with the same
symbol/side/action.

Impact: 3 out of 4 open positions had wrong entry_decision_cycle, causing
the protection reconciler to restore ladder SL from a completely different
price context (e.g., cycle 115 at price 2362 vs cycle 659 at price 2322).

Fixes:
1. Extend FindEntryDecisionCycleForPosition to include a 90-second grace
   window past entry_time, covering the typical AI response→execute→record
   pipeline delay.
2. restoreAIProtectionPlanForPositionWithEntry now validates that the
   restored decision's expected entry price is within 0.5% of the actual
   position entry price. If it deviates (indicating a stale/wrong cycle),
   the plan is skipped rather than applied with wrong price levels.
…ersal detection

- Add MinSLDistanceATRMul (1.2x) and MinRewardATRMul (1.8x) to EntryGateConfig
- New validateATRRelativeDistances() in kernel validation pipeline
- New ATR distance check (stage 3d) in trader entry gate (enforced)
- Regime reversal risk detection when 4h trend contradicts 1h action
- Core Trading Philosophy + ATR scale requirement in AI prompt
- Drawdown tier ATR-relative minimum profit trigger guidance
- UI: PreEntryGateEditor reorganized into 4 functional groups with i18n
- Fix test fixtures for ATR proximity/distance compatibility
Phase A - Prompt瘦身 + 后端补全:
- 删除情绪化语言(gambling/patience is alpha/NOISE/negative expectancy)
- Core Trading Philosophy → 中性 Trading Principles
- ATR-Relative Scale → Backend Entry Gates 解释
- buildDrawdownTierConstraintPrompt 从 HARD CONSTRAINTS 重写为 guidelines
- 删除 engine_analysis 中与 entry_gate 重复的 validateATRRelativeDistances
- 新增 enforceLeverageCap/enforceMaxMarginUsage 后端 enforce
- Drawdown stage 1 close_ratio >= 50% clamp
- Reversal risk 阈值 0.3% → 0.6%

Phase B - 市场数据增强:
- DerivativesEnriched 新增 CVD/OI增速/FundingTrend/VWAP/TakerDelta/DepthChangeRate
- 新增 CalculateCVD/CalculateVWAP/ClassifyFundingTrend 等计算函数
- OKX API: GetFundingRateHistory + GetOpenInterestHistory
- AI prompt 新增 Derivatives Deep Dive 段落
- 策略配置新增 6 个指标开关

Phase C - 评分系统科学化:
- percentileRank 替代 value/maxValue 归一化
- 新增 OIGrowth/FundingEdge 评分维度
- 第二梯队通道 (vol>=20M, OI>=8M, composite>0.70)

Entry gate 配置化:
- SqueezeMinConfidence/SqueezeMinRR/FallbackMinRR/ShortNonDowntrendMinConfidence
  从硬编码提取到 EntryGateConfig 支持运行时调参
Drawdown多级固定仓位系统:
- 开仓时固定分配各tier仓位(基于开仓量,后续不变)
- 每个tier独立追踪峰值和回撤,互不影响
- 未达tier由breakeven收尾(markUnreachedTiersForBE)
- 每级三维(仓位/峰值/回撤)独立AI/手动下拉控制
- Runner policy在tier分配前应用

Breakeven交易所侧委托:
- 开仓时直接下交易所条件止盈单(placeBreakEvenTPOrders)
- 使用SetTakeProfitTagged接口,不再依赖后端轮询

结构位可信度多维评分:
- VolumeScore: 高量触及比例(0-1)
- RecencyScore: 指数衰减时效分(0-1)
- AvgBounceVol: 反弹均量
- MultiTFCount: 跨周期确认数(enrichMultiTFConfirmation)
- Confidence: 综合置信度0-100(触及25%+量30%+时效25%+多TF20%)
- AI prompt输出conf/vol/mtf/touches

其他:
- crypto支持RSA_PRIVATE_KEY_FILE环境变量从文件加载密钥
- store/strategy.go: EntryGateConfig 新增 VolatilityBufferATRMul 字段
  (0=最紧, 1.5=最宽, 默认0.3), 控制SL额外波动保护距离

- trader/entry_gate.go: SL ATR距离校验加入波动缓冲
  有效阈值 = MinSLDistanceATRMul + VolatilityBufferATRMul
  (默认 1.2 + 0.3 = 1.5x ATR)

- trader/protection_phase3.go: buildAIDecisionLadderProtectionPlan
  新增自动加宽逻辑 — 当ladder SL委托价距离不够时自动推远到满足阈值

- kernel/engine_analysis.go: ensureLadderVolatilityBuffer 改用配置值
  代替硬编码0.35, 从 VolatilityBufferATRMul*0.7 计算缓冲系数

- kernel/engine_prompt.go: AI prompt注入实际配置的有效最小SL距离
  告知AI"后端要求SL >= Nx ATR", 引导AI从源头给足距离

- web/: 前端滑块UI — 止损质量组内新增波动保护容错滑块
  范围0~1.5, 步长0.1, 实时显示配置值

- 4个单元测试验证: 自动加宽(long/short)、距离足够不动、禁用不动
- entry_gate.go: SL距离硬拒绝只用基础阈值(1.2x ATR)
  波动缓冲检查改为信息性(Enforced=false, code=sl_distance_below_vol_buffer)
  这样AI给1.3x ATR的SL能通过gate, ladder阶段自动加宽到1.5x

- PreEntryGateEditor.tsx: 修复React.ReactNode导入
  改用 import { type ReactNode } from 'react' 避免HMR运行时错误

- main.tsx: ErrorBoundary接入应用入口, 防止白屏
React.Children undefined 运行时错误的根因是 Vite manualChunks 将 node_modules
拆成过多 chunk(react-vendor, chart-vendor, ui-vendor 等),导致 react-vendor
从 chart-vendor 和 vendor 循环导入,ESM 初始化顺序异常。

修复:简化 manualChunks 为三个独立 chunk:
- katex-vendor(大且独立,无 React 依赖)
- trading-chart-vendor(同上)
- vendor(其余所有 node_modules,含 React 全家桶)

消除循环依赖,前端恢复正常加载。
- adjustNativeDrawdownCallbackRatio: callback < 0.3% 时 clamp up 到 0.3% 而非 reject
  确保交易所始终有 trailing stop order(用户可见委托)
- checkPositionDrawdown: nativeTrailingHandled 只在 state 确实是 native trailing 时设 true
  防止 managed fallback 后阻塞 evaluateDrawdownTiers 执行
- getDrawdownArmRulesForSelectedRule: 新增 isManagedDrawdownRecord 检查
  防止 managed record 被误判为 stale 导致无限 re-arm 循环
- 新增 allow_ai_stop_close, allow_ai_take_profit, ai_stop_min_loss_pct 字段
- 后端: handler/store/manager/loop 全链路支持新字段
- engine_prompt: 根据 no_open/no_stop_close/no_take_profit 变体注入 prompt 约束
- 前端: 替换旧 checkbox 为 toggle 开关 (Open/SL/TP) + min loss % 调节器
- 运行时: close 决策按 is_stop_loss 分流,低于 min loss 阈值自动拦截
ladder 是渐进退出设计,第一层在结构位外、失效位内是合理的分层减仓。
校验 structural alignment 时应该用最深层(兜底层)和 invalidation 比较,
只要最终兜底在失效位外面,保护方案就是合理的。
…ightening

- Fibonacci lookback scales by timeframe (15m=100, 5m=120, 1m=150)
- Swing point lookback scales by timeframe (15m=7, 5m=8, 1m=10)
- Top bar badge: replace 'AI CLOSE OFF' with granular SL/TP status
- DecisionCard shows SL: ON/OFF | TP: ON/OFF instead of old AI Close
- Prompt: TP must come from higher-TF structure, min distance check
- Prompt: confidence >= 60 preferred, target >= 1.5x SL distance
- DecisionRecord API now returns allow_ai_stop_close/take_profit
Phase 1 — 后端结构位评估层:
- 新增 market/structure_evaluation.go: EvaluateForTrading() 按用途分类结构位
  (sl_anchor/tp_target/entry_trigger/context_only) + 质量评级 (high/medium/low)
- 重构 kernel/formatter_structural.go: prompt 按用途分组输出结构位
  (SL Candidates / TP Candidates / Entry Triggers / Context Only)
- 增加质量不足时的 ATR-based 替代建议

Phase 2 — AI 输出结构增强:
- kernel/engine.go: 新增 AISelectedLevel 类型 + Decision.SelectedLevels 字段
- AIProtectionLadderRule/DrawdownRule 新增 BasisType 字段
- engine_prompt.go: 要求 AI 输出 selected_levels (含 basis_type + reason)
- store/decision.go: DecisionActionReviewContext 新增 SelectedLevels
- trader/auto_trader_loop.go: mapSelectedLevels 传递到 review_context

Phase 3 — 前端决策面板重构:
- TraderDashboardPage: 新增 '关键决策/全部' 筛选 toggle (默认只看 open/close/rejected)
- DecisionCard: ActionCard 重写为 3 层结构
  - hold/wait 极简化为单行
  - open/close 展示 AI Selected Levels (basis_type 彩色标注)
  - 详情折叠 (trading details + gate attribution)
  - 去除重复的 audit badges

Phase 4 — 保护面板依据标注:
- PositionProtectionPanel: 每行保护项增加 basis_type 图标标注
  (🎯 structural / 📐 atr_based / 🌀 fibonacci / 📊 percentage)
- types/trading.ts: ProtectionRuntimeTier 新增 basis_type 字段
1. BE 不生效: getActiveBreakEvenRules 不再过滤 r_multiple 模式,
   新增 resolveBreakEvenRulesForPosition 将 R 倍数转换为 profit_pct
   (通过读取交易所 SL 委托距离计算 1R = SL%)

2. DD 分仓比例不按策略配置: 监控循环重建 tier allocs 时改用
   initDrawdownTiersFromResolvedRules (调用 resolveDrawdownRulesWithModes
   合并策略手动值),而非直接用 AI 原始规则的 55%/25%/100%

3. DD T1 执行后又重挂 T1:
   - 新增 detectNativeTrailingFills: 对比当前仓位量与 tier allocs 预期量,
     量减少时标记对应 tier 为 executed
   - 新增 isDrawdownTierExecuted: 在 re-arm 判断前检查 tier 是否已执行,
     已执行则不再重挂
根因: TRANSPORT_ENCRYPTION=true 但站点通过 HTTP 访问,浏览器的
crypto.subtle API 仅在安全上下文 (HTTPS/localhost) 可用,导致
加密步骤抛异常,请求从未发出。

修复:
- 前端: updateModelConfigs/createExchangeEncrypted/updateExchangeConfigsEncrypted
  增加 !window.crypto?.subtle 检查,不可用时回退到明文传输
- 后端: handleUpdateModelConfigs 改为 try-encrypted-first 模式,
  WrappedKey 为空时接受明文 JSON 而非拒绝
- 后端: RiskControlConfig 新增 entry_cooldown_minutes / max_entry_deviation_pct
- 后端: entry_cooldown 从策略配置读取冷却时间(默认90分钟)
- 后端: entry_deviation_check 从策略配置读取偏差上限(默认1.5%)
- 前端: EntryGateConfig 补全 min_reward_atr_mul / short_non_downtrend_min_confidence / squeeze_min_*
- 前端: PreEntryGateEditor 新增 Group E (置信度&方向门禁) + TP距离ATR倍数
- 前端: RiskControlEditor 新增执行约束区域 (冷却时间/入场偏差)
- 布局: 三栏改为 lg/xl 响应式断点,竖屏自动堆叠
- 紧凑化: section 间距 space-y-6→4, padding p-4→p-3
DD (Drawdown) 逻辑修复:
- 移除 clampAIDrawdownCloseRatio 对 close_ratio_pct 的篡改
- 策略配置的 close_ratio_pct 为权威值,AI 不可覆盖
- 实现累计继承: T2触发时平T1+T2仓位(65+25=90%),用T2参数
- 修复 activation price 不再用市场价反复更新(高水位由交易所跟踪)
- DD prompt 重写: 要求多TF结构位 × 悲观因子(0.70-0.85)计算 min_profit
- 禁止使用固定模板值(0.8/1.5/2.5)

AI 开仓保守性修复:
- 移除历史表现评语('需改进'/'盈利因子<1'等抑制开仓意愿)
- RR门槛从2.5降到2.0(策略配置)
- Trading Principles 改为鼓励在有效结构位果断入场
- 移除 formatter.go 的'决策参考'主观警告

基础设施:
- API超时 120s → 300s (上游 ai.ltcraft.cn 响应慢)
- Boot policy: 移除 ForceAllRunning,尊重DB is_running状态
- 修复多容器残留导致重复API调用
@MAX-LIUS
MAX-LIUS deleted the fox/project-takeover-baseline branch May 14, 2026 17:31
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.

2 participants