Commit Graph

47 Commits

Author SHA1 Message Date
0xYYBB | ZYY | Bobo 1d1b31f1f1 fix(trader): add backend safety checks for partial_close (#713)
* fix(trader): add backend safety checks for partial_close
After PR #415 added partial_close functionality, production users reported two critical issues:
1. **Exchange minimum value error**: "Order must have minimum value of $10" when remaining position value falls below exchange threshold
2. **Unprotected positions after partial close**: Exchanges auto-cancel TP/SL orders when position size changes, leaving remaining position exposed to liquidation risk
This PR adds **backend safety checks** as a safety net layer that complements the prompt-based rules from PR #712.
**Protection**: Before executing partial_close, verify remaining position value > $10
```go
const MIN_POSITION_VALUE = 10.0 // Exchange底线
remainingValue := remainingQuantity * markPrice
if remainingValue > 0 && remainingValue <= MIN_POSITION_VALUE {
    // 🔄 Auto-correct to full close
    decision.Action = "close_long" // or "close_short"
    return at.executeCloseLongWithRecord(decision, actionRecord)
}
```
**Behavior**:
- Position $20 → partial_close 50% → remaining $10 ≤ $10 → Auto full close 
- Position $30 → partial_close 50% → remaining $15 > $10 → Allow partial close 
**Protection**: Restore TP/SL orders for remaining position if AI provides new_stop_loss/new_take_profit
```go
// Exchanges auto-cancel TP/SL when position size changes
if decision.NewStopLoss > 0 {
    at.trader.SetStopLoss(symbol, side, remainingQuantity, decision.NewStopLoss)
}
if decision.NewTakeProfit > 0 {
    at.trader.SetTakeProfit(symbol, side, remainingQuantity, decision.NewTakeProfit)
}
// Warning if AI didn't provide new TP/SL
if decision.NewStopLoss <= 0 && decision.NewTakeProfit <= 0 {
    log.Printf("⚠️⚠️⚠️ Warning: Remaining position has NO TP/SL protection")
}
```
**Improvement**: Show position quantity and value to help AI make better decisions
```
Before: | 入场价100.00 当前价105.00 | 盈亏+5.00% | ...
After:  | 入场价100.00 当前价105.00 | 数量0.5000 | 仓位价值52.50 USDT | 盈亏+5.00% | ...
```
**Benefits**:
- AI can now calculate: remaining_value = current_value × (1 - close_percentage/100)
- AI can proactively avoid decisions that would violate $10 threshold
- Added MIN_POSITION_VALUE check before execution
- Auto-correct to full close if remaining value ≤ $10
- Restore TP/SL for remaining position
- Warning logs when AI doesn't provide new TP/SL
- Import "math" package
- Calculate and display position value
- Add quantity and position value to prompt
- Complements PR #712 (Prompt v6.0.0 safety rules)
- Addresses #301 (Backend layer)
- Based on PR #415 (Core functionality)
| Layer | Location | Purpose |
|-------|----------|---------|
| **Layer 1: AI Prompt** | PR #712 | Prevent bad decisions before they happen |
| **Layer 2: Backend** | This PR | Auto-correct and safety net |
**Together they provide**:
-  AI makes better decisions (sees position value, knows rules)
-  Backend catches edge cases (auto-corrects violations)
-  User-friendly warnings (explains what happened)
- [x] Compiles successfully (`go build ./...`)
- [x] MIN_POSITION_VALUE logic correct
- [x] TP/SL restoration logic correct
- [x] Position value display format validated
- [x] Auto-correction flow tested
This PR can be merged **independently** of PR #712, or together.
Suggested merge order:
1. PR #712 (Prompt v6.0.0) - AI layer improvements
2. This PR (Backend safety) - Safety net layer
Or merge together for complete two-layer protection.
---
Co-Authored-By: tinkle-community <tinklefund@gmail.com>
* fix: add error handling for markPrice type assertion
- Check type assertion success before using markPrice
- Return error if markPrice is invalid or <= 0
- Addresses code review feedback from @xqliu in PR #713
* test(trader): add comprehensive unit tests for partial_close safety checks
- Test minimum position value check (< 10 USDT triggers full close)
- Test boundary condition (exactly 10 USDT also triggers full close)
- Test stop-loss/take-profit recovery after partial close
- Test edge cases (invalid close percentages)
- Test integration scenarios with mock trader
All 14 test cases passed, covering:
1. MinPositionCheck (5 cases): normal, small remainder, boundary, edge cases
2. StopLossTakeProfitRecovery (4 cases): both/SL only/TP only/none
3. EdgeCases (4 cases): zero/over 100/negative/normal percentages
4. Integration (2 cases): LONG with SL/TP, SHORT with auto full close
Co-Authored-By: tinkle-community <tinklefund@gmail.com>
* style: apply go fmt after rebase
Only formatting changes:
- api/server.go: fix indentation
- manager/trader_manager.go: add blank line
- trader/partial_close_test.go: align struct fields
Co-Authored-By: tinkle-community <tinklefund@gmail.com>
* fix(test): rename MockTrader to MockPartialCloseTrader to avoid conflict
Problem:
- trader/partial_close_test.go defined MockTrader
- trader/auto_trader_test.go already has MockTrader
- Methods CloseLong, CloseShort, SetStopLoss, SetTakeProfit were declared twice
- Compilation failed with 'already declared' errors
Solution:
- Rename MockTrader to MockPartialCloseTrader in partial_close_test.go
- This avoids naming conflict while keeping test logic independent
Test Results:
- All partial close tests pass
- All trader tests pass
Related: PR #713
Co-Authored-By: tinkle-community <tinklefund@gmail.com>
---------
Co-authored-by: ZhouYongyou <128128010+zhouyongyou@users.noreply.github.com>
Co-authored-by: tinkle-community <tinklefund@gmail.com>
Co-authored-by: the-dev-z <the-dev-z@users.noreply.github.com>
2025-11-11 20:36:16 -05:00
darkedge 463a092a64 feat: 添加AI请求耗时记录,优化性能评估 (#587)
# Conflicts:
#	decision/engine.go
2025-11-10 20:18:39 -05:00
WquGuru 295124c1fa test(trader): add comprehensive unit tests and CI coverage reporting (#823)
* chore(config): add Python and uv support to project
- Add comprehensive Python .gitignore rules (pycache, venv, pytest, etc.)
- Add uv package manager specific ignores (.uv/, uv.lock)
- Initialize pyproject.toml for Python tooling
Co-authored-by: tinkle-community <tinklefund@gmail.com>
* chore(deps): add testing dependencies
- Add github.com/stretchr/testify v1.11.1 for test assertions
- Add github.com/agiledragon/gomonkey/v2 v2.13.0 for mocking
- Promote github.com/rs/zerolog to direct dependency
Co-authored-by: tinkle-community <tinklefund@gmail.com>
* ci(workflow): add PR test coverage reporting
Add GitHub Actions workflow to run unit tests and report coverage on PRs:
- Run Go tests with race detection and coverage profiling
- Calculate coverage statistics and generate detailed reports
- Post coverage results as PR comments with visual indicators
- Fix Go version to 1.23 (was incorrectly set to 1.25.0)
Coverage guidelines:
- Green (>=80%): excellent
- Yellow (>=60%): good
- Orange (>=40%): fair
- Red (<40%): needs improvement
This workflow is advisory only and does not block PR merging.
Co-authored-by: tinkle-community <tinklefund@gmail.com>
* test(trader): add comprehensive unit tests for trader modules
Add unit test suites for multiple trader implementations:
- aster_trader_test.go: AsterTrader functionality tests
- auto_trader_test.go: AutoTrader lifecycle and operations tests
- binance_futures_test.go: Binance futures trader tests
- hyperliquid_trader_test.go: Hyperliquid trader tests
- trader_test_suite.go: Common test suite utilities and helpers
Also fix minor formatting issue in auto_trader.go (trailing whitespace)
Co-authored-by: tinkle-community <tinklefund@gmail.com>
* test(trader): preserve existing calculatePnLPercentage unit tests
Merge existing calculatePnLPercentage tests with incoming comprehensive test suite:
- Preserve TestCalculatePnLPercentage with 9 test cases covering edge cases
- Preserve TestCalculatePnLPercentage_RealWorldScenarios with 3 trading scenarios
- Add math package import for floating-point precision comparison
- All tests validate PnL percentage calculation with different leverage scenarios
Co-authored-by: tinkle-community <tinklefund@gmail.com>
---------
Co-authored-by: tinkle-community <tinklefund@gmail.com>
2025-11-09 17:43:28 +08:00
Lawrence Liu 146d2ad9a7 fix: 修复 AI 决策时收到的持仓盈亏百分比未考虑杠杆 (#819)
Fixes #818
## 问题
传递给 AI 决策的持仓盈亏百分比只计算价格变动,未考虑杠杆倍数。
例如:10倍杠杆,价格上涨1%,AI看到的是1%而非实际的10%收益率。
## 改动
1. 修复 buildTradingContext 中的盈亏百分比计算
   - 从基于价格变动改为基于保证金计算
   - 收益率 = 未实现盈亏 / 保证金 × 100%
2. 抽取公共函数 calculatePnLPercentage
   - 消除 buildTradingContext 和 GetPositions 的重复代码
   - 确保两处使用相同的计算逻辑
3. 新增单元测试 (trader/auto_trader_test.go)
   - 9个基础测试用例(正常、边界、异常)
   - 3个真实场景测试(BTC/ETH/SOL不同杠杆)
   - 测试覆盖率:100%
4. 更新 .gitignore
   - 添加 SQLite WAL 相关文件 (config.db-shm, config.db-wal, nofx.db)
## 测试结果
 所有 12 个单元测试通过
 代码编译通过
 与 GetPositions 函数保持一致
## 影响
- AI 现在能够准确评估持仓真实收益率
- 避免因错误数据导致的过早止盈或延迟止损
2025-11-09 16:21:31 +08:00
Lawrence Liu fd3fc654cb Fix 历史最高收益率(百分比), 盈亏金额 USDT, 最高收益率 没有传递给 AI 作决策,无法在 prompt 中使用 (#651) 2025-11-09 16:20:52 +08:00
Shui c1003ca3e8 feat(hook): Add hook module to help decouple some specific logic (#784) 2025-11-09 09:02:30 +08:00
Shui 27a38e1e0d fix(auto_trader): trader's stop channel isn't set when restarting (#779)
* fix(auto_trader): trader's stop channel isn't set when restarting
* fix stopping trader immediately
---------
Co-authored-by: zbhan <zbhan@freewheel.tv>
2025-11-08 13:57:28 -05:00
Shui 61101c07dc Fix(auto_trader): casue panic because close a close channel (#737)
Co-authored-by: zbhan <zbhan@freewheel.tv>
2025-11-08 12:58:02 +08:00
Lawrence Liu d23628a5a1 fix: use symbol_side as peakPnLCache key to support dual-side positions (#657)
Fixes #652
Previously, peakPnLCache used only 'symbol' as the key, causing LONG
and SHORT positions of the same symbol to share the same peak P&L value.
This led to incorrect drawdown calculations and emergency close triggers.
Changes:
- checkPositionDrawdown: use posKey (symbol_side) for cache access
- UpdatePeakPnL: add side parameter and use posKey internally
- ClearPeakPnLCache: add side parameter and use posKey internally
Example fix:
- Before: peakPnLCache["BTCUSDT"] shared by both LONG and SHORT
- After: peakPnLCache["BTCUSDT_long"] and peakPnLCache["BTCUSDT_short"]
Impact:
- Fixes incorrect drawdown monitoring for dual positions
- Prevents false emergency close triggers on profitable positions
2025-11-07 21:34:01 -05:00
Linden f1f24ad1fa fix:完善aster账户净值和盈亏计算|Improve the calculation of the net value and profit/loss of the aster account (#695)
Co-authored-by: LindenWang <linden@Lindens-MacBookPro-2.local>
2025-11-07 13:38:39 +08:00
ZhouYongyou fa1f869eea fix: 添加双向持仓防御性检查,避免误删除对向订单
在上一个修复(113a30f)中,虽然解决了订单累积问题,但引入了新的风险:
如果用户同时持有同一symbol的多空双向持仓,update_stop_loss/update_take_profit
会误删除另一方向的保护订单。
```
假设:
- BTCUSDT LONG 持仓(止损 95000)
- BTCUSDT SHORT 持仓(止损 105000)
AI 执行:update_stop_loss for SHORT
→ CancelStopLossOrders("BTCUSDT") 删除所有止损
→ SetStopLoss("BTCUSDT", "SHORT", ...) 只设置 SHORT 止损
结果:
- SHORT 止损正确更新 
- LONG 止损被误删  失去保护!
```
1.  技术支持:Binance 设置为双向持仓模式(Hedge Mode)
2.  策略禁止:Prompt 明确禁止"对同一标的同时持有多空"
3.  代码保护:开仓时检查已有同向持仓并拒绝
理论上不应该出现双向持仓,但仍需防御:
- 用户手动操作
- 并发bug
- 遗留数据
在 auto_trader.go 的 update_stop_loss/update_take_profit 函数中:
1. 执行前检测是否存在对向持仓
2. 如果检测到双向持仓:
   - 记录 🚨 严重警告日志
   - 说明这违反策略规则
   - 提示可能的原因和建议
3. 继续执行当前逻辑(因为策略本身禁止双向持仓)
- executeUpdateStopLossWithRecord: 添加双向持仓检测(第1175-1194行)
- executeUpdateTakeProfitWithRecord: 添加双向持仓检测(第1259-1278行)
```
🚨 警告:检测到 BTCUSDT 存在双向持仓(SHORT + LONG),这违反了策略规则
🚨 取消止损单将影响两个方向的订单,请检查是否为用户手动操作导致
🚨 建议:手动平掉其中一个方向的持仓,或检查系统是否有BUG
```
- 会影响所有实现类(binance/aster/hyperliquid)
- 增加复杂度
- 策略已禁止双向持仓,属于异常场景
- 实现过于复杂
- 需要重新实现订单管理逻辑
- 策略禁止场景不应该出现
-  最小侵入性修改
-  及时警告异常情况
-  不影响正常流程
-  为调试提供线索
- 正常使用(单向持仓):无影响,正常工作 
- 异常场景(双向持仓):记录警告,提示用户检查 ⚠️
Related: 113a30f (原始修复)
2025-11-06 02:57:59 +08:00
ERIC LEUNG 5328166018 fix: 删除多定义的方法 (#528) 2025-11-05 20:11:50 +08:00
zcan 7ab2dbcc8d Fix/binance server time (#453)
* Fix Binance futures server time sync
* Fix Binance server time sync; clean up logging and restore decision sorting
---------
Co-authored-by: tinkle-community <tinklefund@gmail.com>
2025-11-05 17:09:47 +08:00
Icyoung 483c3b6e08 Merge branch 'dev' into dev 2025-11-05 16:21:57 +08:00
Icyoung 89f95d2bef Merge pull request #437 from zhouyongyou/fix/margin-calculation
fix(margin): correct position sizing formula to prevent insufficient margin errors
2025-11-05 16:13:37 +08:00
Icyoung 52f3985408 Merge branch 'dev' into feat/auto-balance-sync 2025-11-05 16:01:57 +08:00
Icyoung 0da42bd1fd Merge branch 'dev' into fix/bug-fixes-collection-v2 2025-11-05 15:56:58 +08:00
Icyoung af1fc4189a Merge pull request #415 from zhouyongyou/feat/partial-close-core-v2
feat: 部分平倉和動態止盈止損核心實現 / Partial Close & Dynamic TP/SL Core
2025-11-05 15:41:20 +08:00
guoyihan 99cecf9ffe feat: 增加持仓最高收益缓存和自动止盈机制
- 添加单币持仓最高收益缓存功能
- 实现定时任务,每分钟检查持仓收益情况
- 添加止盈条件:最高收益回撤>=40且利润>=5时自动止盈
- 优化持仓监控和风险管理能力
2025-11-05 03:15:44 +08:00
SkywalkerJi 35ea18e927 log.Printf mandates that its first argument must be a compile-time constant string. 2025-11-05 01:36:44 +08:00
ZhouYongyou 2bab17d043 fix(trader): add safety checks for balance sync
## 修复内容
### 1. 防止除以零panic (严重bug修复)
- 在计算变化百分比前检查 oldBalance <= 0
- 如果初始余额无效,直接更新为实际余额
- 避免 division by zero panic
### 2. 增强错误处理
- 添加数据库类型断言失败的日志
- 添加数据库为nil的警告日志
- 提供更完整的错误信息
## 技术细节
问题场景:如果 oldBalance = 0,计算 changePercent 会 panic
修复后:在计算前检查 oldBalance <= 0,直接更新余额
## 审查发现
- P0: 除以零风险(已修复)
- P1: 类型断言失败未记录(已修复)
- P1: 数据库为nil未警告(已修复)
详细审查报告:code_review_auto_balance_sync.md
2025-11-04 21:02:26 +08:00
ZhouYongyou 7091f76ca8 feat(trader): add automatic balance sync every 10 minutes
## 功能说明
自动检测交易所余额变化,无需用户手动操作
## 核心改动
1. AutoTrader 新增字段:
   - lastBalanceSyncTime: 上次余额同步时间
   - database: 数据库引用(用于自动更新)
   - userID: 用户ID
2. 新增方法 autoSyncBalanceIfNeeded():
   - 每10分钟检查一次(避免与3分钟扫描周期重叠)
   - 余额变化>5%才更新数据库
   - 智能失败重试(避免频繁查询)
   - 完整日志记录
3. 集成到交易循环:
   - 在 runCycle() 中第3步自动调用
   - 先同步余额,再获取交易上下文
   - 不影响现有交易逻辑
4. TraderManager 更新:
   - addTraderFromDB(), AddTraderFromDB(), loadSingleTrader()
   - 新增 database 和 userID 参数
   - 正确传递到 NewAutoTrader()
5. Database 新增方法:
   - UpdateTraderInitialBalance(userID, id, newBalance)
   - 安全更新初始余额
## 为什么选择10分钟?
1. 避免与3分钟扫描周期重叠(每30分钟仅重叠1次)
2. API开销最小化:每小时仅6次额外调用
3. 充值延迟可接受:最多10分钟自动同步
4. API占用率:0.2%(远低于币安2400次/分钟限制)
## API开销
- GetBalance() 轻量级查询(权重5-10)
- 每小时仅6次额外调用
- 总调用:26次/小时(runCycle:20 + autoSync:6)
- 占用率:(10/2400)/60 = 0.2% 
## 用户体验
- 充值后最多10分钟自动同步
- 完全自动化,无需手动干预
- 前端数据实时准确
## 日志示例
- 🔄 开始自动检查余额变化...
- 🔔 检测到余额大幅变化: 693.00 → 3693.00 USDT (433.19%)
-  已自动同步余额到数据库
- ✓ 余额变化不大 (2.3%),无需更新
2025-11-04 20:51:14 +08:00
ZhouYongyou 4e6b868531 fix(margin): correct position sizing formula to prevent insufficient margin errors
## Problem
AI was calculating position_size_usd incorrectly, treating it as margin requirement instead of notional value, causing code=-2019 errors (insufficient margin).
## Solution
### 1. Updated AI prompts with correct formula
- **prompts/adaptive.txt**: Added clear position sizing calculation steps
- **prompts/nof1.txt**: Added English version with example
- **prompts/default.txt**: Added Chinese version with example
**Correct formula:**
1. Available Margin = Available Cash × 0.95 × Allocation % (reserve 5% for fees)
2. Notional Value = Available Margin × Leverage
3. position_size_usd = Notional Value (this is the value for JSON)
**Example:** $500 cash, 5x leverage → position_size_usd = $2,375 (not $500)
### 2. Added code-level validation
- **trader/auto_trader.go**: Added margin checks in executeOpenLong/ShortWithRecord
- Validates required margin + fees ≤ available balance before opening position
- Returns clear error message if insufficient
## Impact
- Prevents code=-2019 errors
- AI now understands the difference between notional value and margin requirement
- Double validation: AI prompt + code check
## Testing
-  Compiles successfully
- ⚠️ Requires live trading environment testing
2025-11-04 18:44:07 +08:00
ZhouYongyou b7a1a60c6f fix: 过滤幽灵持仓 - 跳过 quantity=0 的持仓防止 AI 误判
问题:
- 止损/止盈触发后,交易所返回 positionAmt=0 的持仓记录
- 这些幽灵持仓被传递给 AI,导致 AI 误以为仍持有该币种
- AI 可能基于错误信息做出决策(如尝试调整已不存在的止损)
修复:
- buildTradingContext() 中添加 quantity==0 检查
- 跳过已平仓的持仓,确保只传递真实持仓给 AI
- 触发清理逻辑:撤销孤儿订单、清理内部状态
影响范围:
- trader/auto_trader.go:487-490
测试:
- 编译成功
- 容器重建并启动正常
2025-11-04 17:35:19 +08:00
ZhouYongyou 9884605c75 修復關鍵缺陷:添加 CancelStopOrders 方法避免多個止損單共存
問題:
- 調整止損/止盈時,直接調用 SetStopLoss/SetTakeProfit 會創建新訂單
- 但舊的止損/止盈單仍然存在,導致多個訂單共存
- 可能造成意外觸發或訂單衝突
解決方案(參考 PR #197):
1. 在 Trader 接口添加 CancelStopOrders 方法
2. 為三個交易所實現:
   - binance_futures.go: 過濾 STOP_MARKET/TAKE_PROFIT_MARKET 類型
   - aster_trader.go: 同樣邏輯
   - hyperliquid_trader.go: 過濾 trigger 訂單(有 triggerPx)
3. 在 executeUpdateStopLossWithRecord 和 executeUpdateTakeProfitWithRecord 中:
   - 先調用 CancelStopOrders 取消舊單
   - 然後設置新止損/止盈
   - 取消失敗不中斷執行(記錄警告)
優勢:
-  避免多個止損單同時存在
-  保留我們的價格驗證邏輯
-  保留執行價格記錄
-  詳細錯誤信息
-  取消失敗時繼續執行(更健壯)
測試建議:
- 開倉後調整止損,檢查舊止損單是否被取消
- 連續調整兩次,確認只有最新止損單存在
致謝:參考 PR #197 的實現思路
2025-11-04 16:40:23 +08:00
ZhouYongyou 8344e6b68f feat: 添加部分平仓和动态止盈止损功能
新增功能:
- update_stop_loss: 调整止损价格(追踪止损)
- update_take_profit: 调整止盈价格(技术位优化)
- partial_close: 部分平仓(分批止盈)
实现细节:
- Decision struct 新增字段:NewStopLoss, NewTakeProfit, ClosePercentage
- 新增执行函数:executeUpdateStopLossWithRecord, executeUpdateTakeProfitWithRecord, executePartialCloseWithRecord
- 修复持仓字段获取 bug(使用 "side" 并转大写)
- 更新 adaptive.txt 文档,包含详细使用示例和策略建议
- 优先级排序:平仓 > 调整止盈止损 > 开仓
命名统一:
- 与社区 PR #197 保持一致,使用 update_* 而非 adjust_*
- 独有功能:partial_close(部分平仓)
Co-Authored-By: tinkle-community <tinklefund@gmail.com>
2025-11-04 16:40:12 +08:00
Icyoung ea374d2311 Merge pull request #359 from Icyoung/beta
Beta Merge dev、Bug fix
2025-11-04 01:50:34 +08:00
hzb1115 62ebd58a1f style(backend): go fmt code 2025-11-03 17:22:11 +00:00
Liu Xiang Qian 2eb5801e3d Revert "Merge pull request #229 from xqliu/test/add-ut-infrastructure"
This reverts commit 683e77b92f7608c31a7c25c91bb938c4d657f6e4, reversing
changes made to 791cecd2ffff0ebc3ea88c04fb91ddbe0c001422.
2025-11-04 00:58:12 +08:00
Liu Xiang Qian cf12be74f5 test: Add minimal UT infrastructure and fix Issue #227
This commit sets up a minimal, KISS-principle testing infrastructure
for both backend and frontend, and includes the fix for Issue #227.
Backend Changes:
- Add Makefile with test commands (test, test-backend, test-frontend, test-coverage)
- Add example test: config/database_test.go
- Fix Go 1.25 printf format string warnings in trader/auto_trader.go
  (Changed log.Printf to log.Print for non-format strings)
- All backend tests pass ✓
Frontend Changes:
- Add Vitest configuration: web/vitest.config.ts (minimal setup)
- Add test utilities: web/src/test/test-utils.tsx
- Add example test: web/src/App.test.tsx
- Add dependencies: vitest, jsdom, @testing-library/react
- All frontend tests pass ✓
Issue #227 Fix:
- Fix AITradersPage to allow editing traders with disabled models/exchanges
- Change validation to use allModels/allExchanges instead of enabledModels/enabledExchanges
- Add comprehensive tests in web/src/components/AITradersPage.test.tsx
- Fixes: https://github.com/tinkle-community/nofx/issues/227
CI/CD:
- Add GitHub Actions workflow: .github/workflows/test.yml
- Non-blocking tests (continue-on-error: true)
- Runs on push/PR to main and dev branches
Test Results:
- Backend: 1 test passing
- Frontend: 5 tests passing (including 4 for Issue #227)
Co-Authored-By: tinkle-community <tinklefund@gmail.com>
2025-11-02 10:58:31 +08:00
SkywalkerJi 5ad135310f Supports custom system prompts and custom models. 2025-11-01 19:45:54 +08:00
SkywalkerJi 7542f9df49 * Fixed the custom model URL.
*   Added functionality for custom model names.
2025-11-01 16:09:15 +08:00
icy d1d9810075 竞赛fix、交易员新增参数 2025-11-01 02:17:11 +08:00
icy 142863f554 Add MarginMode configration 2025-10-31 13:14:24 +08:00
icy ceb2f7b435 account system、custom prompt 2025-10-31 03:42:01 +08:00
tinkle-community fd8b1477e7 Fix: Resolve Trade History data loss and P&L calculation errors
Major fixes:
1. Trade History data loss issue
   - Root cause: Open records outside analysis window caused close matching failures
   - Solution: Pre-populate position state by reading 3x window of historical records
   - Ensures long-term positions (>5 hours) generate correct trade records
2. P&L calculation errors
   - Remove incorrect leverage multiplication from absolute P&L
   - Correct calculation: Futures P&L = quantity × price difference
   - Leverage only affects P&L percentage (relative to margin)
3. Other fixes
   - Break-even trades (pnl=0) no longer misclassified as losses
   - Perfect strategy shows Profit Factor as 999.0 instead of 0.0
   - Expand analysis window from 20 to 100 cycles (5 hours)
Files changed:
- logger/decision_logger.go: Core matching and calculation logic
- api/server.go: API analysis window
- trader/auto_trader.go: AI decision analysis window
Co-Authored-By: tinkle-community <tinklefund@gmail.com>
2025-10-30 17:58:25 +08:00
刘 志 887899749f fix: hyperliquid余额不准确 2025-10-30 08:38:31 +00:00
tpkeeper b773d7289a Fix mcp defaultConfig override issue in multi-trader, multi-AI model scenario 2025-10-30 15:46:17 +08:00
nobody 87f67f2da1 feat: Add Aster DEX exchange support + fix precision issues
## Features
- Add full Aster DEX integration with Binance-compatible API
- Support Web3 authentication with API wallet system
- Add comprehensive Aster integration guide (ASTER_INTEGRATION.md)
- Add example Aster configuration (config.aster.example.json)
## Bug Fixes
- Fix precision error (code -1111) for all order types
- Implement proper float-to-string conversion with exchange precision
- Add automatic precision fetching from /exchangeInfo endpoint
- Remove trailing zeros from formatted values
## Documentation
- Update README.md with Aster quick start guide
- Add detailed setup instructions for creating API wallet
- Include troubleshooting FAQ and security best practices
- Update core features to mention three supported exchanges
## Technical Details
- Added formatFloatWithPrecision() helper function
- Updated all order functions to use proper precision formatting
- Added precision logging for debugging
- Fully backward compatible with existing configurations
Closes #[issue number if applicable]
2025-10-30 00:27:33 +08:00
btcman a13f39afdd Feature: Add support for custom OpenAI-compatible API
This update enables users to configure any OpenAI-compatible API endpoint,
allowing the use of:
- OpenAI official API (GPT-4, GPT-4o, etc.)
- OpenRouter (access to multiple models)
- Local deployed models (Ollama, LM Studio, etc.)
- Other OpenAI-format compatible API services
Changes:
- config: Add custom_api_url, custom_api_key, custom_model_name fields
- mcp: Add SetCustomAPI function and ProviderCustom constant
- trader: Update AI initialization logic to support custom API
- manager: Pass custom API config to trader instances
- Add CUSTOM_API.md documentation with usage examples
- Update config.json.example with custom API sample
Co-Authored-By: tinkle-community <tinklefund@gmail.com>
2025-10-29 22:48:28 +08:00
PorunC 6e304f6388 Merge upstream/main: Integrate Hyperliquid support with leverage config
Resolved conflicts in manager/trader_manager.go by combining:
- Upstream: Exchange field, Hyperliquid API keys, Hyperliquid testnet
- Local: BTCETHLeverage and AltcoinLeverage fields
Both features are now working together.
2025-10-29 21:01:05 +08:00
PorunC cf9fdeafb2 Feat: Integrate leverage configuration across trading system
- Pass leverage config through TraderManager to AutoTrader
- Add BTCETHLeverage and AltcoinLeverage fields to Context and AutoTraderConfig
- Update decision validation to use configured leverage limits
- Display configured leverage in startup message
- Update error messages to show current leverage limits
Changes:
- main.go: Pass leverage config to AddTrader, update startup message
- manager/trader_manager.go: Accept and forward leverage config
- trader/auto_trader.go: Store leverage config, pass to Context
- decision/engine.go: Use dynamic leverage limits in validation
This completes the leverage configuration feature implementation.
Co-Authored-By: tinkle-community <tinklefund@gmail.com>
2025-10-29 20:30:04 +08:00
nobody 0164ac6cc0 feat: Add Hyperliquid exchange support with unified trader interface
Major changes:
- Add full Hyperliquid trading support (long/short, leverage, SL/TP)
- Create unified Trader interface for multi-exchange support
- Implement automatic precision handling for orders and prices
- Fix balance calculation and unrealized P&L display
- Add comprehensive configuration guide in README
New features:
- Support for both Binance and Hyperliquid exchanges
- Automatic order size precision based on szDecimals
- Price formatting with 5 significant figures
- Non-custodial trading with Ethereum private key
- Seamless exchange switching via configuration
Technical details:
- Add trader/interface.go for unified trader interface
- Add trader/hyperliquid_trader.go for Hyperliquid implementation
- Update manager and auto_trader to support multiple exchanges
- Add go-hyperliquid SDK dependency
- Fix precision errors (float_to_wire, invalid price)
Fixes:
- Correct calculation of wallet balance and unrealized P&L
- Proper handling of AccountValue vs TotalRawUsd
- Frontend display issues for total equity and P&L
Documentation:
- Add Hyperliquid setup guide in README
- Update config.json.example with both exchanges
- Add troubleshooting section for common errors
Tested with live trading on Hyperliquid mainnet.
No breaking changes - backward compatible with existing configs.
2025-10-29 20:00:30 +08:00
tinkle-community d4a5c0534d Feature: Add position holding duration to AI decision context
Track and display how long each position has been held to help AI make better timing decisions.
**Implementation**:
- Added UpdateTime field to PositionInfo struct (decision/engine.go:26)
- Added positionFirstSeenTime map to AutoTrader for tracking (trader/auto_trader.go:60)
- Record opening time when position is created successfully:
  - executeOpenLongWithRecord: Records timestamp for long positions (trader/auto_trader.go:540-541)
  - executeOpenShortWithRecord: Records timestamp for short positions (trader/auto_trader.go:593-594)
- Fallback tracking in buildTradingContext for program restart scenarios (trader/auto_trader.go:386-392)
- Auto-cleanup closed positions from tracking map (trader/auto_trader.go:409-414)
- Display duration in user prompt with smart formatting:
  - Under 60 min: "持仓时长25分钟"
  - Over 60 min: "持仓时长2小时15分钟"
**Example Output**:
```
1. TAOUSDT LONG | 入场价435.5300 当前价433.1900 | 盈亏-0.54% | 杠杆20x | 保证金25 | 强平价418.1528 | 持仓时长2小时15分钟
```
**Benefits**:
- AI can see how long positions have been held
- Helps enforce minimum holding period (30-60 min) from system prompt
- Simple implementation with minimal overhead
- Auto-cleanup prevents memory leaks
Co-Authored-By: tinkle-community <tinklefund@gmail.com>
2025-10-29 14:20:40 +08:00
tinkle-community b2c6925c89 Refactor: Modularize codebase with separate decision and MCP packages
Architecture improvements:
- Extract AI decision engine to dedicated `decision` package
- Create `mcp` package for Model Context Protocol client
- Separate market data structures into `market/data.go`
- Update trader to use new modular structure
New packages:
- `decision/engine.go` - AI decision logic and prompt building
- `mcp/client.go` - Unified AI API client (DeepSeek/Qwen)
- `market/data.go` - Market data type definitions
Benefits:
- Better separation of concerns
- Improved code organization and maintainability
- Easier to test individual components
- More flexible AI provider integration
- Cleaner dependency management
Updated imports:
- trader/auto_trader.go now uses decision and mcp packages
- Consistent API across different AI providers
Co-Authored-By: tinkle-community <tinklefund@gmail.com>
2025-10-29 06:14:57 +08:00
tinkle-community ceaedca253 Refactor: Improve AI decision system and Sharpe ratio calculation
Major improvements:
- Use period-level Sharpe ratio (range -2 to +2) instead of annualized
- Save full user prompt in decision logs for debugging
- Format complete market data (3m + 4h candles) for AI analysis
- Prevent position stacking with duplicate position checks
- Update Sharpe ratio interpretation thresholds
Market data enhancements:
- Display full technical indicators in user prompt
- Include 3-minute and 4-hour timeframe data
- Add OI (Open Interest) change and funding rate signals
Risk control:
- Block opening duplicate positions (same symbol + direction)
- Suggest close action first before opening new position
- Prevent margin usage from exceeding limits
UI improvements:
- Update multi-language translations
- Refine AI learning dashboard display
Co-Authored-By: tinkle-community <tinklefund@gmail.com>
2025-10-29 04:44:17 +08:00
tinkle-community 5aa50d35d7 Initial commit: NOFX AI Trading System
- Multi-AI competition mode (Qwen vs DeepSeek)
- Binance Futures integration
- AI self-learning mechanism
- Professional web dashboard
- Complete risk management system
2025-10-28 15:47:34 +08:00