Skip to content

Conversation

@the-dev-z
Copy link
Collaborator

@the-dev-z the-dev-z commented Nov 7, 2025

Pull Request - Backend

🎯 問題描述

槓桿超限導致決策失敗

現象

Cycle #70: 獲取AI決策失敗:決策驗證失敗:決策 #3 驗證失敗:
杠桿必須在1-10之間(SOLUSDT,當前配置上限10倍):20

根本原因

  • config.json 配置 altcoin_leverage: 5(子帳戶限制)
  • AI 可能輸出超限槓桿(如 20x)
  • 驗證層直接拒絕 → 整個交易週期失敗

✅ 解決方案

槓桿超限自動修正 (decision/engine.go)

Before(舊邏輯)

if d.Leverage > maxLeverage {
    return fmt.Errorf("杠杆必须在1-%d之间...", maxLeverage)  // ❌ 直接拒絕
}

After(新邏輯)

if d.Leverage > maxLeverage {
    log.Printf("⚠️  [Leverage Fallback] %s 杠杆超限 (%dx > %dx),自动调整为上限值 %dx",
        d.Symbol, d.Leverage, maxLeverage, maxLeverage)
    d.Leverage = maxLeverage  // ✅ 自動修正為上限值
}

效果

  • SOLUSDT 20x → 自動修正為 5x(配置上限)
  • 決策不再失敗,交易繼續執行
  • 日誌記錄警告,便於後續調優

單元測試覆蓋 (decision/validate_test.go)

新增 TestLeverageFallback,覆蓋 4 個場景:

  • ✅ 山寨幣槓桿超限(20x → 5x 自動修正)
  • ✅ BTC 槓桿超限(20x → 10x 自動修正)
  • ✅ 槓桿在範圍內(不修正)
  • ✅ 槓桿為 0(拒絕並報錯)

🧪 測試結果

=== RUN   TestLeverageFallback
=== RUN   TestLeverageFallback/山寨币杠杆超限_自动修正为上限
⚠️  [Leverage Fallback] SOLUSDT 杠杆超限 (20x > 5x),自动调整为上限值 5x
=== RUN   TestLeverageFallback/BTC杠杆超限_自动修正为上限
⚠️  [Leverage Fallback] BTCUSDT 杠杆超限 (20x > 10x),自动调整为上限值 10x
=== RUN   TestLeverageFallback/杠杆在上限内_不修正
=== RUN   TestLeverageFallback/杠杆为0_应该报错
--- PASS: TestLeverageFallback (0.00s)
PASS
ok  	nofx/decision	0.278s

📊 修復效果對比

場景 修復前 修復後
AI 輸出 20x 槓桿 ❌ 決策失敗,交易週期浪費 ✅ 自動降為 5x,繼續執行
日誌可見性 ❌ 只看到錯誤 ✅ 警告訊息:[Leverage Fallback]
系統穩定性 ❌ 頻繁失敗 ✅ 容錯性強

📦 變更文件

  • decision/engine.go - 智能修正邏輯(+8 lines, -2 lines)
  • decision/validate_test.go - 單元測試(+100 lines, new file)

總計: +108 lines, -2 lines


🔍 技術細節

向後兼容性

  • ✅ 正常槓桿範圍不受影響
  • ✅ 現有配置無需修改
  • ✅ 只在超限時觸發 fallback

多層防禦架構

配置層(config.json)
    ↓
驗證層兜底(Fallback 修正)
    ↓
單元測試(持續驗證)

🚀 下次交易週期預期行為

Cycle #71
- AI 分析:SOLUSDT 信心度 95,建議 20x 槓桿
- ⚠️  [Leverage Fallback] SOLUSDT 杠杆超限 (20x > 5x),自动调整为上限值 5x
- ✅ 決策執行:開倉 SOLUSDT,5x 槓桿
- 📊 結果:正常交易,無失敗

📝 Note

原本 PR 包含 prompts/adaptive.txt 的修改,但該文件已在 PR #712 和後續 commit 中被重構/刪除。

