Skip to content

Conversation

@Im-Sue
Copy link
Contributor

@Im-Sue Im-Sue commented Nov 5, 2025

  • 新增 PositionDetail 结构体存储持仓快照
  • 在 AutoTrader 中维护 previousPositions 和 currentCyclePositions
  • 每个交易周期对比持仓快照,检测消失的持仓
  • 将检测到的手动平仓操作记录到决策日志
  • 使用标记价格(MarkPrice)作为平仓价格估算

Author: sue

Pull Request | PR 提交

💡 提示 Tip: 推荐 PR 标题格式 Recommended PR title format: type(scope): description
例如 Examples: feat(trader): add new strategy | fix(api): resolve auth issue
详情 Details: PR Title Guide


📝 Description | 描述

实现了手动平仓历史记录检测功能,通过对比每个交易周期的持仓快照,自动检测并记录手动平仓操作


🎯 Type of Change | 变更类型

  • [√ ] 🐛 Bug fix | 修复 Bug(不影响现有功能的修复)
  • [√ ] ✨ New feature | 新功能(不影响现有功能的新增)
  • 💥 Breaking change | 破坏性变更(会导致现有功能无法正常工作的修复或功能)
  • 📝 Documentation update | 文档更新
  • 🎨 Code style update | 代码样式更新(格式化、重命名等)
  • ♻️ Refactoring | 重构(无功能变更)
  • ⚡ Performance improvement | 性能优化
  • ✅ Test update | 测试更新
  • 🔧 Build/config change | 构建/配置变更
  • 🔒 Security fix | 安全修复

🔗 Related Issues | 相关 Issue


📋 Changes Made | 具体变更

English:

  • Change 1
  • Change 2
  • Change 3

中文:

  • 变更 1
  • 变更 2
  • 变更 3

🧪 Testing | 测试

Manual Testing | 手动测试

  • [√ ] Tested locally | 本地测试通过
  • Tested on testnet | 测试网测试通过(交易所集成相关)
  • Tested with different configurations | 测试了不同配置
  • Verified no existing functionality broke | 确认没有破坏现有功能

Test Environment | 测试环境

  • OS | 操作系统: [e.g. macOS, Ubuntu, Windows]
  • Go Version | Go 版本: [e.g. 1.21.5]
  • Node Version | Node 版本: [e.g. 18.x] (if applicable | 如适用)
  • Exchange | 交易所: [if applicable | 如适用]

Test Results | 测试结果

Test output here | 测试输出

📸 Screenshots / Demo | 截图/演示

image

Before | 变更前:

After | 变更后:


✅ Checklist | 检查清单

Code Quality | 代码质量

  • [√ ] My code follows the project's code style | 我的代码遵循项目代码风格 (Contributing Guide)
  • I have performed a self-review of my code | 我已进行代码自查
  • I have commented my code, particularly in hard-to-understand areas | 我已添加代码注释,特别是难以理解的部分
  • My changes generate no new warnings or errors | 我的变更没有产生新的警告或错误
  • Code compiles successfully | 代码编译成功 (go build / npm run build)
  • I have run go fmt (for Go code) | 我已运行 go fmt(Go 代码)
  • I have run npm run lint (for frontend code) | 我已运行 npm run lint(前端代码)

Testing | 测试

  • [ √] I have added tests that prove my fix is effective or that my feature works | 我已添加证明修复有效或功能正常的测试
  • New and existing unit tests pass locally | 新旧单元测试在本地通过
  • I have tested on testnet (for trading/exchange changes) | 我已在测试网测试(交易/交易所变更)
  • Integration tests pass | 集成测试通过

Documentation | 文档

  • I have updated the documentation accordingly | 我已相应更新文档
  • I have updated the README if needed | 我已更新 README(如需要)
  • I have added inline code comments where necessary | 我已在必要处添加代码注释
  • I have updated type definitions (for TypeScript changes) | 我已更新类型定义(TypeScript 变更)
  • I have updated API documentation (if applicable) | 我已更新 API 文档(如适用)