本 PR 現在專注於後端槓桿驗證邏輯的改進,與 prompt 系統無關。


🤖 Generated with Claude Code

Co-Authored-By: Claude [email protected]


🎯 Type of Change | 變更類型

  • 🐛 Bug fix | 修復 Bug
  • ✨ New feature | 新功能
  • 💥 Breaking change | 破壞性變更
  • ♻️ Refactoring | 重構
  • ⚡ Performance improvement | 性能優化
  • 🔒 Security fix | 安全修復(容錯性)
  • 🔧 Build/config change | 構建/配置變更

🔗 Related Issues | 相關 Issue

  • Related to 槓桿超限導致決策失敗問題

🧪 Testing | 測試

Test Environment | 測試環境

  • OS | 操作系統: macOS / Linux
  • Go Version | Go 版本: 1.21+
  • Exchange | 交易所: Binance (Testnet)

Manual Testing | 手動測試

  • Tested locally | 本地測試通過
  • Unit tests pass | 單元測試通過 (TestLeverageFallback)
  • Verified no existing functionality broke | 確認沒有破壞現有功能
  • Tested on testnet | 測試網測試通過(交易所集成相關)

🔒 Security Considerations | 安全考慮

  • No API keys or secrets hardcoded | 沒有硬編碼 API 密鑰
  • User inputs properly validated | 用戶輸入已正確驗證
  • No SQL injection vulnerabilities | 無 SQL 注入漏洞
  • Authentication/authorization properly handled | 認證/授權正確處理
  • Sensitive data is encrypted | 敏感數據已加密
  • Enhanced error handling | 增強錯誤處理

⚡ Performance Impact | 性能影響

  • No significant performance impact | 無顯著性能影響
  • Performance improved | 性能提升
  • Performance may be impacted (explain below) | 性能可能受影響

If impacted, explain | 如果受影響,請說明:
無顯著影響。Fallback 機制僅在槓桿超限時觸發,不影響正常流程性能。


✅ Checklist | 檢查清單

Code Quality | 代碼質量

  • Code follows project style | 代碼遵循項目風格
  • Self-review completed | 已完成代碼自查
  • Comments added for complex logic | 已添加必要註釋
  • Code compiles successfully | 代碼編譯成功 (go build)
  • Ran go fmt | 已運行 go fmt

Documentation | 文檔

  • Updated relevant documentation | 已更新相關文檔
  • Added inline comments where necessary | 已添加必要的代碼註釋
  • Updated API documentation (if applicable) | 已更新 API 文檔

Git

  • Commits follow conventional format | 提交遵循 Conventional Commits 格式
  • Rebased on latest dev branch | 已 rebase 到最新 dev 分支
  • No merge conflicts | 無合併衝突

By submitting this PR, I confirm | 提交此 PR,我確認:

  • I have read the Contributing Guidelines | 已閱讀貢獻指南
  • I agree to the Code of Conduct | 同意行為準則
  • My contribution is licensed under AGPL-3.0 | 貢獻遵循 AGPL-3.0 許可證

🤖 Generated with Claude Code

Co-Authored-By: Claude [email protected]

@github-actions
Copy link

github-actions bot commented Nov 7, 2025

🤖 Advisory Check Results

These are advisory checks to help improve code quality. They won't block your PR from being merged.

📋 PR Information

Title Format: ✅ Good - Follows Conventional Commits
PR Size: 🟢 Small (127 lines: +122 -5)

🔧 Backend Checks

Go Formatting: ✅ Good
Go Vet: ✅ Good
Tests: ✅ Passed

Fix locally:

go fmt ./...      # Format code
go vet ./...      # Check for issues
go test ./...     # Run tests

⚛️ Frontend Checks

Build & Type Check: ✅ Success

Fix locally:

cd web
npm run build  # Test build (includes type checking)

📖 Resources

Questions? Feel free to ask in the comments! 🙏


These checks are advisory and won't block your PR from being merged. This comment is automatically generated from pr-checks-run.yml.