Git

  • My commits follow the conventional commits format | 我的提交遵循 Conventional Commits 格式 (feat:, fix:, etc.)
  • I have rebased my branch on the latest dev branch | 我已将分支 rebase 到最新的 dev 分支
  • There are no merge conflicts | 没有合并冲突
  • Commit messages are clear and descriptive | 提交信息清晰明确

🔒 Security Considerations | 安全考虑

  • No API keys or secrets are hardcoded | 没有硬编码 API 密钥或密钥
  • User inputs are properly validated | 用户输入已正确验证
  • No SQL injection vulnerabilities introduced | 未引入 SQL 注入漏洞
  • No XSS vulnerabilities introduced | 未引入 XSS 漏洞
  • Authentication/authorization properly handled | 认证/授权已正确处理
  • Sensitive data is encrypted | 敏感数据已加密
  • N/A (not security-related) | 不适用(非安全相关)

⚡ Performance Impact | 性能影响

  • No significant performance impact | 无显著性能影响
  • Performance improved | 性能提升
  • Performance may be impacted (explain below) | 性能可能受影响(请在下方说明)

English:

中文:


🌐 Internationalization | 国际化

  • All user-facing text supports i18n | 所有面向用户的文本支持国际化
  • Both English and Chinese versions provided | 提供了中英文版本
  • N/A | 不适用

📚 Additional Notes | 补充说明

English:

中文:


💰 For Bounty Claims | 赏金申请

  • This PR is for bounty issue # | 此 PR 用于赏金 issue #
  • All acceptance criteria from the bounty issue are met | 满足赏金 issue 的所有验收标准
  • I have included a demo video/screenshots | 我已包含演示视频/截图
  • I am ready for payment upon merge | 我准备好在合并后接收付款

Payment Details | 付款详情:


🙏 Reviewer Notes | 审查者注意事项

English:

中文:


📋 PR Size Estimate | PR 大小估计

  • 🟢 Small (< 100 lines) | 小(< 100 行)
  • 🟡 Medium (100-500 lines) | 中(100-500 行)
  • 🔴 Large (> 500 lines) | 大(> 500 行)

🎯 Review Focus Areas | 审查重点

Please pay special attention to:
请特别注意:

  • Logic changes | 逻辑变更
  • Security implications | 安全影响
  • Performance optimization | 性能优化
  • API changes | API 变更
  • Database schema changes | 数据库架构变更
  • UI/UX changes | UI/UX 变更

By submitting this PR, I confirm that:
提交此 PR,我确认:

  • I have read the Contributing Guidelines | 我已阅读贡献指南
  • I agree to the Code of Conduct | 我同意行为准则
  • My contribution is licensed under the AGPL-3.0 License | 我的贡献遵循 AGPL-3.0 许可证
  • I understand this is a voluntary contribution | 我理解这是自愿贡献
  • I have the right to submit this code | 我有权提交此代码

- 新增 PositionDetail 结构体存储持仓快照
- 在 AutoTrader 中维护 previousPositions 和 currentCyclePositions
- 每个交易周期对比持仓快照,检测消失的持仓
- 将检测到的手动平仓操作记录到决策日志
- 使用标记价格(MarkPrice)作为平仓价格估算

Author: sue
@github-actions
Copy link

github-actions bot commented Nov 5, 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 (128 lines: +125 -3)

🔧 Backend Checks

Go Formatting: ⚠️ Needs formatting

Files needing formatting
decision/engine.go
logger/telegram_sender.go
mcp/client.go
trader/aster_trader.go
trader/hyperliquid_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.

@tinkle-community
Copy link
Collaborator

这个平台用户多,性能会受影响不?

@xqliu
Copy link
Contributor

xqliu commented Nov 8, 2025

代码审查报告 - PR #521

📋 基本信息


⚠️ BLOCKING 问题

1. 合并冲突

当前状态: CONFLICTING

要求: 必须先rebase到最新的dev分支,解决冲突后才能审查

git fetch origin
git rebase origin/dev
# 解决冲突
git add .
git rebase --continue
git push --force-with-lease

1️⃣ 业务逻辑审查

✅ 问题定义

需求: 检测用户在交易所手动平仓的操作,并记录到决策日志中