if d.Leverage > maxLeverage {
log.Printf("⚠️ [Leverage Fallback] %s 杠杆超限 (%dx > %dx),自动调整为上限值 %dx",
d.Symbol, d.Leverage, maxLeverage, maxLeverage)
d.Leverage = maxLeverage // 自动修正为上限值
Copy link
Member

Choose a reason for hiding this comment

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

Will this cause user confusion?

- 信心度 90-95 → 杠杆 2-4x,风险预算 2%
- 信心度 >95 → 杠杆 4-5x,风险预算 2.5%(谨慎)

⚠️ **实际杠杆上限由配置文件决定**(BTC/ETH 和山寨币可能不同),系统会在"硬约束"部分明确告知当前配置的上限值
Copy link
Member

Choose a reason for hiding this comment

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

I think this will be sent to AI engine but how can it understand this ?

@xqliu
Copy link
Contributor

xqliu commented Nov 8, 2025

代码审查报告 - PR #716

审查结果:✅ 通过(有建议改进)

业务层面审查

✅ 需求验证

  • 需求明确:解决 AI 输出超限杠杆导致决策失败的问题
  • 需求合理:fallback 机制比直接拒绝更友好,提高系统容错性
  • 业务逻辑正确:自动修正为配置上限值符合预期

✅ 功能完整性

  • 杠杆超限自动修正
  • Prompt 指导更新(对齐配置)
  • 盈亏计算说明澄清
  • 单元测试覆盖(4个场景)

✅ Edge Case 处理

  • 杠杆 <= 0 仍然报错(符合预期)
  • BTC/ETH 和山寨币分别处理
  • 正常范围内的杠杆不受影响

技术层面审查

✅ 架构合理性

  • 多层防御:Prompt 指导 → 验证层修正 → 单元测试
  • 职责清晰:验证逻辑独立,易于维护
  • 向后兼容:现有配置无需修改

✅ KISS 原则

  • 修改简洁明了(仅修改验证逻辑)
  • 不引入额外依赖
  • 日志清晰([Leverage Fallback] 前缀)

✅ 测试完备性

  • 单元测试覆盖 4 个关键场景
  • 测试代码清晰,易于理解
  • 测试通过 (PASS)

🟡 改进建议(非 BLOCKING)

建议1:记录 fallback 到决策日志

当前:只记录到标准日志 (log.Printf)
建议:也记录到决策日志,便于后续分析

// decision/engine.go
if d.Leverage > maxLeverage {
    originalLeverage := d.Leverage
    d.Leverage = maxLeverage
    
    log.Printf("⚠️  [Leverage Fallback] %s 杠杆超限 (%dx > %dx),自动调整为上限值 %dx",
        d.Symbol, originalLeverage, maxLeverage, maxLeverage)
    
    // 建议:记录到决策日志
    // d.Warnings = append(d.Warnings, fmt.Sprintf(
    //     "杠杆超限(%dx -> %dx)", originalLeverage, maxLeverage))
}

理由

  • 便于分析 AI 输出杠杆的分布
  • 可以统计 fallback 触发频率
  • 帮助优化 prompt 减少超限次数

建议2:添加指标监控

// 建议添加 fallback 计数器
var (
    leverageFallbackCounter = promauto.NewCounterVec(
        prometheus.CounterOpts{
            Name: "leverage_fallback_total",
            Help: "Number of leverage fallback events",
        },
        []string{"symbol", "original_leverage"},
    )
)

// 在 fallback 时增加计数
leverageFallbackCounter.WithLabelValues(d.Symbol, fmt.Sprintf("%d", originalLeverage)).Inc()

理由

  • 监控 fallback 频率,评估 AI 学习效果
  • 如果频率过高,说明 prompt 需要进一步优化
  • 便于运维告警(如果突然大量 fallback)

建议3:考虑渐进式修正

当前:直接修正为上限值
可选方案:修正为上限值的 80%(留一点余地)

// 可选:修正为上限的 80%(更保守)
d.Leverage = int(float64(maxLeverage) * 0.8)
if d.Leverage < 1 {
    d.Leverage = maxLeverage // 避免过小
}

权衡

  • 优点:更保守,降低风险
  • 缺点:可能与 AI 意图偏离较多
  • 建议:先使用当前方案(修正为上限),后续根据实际效果调整

建议4:Prompt 中添加示例

当前:只有文字说明
建议:添加具体示例

⚠️ **实际杠杆上限由配置文件决定**(BTC/ETH 和山寨币可能不同),系统会在"硬约束"部分明确告知当前配置的上限值

**示例**- 配置上限 5x(山寨币):即使信心度 >95,最高也只能使用 5x 杠杆
- 配置上限 10x(BTC/ETH):信心度 >95 时,可使用 8-10x 杠杆
- ⚠️ 如果输出的杠杆超过配置上限,系统会自动修正为上限值(并记录警告日志)

安全审查(Web3 交易系统)

✅ 资金保护

  • 杠杆上限强制执行(即使 AI 输出错误也不会超限)
  • Prompt 澄清盈亏计算(避免 AI 低估风险)
  • 杠杆 <= 0 拒绝(防止无效交易)

✅ 限额控制

  • 杠杆上限由配置文件控制
  • BTC/ETH 和山寨币分别限制
  • 仓位大小验证仍然存在

⚠️ 建议增强(可选)

建议:添加杠杆修正次数限制

  • 如果同一个 symbol 连续 N 次 fallback,可能说明 AI 模型有问题
  • 可以触发告警或暂停该 symbol 的交易
// 伪代码
fallbackCount[symbol]++
if fallbackCount[symbol] > 5 {
    log.Printf("⚠️  [Critical] %s 连续 5 次杠杆 fallback,可能需要检查 AI 模型", symbol)
    // 可选:暂停该 symbol 的交易
}

E2E 验证报告

✅ 测试场景1:杠杆超限(山寨币)

输入SOLUSDT, 杠杆 20x, 配置上限 5x
预期自动修正为 5x, 日志警告, 决策继续
实际:✅ 通过单元测试覆盖

✅ 测试场景2:杠杆超限(BTC)

输入BTCUSDT, 杠杆 20x, 配置上限 10x
预期自动修正为 10x, 日志警告, 决策继续
实际:✅ 通过单元测试覆盖

✅ 测试场景3:杠杆正常

输入ETHUSDT, 杠杆 5x, 配置上限 10x
预期不修正, 无警告, 决策继续
实际:✅ 通过单元测试覆盖

✅ 测试场景4:杠杆无效

输入SOLUSDT, 杠杆 0x, 配置上限 5x
预期拒绝决策, 返回错误
实际:✅ 通过单元测试覆盖

⚠️ 建议补充集成测试

当前只有单元测试,建议补充集成测试:

// 测试完整流程:AI 输出 -> 验证 -> 修正 -> 记录日志
func TestLeverageFallback_Integration(t *testing.T) {
    // 1. 模拟 AI 输出 20x 杠杆的决策
    // 2. 调用 validateDecision
    // 3. 验证决策被修正为 5x
    // 4. 验证日志包含 "[Leverage Fallback]"
    // 5. 验证决策可以正常执行(不报错)
}

代码质量审查

✅ 代码风格

  • 符合 Go 代码规范
  • 注释清晰(// ✅ Fallback 机制
  • 命名合理(maxLeverage, wantLeverage

✅ 错误处理

  • 杠杆 <= 0 明确报错
  • Fallback 日志清晰

✅ 性能影响

  • 无额外性能开销(只是简单的比较和赋值)

文档完整性

✅ PR 描述

  • 问题描述清晰(带示例)
  • 解决方案明确(Before/After 对比)
  • 测试结果完整(单元测试输出)
  • 修复效果对比表格
  • 技术细节说明

✅ 代码注释

  • 关键逻辑有注释(Fallback 机制)
  • Prompt 更新有说明

✅ 测试文档

  • 单元测试代码清晰
  • 测试用例命名规范

总结

这是一个高质量的 PR

优点

  1. ✅ 问题识别准确(AI 杠杆超限导致决策失败)
  2. ✅ 解决方案合理(Fallback 修正而不是拒绝)
  3. ✅ 测试覆盖完整(4个场景)
  4. ✅ 文档详细(PR 描述 + 代码注释)
  5. ✅ 向后兼容(现有配置无需修改)
  6. ✅ 性能无影响(简单的比较和赋值)

改进空间(非 BLOCKING)

  1. ⚠️ 考虑记录 fallback 到决策日志(便于后续分析)
  2. ⚠️ 考虑添加指标监控(评估 AI 学习效果)
  3. ⚠️ 考虑添加集成测试(验证完整流程)
  4. ⚠️ Prompt 中添加具体示例(帮助 AI 理解)

建议

  • 立即合并:当前实现已经解决了关键问题
  • 后续优化:根据实际运行效果,考虑添加监控和告警

审查结论:✅ 通过,建议合并

@github-actions
Copy link

github-actions bot commented Nov 9, 2025

🤖 Advisory Check Results

These are advisory checks to help improve code quality. They won't block your PR from being merged.

📋 PR Information

Title Format: ✅ Good - Follows Conventional Commits
PR Size: 🟢 Small (110 lines: +108 -2)

🔧 Backend Checks

Go Formatting: ⚠️ Needs formatting

Files needing formatting
auth/auth.go
bootstrap/bootstrap.go
config/database.go
crypto/crypto.go
main.go
trader/auto_trader.go

Go Vet: ✅ Good
Tests: ✅ Passed

Fix locally:

go fmt ./...      # Format code
go vet ./...      # Check for issues
go test ./...     # Run tests

⚛️ Frontend Checks

Build & Type Check: ✅ Success

Fix locally:

cd web
npm run build  # Test build (includes type checking)

📖 Resources

Questions? Feel free to ask in the comments! 🙏


These checks are advisory and won't block your PR from being merged. This comment is automatically generated from pr-checks-run.yml.

@the-dev-z
Copy link
Collaborator Author

此 PR 已獲批准 ✅

修復內容:

  • 新增槓桿自動回退機制
  • 解決提示詞檔案衝突(已採用上游刪除)

可以合併了嗎?謝謝!🙏

@the-dev-z the-dev-z force-pushed the fix/leverage-fallback-and-pnl-guidance branch from 3b27133 to 00721a3 Compare November 9, 2025 02:23
@github-actions
Copy link

github-actions bot commented Nov 9, 2025

🤖 Advisory Check Results

These are advisory checks to help improve code quality. They won't block your PR from being merged.

📋 PR Information

Title Format: ✅ Good - Follows Conventional Commits
PR Size: 🟢 Small (110 lines: +108 -2)

🔧 Backend Checks

Go Formatting: ⚠️ Needs formatting

Files needing formatting
auth/auth.go
bootstrap/bootstrap.go
config/database.go
config/database_test.go
crypto/crypto.go
main.go
trader/auto_trader.go

Go Vet: ✅ Good
Tests: ✅ Passed

Fix locally:

go fmt ./...      # Format code
go vet ./...      # Check for issues
go test ./...     # Run tests

⚛️ Frontend Checks

Build & Type Check: ✅ Success

Fix locally:

cd web
npm run build  # Test build (includes type checking)

📖 Resources

Questions? Feel free to ask in the comments! 🙏


These checks are advisory and won't block your PR from being merged. This comment is automatically generated from pr-checks-run.yml.

the-dev-z and others added 2 commits November 11, 2025 00:59
1. AI 決策輸出超限槓桿時(如 20x),驗證直接拒絕導致整個交易週期失敗
2. Prompt 未明確說明盈虧百分比已包含槓桿效應,導致 AI 思維鏈中誤用價格變動%

- **Before**: 超限直接報錯 → 決策失敗
- **After**: 自動降級為配置上限 → 決策繼續執行
- **效果**: SOLUSDT 20x → 自動修正為 5x(配置上限)

- 明確告知 AI:系統提供的「盈虧%」已包含槓桿效應
- 公式: 盈虧% = (未實現盈虧 / 保證金) × 100
- 示例: 5x 槓桿,價格漲 2% = 實際盈利 10%

- 測試山寨幣超限修正(20x → 5x)
- 測試 BTC/ETH 超限修正(20x → 10x)
- 測試正常範圍不修正
- 測試無效槓桿拒絕

```
PASS: TestLeverageFallback/山寨币杠杆超限_自动修正为上限
PASS: TestLeverageFallback/BTC杠杆超限_自动修正为上限
PASS: TestLeverageFallback/杠杆在上限内_不修正
PASS: TestLeverageFallback/杠杆为0_应该报错
```

- ✅ 向後兼容:正常槓桿範圍不受影響
- ✅ 容錯性增強:AI 輸出超限時系統自動修正
- ✅ 決策質量提升:AI 對槓桿收益有正確認知

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
@the-dev-z the-dev-z force-pushed the fix/leverage-fallback-and-pnl-guidance branch from 00721a3 to aaef135 Compare November 10, 2025 16:59
@github-actions
Copy link

🤖 Advisory Check Results

These are advisory checks to help improve code quality. They won't block your PR from being merged.

📋 PR Information

Title Format: ✅ Good - Follows Conventional Commits
PR Size: 🟢 Small (113 lines: +110 -3)

🔧 Backend Checks

Go Formatting: ✅ Good
Go Vet: ✅ Good
Tests: ✅ Passed

Fix locally:

go fmt ./...      # Format code
go vet ./...      # Check for issues
go test ./...     # Run tests

⚛️ Frontend Checks

Build & Type Check: ✅ Success

Fix locally:

cd web
npm run build  # Test build (includes type checking)

📖 Resources

Questions? Feel free to ask in the comments! 🙏


These checks are advisory and won't block your PR from being merged. This comment is automatically generated from pr-checks-run.yml.

@hzb1115 hzb1115 merged commit 6217318 into NoFxAiOS:dev Nov 11, 2025
16 checks passed
sparrow211 pushed a commit to sparrow211/nofx that referenced this pull request Nov 11, 2025
* fix(decision): 添加槓桿超限 fallback 機制並澄清盈虧計算說明

1. AI 決策輸出超限槓桿時(如 20x),驗證直接拒絕導致整個交易週期失敗
2. Prompt 未明確說明盈虧百分比已包含槓桿效應,導致 AI 思維鏈中誤用價格變動%

- **Before**: 超限直接報錯 → 決策失敗
- **After**: 自動降級為配置上限 → 決策繼續執行
- **效果**: SOLUSDT 20x → 自動修正為 5x(配置上限)

- 明確告知 AI:系統提供的「盈虧%」已包含槓桿效應
- 公式: 盈虧% = (未實現盈虧 / 保證金) × 100
- 示例: 5x 槓桿,價格漲 2% = 實際盈利 10%

- 測試山寨幣超限修正(20x → 5x)
- 測試 BTC/ETH 超限修正(20x → 10x)
- 測試正常範圍不修正
- 測試無效槓桿拒絕

```
PASS: TestLeverageFallback/山寨币杠杆超限_自动修正为上限
PASS: TestLeverageFallback/BTC杠杆超限_自动修正为上限
PASS: TestLeverageFallback/杠杆在上限内_不修正
PASS: TestLeverageFallback/杠杆为0_应该报错
```

- ✅ 向後兼容:正常槓桿範圍不受影響
- ✅ 容錯性增強:AI 輸出超限時系統自動修正
- ✅ 決策質量提升:AI 對槓桿收益有正確認知

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* style: apply go fmt after rebase

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

---------

Co-authored-by: ZhouYongyou <[email protected]>
Co-authored-by: Claude <[email protected]>
@the-dev-z the-dev-z deleted the fix/leverage-fallback-and-pnl-guidance branch November 12, 2025 08:37
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.

3 participants