业务价值:

  • 完整性:决策日志包含所有平仓操作(AI + 手动)
  • 可追溯:用户可以看到自己的手动干预历史
  • 数据完整:统计盈亏时考虑手动平仓

✅ 实现方案

检测机制: 持仓快照对比

1. previousPositions    // 上一周期持仓快照
2. currentCyclePositions // 当前周期持仓快照
3. 对比发现消失的持仓判定为手动平仓

记录方式:

  • 使用MarkPrice作为平仓价格(与实际成交价偏差<1%)
  • 记录未实现盈亏
  • 标记为"手动平仓"

2️⃣ 技术实现审查

✅ 优点

  1. 设计简洁

    • 使用快照对比,不依赖交易所API
    • 数据结构清晰(PositionDetail
  2. 性能良好

    • O(n)时间复杂度(n=持仓数量)
    • 内存占用小(只存快照,不存历史)
  3. 代码质量

    • 日志详细(便于排查)
    • 注释清晰

⚠️ 潜在问题

问题1: 误判风险 - 部分平仓

场景: 用户手动部分平仓(如50% → 25%)

当前逻辑:

if _, exists := at.currentCyclePositions[posKey]; !exists {
    // 只检测完全消失的持仓
}

问题: 部分平仓不会被检测到

建议: 添加数量变化检测

if currentPos, exists := at.currentCyclePositions[posKey]; exists {
    // 检测数量减少
    if currentPos.Quantity < oldPos.Quantity {
        // 记录部分平仓: oldPos.Quantity - currentPos.Quantity
    }
} else {
    // 完全平仓(现有逻辑)
}

问题2: 误判风险 - 爆仓/强平

场景: 持仓被强制平仓(liquidation)

当前逻辑: 强平也会被记录为"手动平仓"

影响:

  • 日志信息不准确
  • 用户可能误解自己的操作

建议: 区分强平和手动平仓

// 检查是否接近强平价
isLiquidation := false
if oldPos.Side == "long" && oldPos.MarkPrice <= oldPos.LiquidationPrice*1.01 {
    isLiquidation = true
} else if oldPos.Side == "short" && oldPos.MarkPrice >= oldPos.LiquidationPrice*0.99 {
    isLiquidation = true
}

errorMsg := "手动平仓"
if isLiquidation {
    errorMsg = "强制平仓(爆仓)"
}

问题3: 价格准确性

当前: 使用MarkPrice作为平仓价格

问题:

  • MarkPrice是估算,可能与实际成交价有偏差
  • 对于大额平仓,偏差可能较大

建议:

  • 在注释中明确说明这是估算价格
  • 如果可以,从交易所API获取实际成交记录(更准确,但增加复杂度)

问题4: 周期间隙问题

场景: 两个周期之间的持仓变化

周期1: 持仓A存在
[30秒间隙 - 用户手动平仓A,开仓B]
周期2: 持仓B存在

当前逻辑: ✅ 能检测到A消失(手动平仓)

但是: 新开仓B不会被记录(因为没有AI决策)

建议: 文档中说明这个限制


3️⃣ E2E场景验证

✅ 正常场景

场景1: 用户手动完全平仓

周期1: BTC-USDT long, 数量0.1
[用户手动平仓]
周期2: 无持仓

预期: ✅ 检测到手动平仓,记录到日志


场景2: AI平仓

周期1: BTC-USDT long, 数量0.1
[AI决策平仓]
周期2: 无持仓

预期: ✅ 不会重复记录(AI决策已经记录)

验证:

// 周期开始时更新previousPositions
at.previousPositions = at.currentCyclePositions

// AI决策平仓后,currentCyclePositions会更新
// detectManualCloses()时对比的是周期开始的快照

问题: ❌ 可能会误判!

分析:

1. 周期开始: previousPositions = {BTC: 0.1}
2. 获取当前持仓: currentCyclePositions = {BTC: 0.1}
3. 检测手动平仓: 无(因为持仓还在)✅
4. AI决策平仓BTC
5. 执行平仓
6. 周期结束更新快照: previousPositions = {BTC: 0.1}

下一周期:
1. 获取当前持仓: currentCyclePositions = {} (已平仓)
2. 检测手动平仓: ❌ 误判为手动平仓!

根本原因: currentCyclePositions在周期开始时更新,AI平仓后持仓已消失,下一周期会误判

修复方案: 在AI执行平仓后,同步更新currentCyclePositions

// 在executeTrades()成功平仓后
if action.Action == "close_long" || action.Action == "close_short" {
    posKey := fmt.Sprintf("%s_%s", action.Symbol, side)
    delete(at.currentCyclePositions, posKey)
}

⚠️ 边界场景

场景3: 部分平仓

周期1: BTC-USDT long, 数量0.1
[用户手动平仓50%]
周期2: BTC-USDT long, 数量0.05

预期: 应该检测到部分平仓0.05
实际: ❌ 不会检测到(只检测完全消失)


场景4: 强制平仓

周期1: BTC-USDT long, 数量0.1, 强平价=$60000
[价格跌至$60000,被强平]
周期2: 无持仓

预期: 应该标记为"强平"
实际: ⚠️ 标记为"手动平仓"(不准确)


场景5: 手动开仓

周期1: 无持仓
[用户手动开仓BTC]
周期2: BTC-USDT long, 数量0.1

预期: 不应该有误报
实际: ✅ 不会检测(只检测消失的持仓)


4️⃣ 安全性审查

✅ 无安全问题

  • 不涉及外部输入
  • 不涉及权限控制
  • 只是内部状态对比

5️⃣ 代码质量审查

✅ 优点

  • 结构清晰
  • 命名规范
  • 日志详细

⚠️ 改进建议

  1. 添加单元测试
func TestDetectManualCloses(t *testing.T) {
    // 测试完全平仓
    // 测试部分平仓(如果支持)
    // 测试强平场景
    // 测试无变化场景
}
  1. 添加配置开关
// 允许用户禁用手动平仓检测
EnableManualCloseDetection bool
  1. 添加统计信息
// 在统计API中显示手动平仓次数
ManualCloseCount int

6️⃣ 审查总结

⚠️ 审查结果: 需要修复后通过

维度 评分 说明
业务价值 ⭐⭐⭐⭐⭐ 重要功能,提升数据完整性
实现思路 ⭐⭐⭐⭐ 快照对比方案简洁有效
代码质量 ⭐⭐⭐⭐ 清晰规范
边界处理 ⭐⭐⭐ 缺少部分平仓和强平区分
测试覆盖 ⭐⭐ 缺少单元测试

🔧 必须修复(BLOCKING)

  1. 解决合并冲突 - rebase到最新dev分支

  2. 修复AI平仓误判问题 - 在executeTrades()后同步更新currentCyclePositions

    // executeTrades()中,成功平仓后
    if success && (action == "close_long" || action == "close_short") {
        posKey := fmt.Sprintf("%s_%s", symbol, side)
        delete(at.currentCyclePositions, posKey)
    }

💡 强烈建议

  1. 区分强平和手动平仓

    • 检查MarkPrice是否接近LiquidationPrice
    • 使用不同的Error消息标记
  2. 支持部分平仓检测

    • 对比数量变化
    • 记录减少的数量
  3. 添加单元测试

    • 测试完全平仓、部分平仓、强平等场景

📌 可选优化

  1. 添加配置开关
  2. 在统计API中显示手动平仓统计
  3. 考虑从交易所API获取实际成交记录(更准确)

🎯 下一步

  1. 先rebase解决冲突
  2. ⚠️ 修复AI平仓误判问题(BLOCKING)
  3. 💡 考虑添加强平区分和部分平仓支持
  4. 🧪 添加单元测试
  5. 📝 更新后re-request review

总评: 这是一个有价值的功能,实现思路清晰,但存在AI平仓误判的严重bug。修复后可以合并。


审查时间: 2025-11-08
审查者: Claude AI Code Reviewer

@hzb1115 hzb1115 closed this Nov 11, 2025
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.

[BUG] 手动平仓的交易也无法记录到历史成交

4 participants