mirror of
https://github.com/NoFxAiOS/nofx.git
synced 2025-12-06 13:54:41 +08:00
dev
36 Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
9c2eb897a1 | update docs | ||
|
|
250758959c | update Security Policy | ||
|
|
b66fd5fb0a |
fix(docker): revert healthcheck to wget for Alpine compatibility (#986)
## Problem PR #906 changed healthcheck commands from `wget` to `curl`, but Alpine Linux (our base image) does not include `curl` by default, causing all containers to fail healthchecks with: ``` exec: "curl": executable file not found in $PATH ``` This creates a configuration mismatch: - docker/Dockerfile.backend uses `wget` (✅ works) - docker-compose.yml uses `curl` (❌ fails) ## Root Cause Analysis Alpine Linux philosophy is minimalism: - ✅ `wget` is pre-installed (part of busybox) - ❌ `curl` requires `apk add curl` (~3MB extra) The original PR #906 made two commits: 1. First commit ( |
||
|
|
c0239f2b14 | fix gh job failed when pr contains issues (#1019) | ||
|
|
190b0c29d4 | merge dev | ||
|
|
db9851b993 |
Merge branch 'dev' into beta
# Conflicts: # .github/workflows/docker-build.yml # .gitignore # api/server.go # config/config.go # config/database.go # decision/engine.go # docker-compose.yml # go.mod # go.sum # logger/telegram_sender.go # main.go # mcp/client.go # prompts/adaptive.txt # prompts/default.txt # prompts/nof1.txt # start.sh # trader/aster_trader.go # trader/auto_trader.go # trader/binance_futures.go # trader/hyperliquid_trader.go # web/package-lock.json # web/package.json # web/src/App.tsx # web/src/components/AILearning.tsx # web/src/components/AITradersPage.tsx # web/src/components/CompetitionPage.tsx # web/src/components/EquityChart.tsx # web/src/components/Header.tsx # web/src/components/LoginPage.tsx # web/src/components/RegisterPage.tsx # web/src/components/TraderConfigModal.tsx # web/src/components/TraderConfigViewModal.tsx # web/src/components/landing/FooterSection.tsx # web/src/components/landing/HeaderBar.tsx # web/src/contexts/AuthContext.tsx # web/src/i18n/translations.ts # web/src/lib/api.ts # web/src/lib/config.ts # web/src/types.ts |
||
|
|
97797d3c3a |
fix(ci): add test encryption key for CI environment (#826)
* fix(ci): add test encryption key for CI environment - Add DATA_ENCRYPTION_KEY environment variable to PR test workflow - Add test RSA public key for encryption tests in CI - Ensures unit tests pass in CI without production credentials Co-authored-by: tinkle-community <tinklefund@gmail.com> * fix(ci): install Go cover tool to eliminate covdata warnings - Add step to install golang.org/x/tools/cmd/cover in CI workflow - Use || true to prevent installation failure from breaking CI - Eliminates "no such tool covdata" warnings during test execution - Apply go fmt to multiple files for consistency Co-authored-by: tinkle-community <tinklefund@gmail.com> * fix(ci): install covdata tool for Go 1.23 coverage The CI was failing with "go: no such tool 'covdata'" error. This is because Go 1.23 requires the covdata tool to be installed for coverage reporting. Changes: - Install golang.org/x/tools/cmd/covdata in CI workflow - Update step name to reflect both coverage tools being installed Fixes the unit test failures in CI pipeline. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: tinkle-community <tinklefund@gmail.com> * fix(ci): remove unnecessary covdata installation and use builtin go tool cover The previous attempt to install golang.org/x/tools/cmd/covdata was failing because the package structure changed in Go 1.23 and tools v0.38.0. The covdata tool is not needed for this project since we only use simple coverage reporting with go test -coverprofile. The go tool cover command is built into the Go toolchain and requires no additional installation. Changes: - Remove failed covdata and cover installation attempts - Add verification step for go tool cover availability - Simplify CI pipeline by eliminating unnecessary dependencies Co-authored-by: tinkle-community <tinklefund@gmail.com> * fix(ci): upgrade Go version to 1.25 to match go.mod declaration The CI was using Go 1.23 while go.mod declares go 1.25.0, causing "no such tool covdata" errors during coverage test compilation. Go 1.25's coverage infrastructure requires toolchain features not available in Go 1.23. This change aligns the CI Go version with the project's declared version requirement, ensuring the full Go 1.25 toolchain (including the covdata tool) is available for coverage testing. Co-authored-by: tinkle-community <tinklefund@gmail.com> --------- Co-authored-by: tinkle-community <tinklefund@gmail.com> |
||
|
|
ae09647468 |
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> |
||
|
|
65053518d6 |
feat: implement hybrid database architecture and frontend encryption
- Add PostgreSQL + SQLite hybrid database support with automatic switching - Implement frontend AES-GCM + RSA-OAEP encryption for sensitive data - Add comprehensive DatabaseInterface with all required methods - Fix compilation issues with interface consistency - Update all database method signatures to use DatabaseInterface - Add missing UpdateTraderInitialBalance method to PostgreSQL implementation - Integrate RSA public key distribution via /api/config endpoint - Add frontend crypto service with proper error handling - Support graceful degradation between encrypted and plaintext transmission - Add directory creation for RSA keys and PEM parsing fixes - Test both SQLite and PostgreSQL modes successfully 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: tinkle-community <tinklefund@gmail.com> |
||
|
|
05957cccf5 |
fix: Increase Docker build speed by 98%. (#545)
* Resolved front-end linting issues. * Streamlining Docker Build Scripts * Leveraging Native ARM64 Runners on GitHub. * Use lowercase framework names. |
||
|
|
d8cb1e6e47 |
Beta merge from dev (#535)
* fix: GetTraderConfig missing critical fields in SELECT/Scan **Problem**: - GetTraderConfig was missing 9 critical fields in SELECT statement - Missing corresponding Scan variables - Caused trader edit UI to show 0 for leverage and empty trading_symbols **Root Cause**: Database query only selected basic fields (id, name, balance, etc.) but missed leverage, trading_symbols, prompts, and all custom configs **Fix**: - Added missing fields to SELECT: * btc_eth_leverage, altcoin_leverage * trading_symbols * use_coin_pool, use_oi_top * custom_prompt, override_base_prompt * system_prompt_template * is_cross_margin * AI model custom_api_url, custom_model_name - Added corresponding Scan variables to match SELECT order **Impact**: ✅ Trader edit modal now displays correct leverage values ✅ Trading symbols list properly populated ✅ All custom configurations preserved and displayed ✅ API endpoint /traders/:id/config returns complete data **Testing**: - ✅ Go compilation successful - ✅ All fields aligned (31 SELECT = 31 Scan) - ✅ API layer verified (api/server.go:887-904) Reported by: 寒江孤影 Issue: Trader config edit modal showing 0 leverage and empty symbols 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: tinkle-community <tinklefund@gmail.com> * Fix PR check * fix(readme): update readme and pr reviewer * fix owner * Fix owner * feat(hyperliquid): Auto-generate wallet address from private key Enable automatic wallet address generation from private key for Hyperliquid exchange, simplifying user onboarding and reducing configuration errors. Backend Changes (trader/hyperliquid_trader.go): - Import crypto/ecdsa package for ECDSA public key operations - Enable wallet address auto-generation when walletAddr is empty - Use crypto.PubkeyToAddress() to derive address from private key - Add logging for both auto-generated and manually provided addresses Frontend Changes (web/src/components/AITradersPage.tsx): - Remove wallet address required validation (only private key required) - Update button disabled state to only check private key - Add "Optional" label to wallet address field - Add dynamic placeholder with bilingual hint - Show context-aware helper text based on input state - Remove HTML required attribute from input field Translation Updates (web/src/i18n/translations.ts): - Add 'optional' translation (EN: "Optional", ZH: "可选") - Add 'hyperliquidWalletAddressAutoGenerate' translation EN: "Leave blank to automatically generate wallet address from private key" ZH: "留空将自动从私钥生成钱包地址" Benefits: ✅ Simplified UX - Users only need to provide private key ✅ Error prevention - Auto-generated address always matches private key ✅ Backward compatible - Manual address input still supported ✅ Better UX - Clear visual indicators for optional fields Technical Details: - Uses Ethereum standard ECDSA public key to address conversion - Implementation was already present but commented out (lines 37-43) - No database schema changes required (hyperliquid_wallet_addr already nullable) - Fallback behavior: manual input > auto-generation 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: tinkle-community <tinklefund@gmail.com> * fix * fix pk prefix handle * fix go vet check * fix print * feat: Add Binance setup guide with tutorial modal - Add Binance configuration tutorial image (guide.png) - Implement "View Guide" button in exchange configuration modal - Add tutorial display modal with image viewer - Add i18n support for guide-related text (EN/ZH) - Button only appears when configuring Binance exchange 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: tinkle-community <tinklefund@gmail.com> * feat: add PostgreSQL data viewing utility script - Create view_pg_data.sh for easy database data inspection - Display table record counts, AI models, exchanges, and system config - Include beta codes and user statistics - Auto-detect docker-compose vs docker compose commands 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: tinkle-community <tinklefund@gmail.com> * fix(api): query actual exchange balance when creating trader Problem: - Users could input arbitrary initial balance when creating traders - This didn't reflect the actual available balance in exchange account - Could lead to incorrect position sizing and risk calculations Solution: - Before creating trader, query exchange API for actual balance - Use GetBalance() from respective trader implementation: * Binance: NewFuturesTrader + GetBalance() * Hyperliquid: NewHyperliquidTrader + GetBalance() * Aster: NewAsterTrader + GetBalance() - Extract 'available_balance' or 'balance' from response - Override user input with actual balance - Fallback to user input if query fails Changes: - Added 'nofx/trader' import - Query GetExchanges() to find matching exchange config - Create temporary trader instance based on exchange type - Call GetBalance() to fetch actual available balance - Use actualBalance instead of req.InitialBalance - Comprehensive error handling with fallback logic Benefits: - ✅ Ensures accurate initial balance matches exchange account - ✅ Prevents user errors in balance input - ✅ Improves position sizing accuracy - ✅ Maintains data integrity between system and exchange Example logs: ✓ 查询到交易所实际余额: 150.00 USDT (用户输入: 100.00 USDT) ⚠️ 查询交易所余额失败,使用用户输入的初始资金: connection timeout 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: tinkle-community <tinklefund@gmail.com> * fix(api): correct variable name from traderRecord to trader Fixed compilation error caused by variable name mismatch: - Line 404: defined as 'trader' - Line 425: was using 'traderRecord' (undefined) This aligns with upstream dev branch naming convention. * 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(部分平仓) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: tinkle-community <tinklefund@gmail.com> * 修復關鍵 BUG:validActions 缺少新動作導致驗證失敗 問題根因: - auto_trader.go 已實現 update_stop_loss/update_take_profit/partial_close 處理 - adaptive.txt 已描述這些功能 - 但 validateDecision 的 validActions map 缺少這三個動作 - 導致 AI 生成的決策在驗證階段被拒絕:「无效的action:update_stop_loss」 修復內容: 1. validActions 添加三個新動作 2. 為每個新動作添加參數驗證: - update_stop_loss: 驗證 NewStopLoss > 0 - update_take_profit: 驗證 NewTakeProfit > 0 - partial_close: 驗證 ClosePercentage 在 0-100 之間 3. 修正註釋:adjust_* → update_* 測試狀態:feature 分支,等待測試確認 * 修復關鍵缺陷:添加 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 的實現思路 * fix: 修复部分平仓盈利计算错误 问题:部分平仓时,历史记录显示的是全仓位盈利,而非实际平仓部分的盈利 根本原因: - AnalyzePerformance 使用开仓总数量计算部分平仓的盈利 - 应该使用 action.Quantity(实际平仓数量)而非 openPos["quantity"](总数量) 修复: - 添加 actualQuantity 变量区分完整平仓和部分平仓 - partial_close 使用 action.Quantity - 所有相关计算(PnL、PositionValue、MarginUsed)都使用 actualQuantity 影响范围:logger/decision_logger.go:428-465 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: tinkle-community <tinklefund@gmail.com> * fix: 修復 Hyperliquid CancelStopOrders 編譯錯誤 - OpenOrder 結構不暴露 trigger 字段 - 改為取消該幣種的所有掛單(安全做法) * fix: remove unnecessary prompts/adaptive.txt changes - This PR should only contain backend core functionality - prompts/adaptive.txt v2.0 is already in upstream - Prompt enhancements will be in separate PR (Batch 3) * 更新 logger:支持新增的三個動作類型 更新內容: 1. DecisionAction 註釋:添加 update_stop_loss, update_take_profit, partial_close 2. GetStatistics:partial_close 計入 TotalClosePositions 3. AnalyzePerformance 預填充邏輯:處理 partial_close(不刪除持倉記錄) 4. AnalyzePerformance 分析邏輯: - partial_close 正確判斷持倉方向 - 記錄部分平倉的盈虧統計 - 保留持倉記錄(因為還有剩餘倉位) 說明:partial_close 會記錄盈虧,但不刪除 openPositions, 因為還有剩餘倉位可能繼續交易 * refactor(prompts): add comprehensive partial_close guidance to adaptive.txt Add detailed guidance chapter for dynamic TP/SL management and partial close operations. ## Changes - New chapter: "动态止盈止损与部分平仓指引" (Dynamic TP/SL & Partial Close Guidance) - Inserted between "可用动作" (Actions) and "决策流程" (Decision Flow) sections - 4 key guidance points covering: 1. Partial close best practices (use clear percentages like 25%/50%/75%) 2. Reassessing remaining position after partial exit 3. Proper use cases for update_stop_loss / update_take_profit 4. Multi-stage exit strategy requirements ## Benefits - ✅ Provides concrete operational guidelines for AI decision-making - ✅ Clarifies when and how to use partial_close effectively - ✅ Emphasizes remaining position management (prevents "orphan" positions) - ✅ Aligns with existing backend support for partial_close action ## Background While adaptive.txt already lists partial_close as an available action, it lacked detailed operational guidance. This enhancement fills that gap by providing specific percentages, use cases, and multi-stage exit examples. Backend (decision/engine.go) already validates partial_close with close_percentage field, so this is purely a prompt enhancement with no code changes required. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: tinkle-community <tinklefund@gmail.com> * fix(market): resolve price staleness issue in GetCurrentKlines ## Problem GetCurrentKlines had two critical bugs causing price data to become stale: 1. Incorrect return logic: returned error even when data fetch succeeded 2. Race condition: returned slice reference instead of deep copy, causing concurrent data corruption ## Impact - BTC price stuck at 106xxx while actual market price was 107xxx+ - LLM calculated take-profit based on stale prices → orders failed validation - Statistics showed incorrect P&L (0.00%) due to corrupted historical data - Alt-coins filtered out due to failed market data fetch ## Solution 1. Fixed return logic: only return error when actual failure occurs 2. Return deep copy instead of reference to prevent race conditions 3. Downgrade subscription errors to warnings (non-blocking) ## Test Results ✅ Price updates in real-time ✅ Take-profit orders execute successfully ✅ P&L calculations accurate ✅ Alt-coins now tradeable Related: Price feed mechanism, concurrent data access * feat(decision): make OI threshold configurable + add relaxed prompt template ## Changes ### 1. decision/engine.go - Configurable OI Threshold - Extract hardcoded 15M OI threshold to configurable constant - Add clear documentation for risk profiles: - 15M (Conservative) - BTC/ETH/SOL only - 10M (Balanced) - Add major alt-coins - 8M (Relaxed) - Include mid-cap coins (BNB/LINK/AVAX) - 5M (Aggressive) - Most alt-coins allowed - Default: 15M (保守,維持原行為) ### 2. prompts/adaptive_relaxed.txt - New Trading Template Conservative optimization for increased trading frequency while maintaining high win-rate: **Key Adjustments:** - Confidence threshold: 85 → 80 (allow more opportunities) - Cooldown period: 9min → 6min (faster reaction) - Multi-timeframe trend: 3 periods → 2 periods (relaxed requirement) - Entry checklist: 5/8 → 4/8 (easier to pass) - RSI range: 30-40/65-70 → <45/>60 (wider acceptance) - Risk-reward ratio: 1:3 → 1:2.5 (more flexible) **Expected Impact:** - Trading frequency: 5/day → 8-15/day (+60-200%) - Win-rate: 40% → 50-55% (improved) - Alt-coins: More opportunities unlocked - Risk controls: Preserved (Sharpe-based, loss-pause) ## Usage Users can now choose trading style via Web UI: - `adaptive` - Strictest (original) - `adaptive_relaxed` - Balanced (this PR) - `nof1` - Most aggressive ## Rationale The original adaptive.txt uses 5-layer filtering (confidence/cooldown/trend/checklist/RSI) that filters out ~95% of opportunities. This template provides a middle-ground option for users who want higher frequency without sacrificing core risk management. Related: #trading-frequency #alt-coin-support * fix: 过滤幽灵持仓 - 跳过 quantity=0 的持仓防止 AI 误判 问题: - 止损/止盈触发后,交易所返回 positionAmt=0 的持仓记录 - 这些幽灵持仓被传递给 AI,导致 AI 误以为仍持有该币种 - AI 可能基于错误信息做出决策(如尝试调整已不存在的止损) 修复: - buildTradingContext() 中添加 quantity==0 检查 - 跳过已平仓的持仓,确保只传递真实持仓给 AI - 触发清理逻辑:撤销孤儿订单、清理内部状态 影响范围: - trader/auto_trader.go:487-490 测试: - 编译成功 - 容器重建并启动正常 * fix: 添加 HTTP/2 stream error 到可重試錯誤列表 問題: - 用戶遇到錯誤:stream error: stream ID 1; INTERNAL_ERROR - 這是 HTTP/2 連接被服務端關閉的錯誤 - 當前重試機制不包含此類錯誤,導致直接失敗 修復: - 添加 "stream error" 到可重試列表 - 添加 "INTERNAL_ERROR" 到可重試列表 - 遇到此類錯誤時會自動重試(最多 3 次) 影響: - 提高 API 調用穩定性 - 自動處理服務端臨時故障 - 減少因網絡波動導致的失敗 * fix: 修復首次運行時數據庫初始化失敗問題 問題: - 用戶首次運行報錯:unable to open database file: is a directory - 原因:Docker volume 掛載時,如果 config.db 不存在,會創建目錄而非文件 - 影響:新用戶無法正常啟動系統 修復: - 在 start.sh 啟動前檢查 config.db 是否存在 - 如不存在則創建空文件(touch config.db) - 確保 Docker 掛載為文件而非目錄 測試: - 首次運行:./start.sh start → 正常初始化 ✓ - 現有用戶:無影響,向後兼容 ✓ * fix: 修復初始余額顯示錯誤(使用當前淨值而非配置值) 問題: - 圖表顯示「初始余額 693.15 USDT」(實際應該是 600) - 原因:使用 validHistory[0].total_equity(當前淨值) - 導致初始余額隨著盈虧變化,數學邏輯錯誤 修復: - 優先從 account.initial_balance 讀取真實配置值 - 備選方案:從歷史數據反推(淨值 - 盈虧) - 默認值使用 1000(與創建交易員時的默認配置一致) 測試: - 初始余額:600 USDT(固定) - 當前淨值:693.15 USDT - 盈虧:+93.15 USDT (+15.52%) ✓ * fix: 統一 handleTraderList 返回完整 AI model ID(保持與 handleGetTraderConfig 一致) 問題: - handleTraderList 仍在截斷 AI model ID (admin_deepseek → deepseek) - 與 handleGetTraderConfig 返回的完整 ID 不一致 - 導致前端 isModelInUse 檢查失效 修復: - 移除 handleTraderList 中的截斷邏輯 - 返回完整 AIModelID (admin_deepseek) - 與其他 API 端點保持一致 測試: - GET /api/traders → ai_model: admin_deepseek ✓ - GET /api/traders/:id → ai_model: admin_deepseek ✓ - 模型使用檢查邏輯正確 ✓ * chore: upgrade sqlite3 to v1.14.22 for Alpine Linux compatibility - Fix compilation error on Alpine: off64_t type not defined in v1.14.16 - Remove unused pure-Go sqlite implementation (modernc.org/sqlite) and its dependencies - v1.14.22 is the first version fixing Alpine/musl build issues (2024-02-02) - Minimizes version jump (v1.14.16 → v1.14.22, 18 commits) to reduce risk Reference: https://github.com/mattn/go-sqlite3/issues/1164 Verified: Builds successfully on golang:1.25-alpine * chore: run go fmt to fix formatting issues * 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 * fix(stats): aggregate partial closes into single trade for accurate statistics ## Problem Multiple partial_close actions on the same position were being counted as separate trades, inflating TotalTrades count and distorting win rate/profit factor statistics. **Example of bug:** - Open 1 BTC @ $100,000 - Partial close 30% @ $101,000 → Counted as trade #1 ❌ - Partial close 50% @ $102,000 → Counted as trade #2 ❌ - Close remaining 20% @ $103,000 → Counted as trade #3 ❌ - **Result:** 3 trades instead of 1 ❌ ## Solution ### 1. Added tracking fields to openPositions map - `remainingQuantity`: Tracks remaining position size - `accumulatedPnL`: Accumulates PnL from all partial closes - `partialCloseCount`: Counts number of partial close operations - `partialCloseVolume`: Total volume closed partially ### 2. Modified partial_close handling logic - Each partial_close: - Accumulates PnL into `accumulatedPnL` - Reduces `remainingQuantity` - **Does NOT increment TotalTrades++** - Keeps position in openPositions map - Only when `remainingQuantity <= 0.0001`: - Records ONE TradeOutcome with aggregated PnL - Increments TotalTrades++ once - Removes from openPositions map ### 3. Updated full close handling - If position had prior partial closes: - Adds `accumulatedPnL` to final close PnL - Reports total PnL in TradeOutcome ### 4. Fixed GetStatistics() - Removed `partial_close` from TotalClosePositions count - Only `close_long/close_short/auto_close` count as close operations ## Impact - ✅ Statistics now accurate: multiple partial closes = 1 trade - ✅ Win rate calculated correctly - ✅ Profit factor reflects true performance - ✅ Backward compatible: handles positions without tracking fields ## Testing - ✅ Compiles successfully - ⚠️ Requires validation with live partial_close scenarios ## Code Changes ``` logger/decision_logger.go: - Lines 420-430: Add tracking fields to openPositions - Lines 441-534: Implement partial_close aggregation logic - Lines 536-593: Update full close to include accumulated PnL - Lines 246-250: Fix GetStatistics() to exclude partial_close ``` * fix(ui): prevent system_prompt_template overwrite when value is empty string ## Problem When editing trader configuration, if `system_prompt_template` was set to an empty string (""), the UI would incorrectly treat it as falsy and overwrite it with 'default', losing the user's selection. **Root cause:** ```tsx if (traderData && !traderData.system_prompt_template) { // ❌ This triggers for both undefined AND empty string "" setFormData({ system_prompt_template: 'default' }); } ``` JavaScript falsy values that trigger `!` operator: - `undefined` ✅ Should trigger default - `null` ✅ Should trigger default - `""` ❌ Should NOT trigger (user explicitly chose empty) - `false`, `0`, `NaN` (less relevant here) ## Solution Change condition to explicitly check for `undefined`: ```tsx if (traderData && traderData.system_prompt_template === undefined) { // ✅ Only triggers for truly missing field setFormData({ system_prompt_template: 'default' }); } ``` ## Impact - ✅ Empty string selections are preserved - ✅ Legacy data (undefined) still gets default value - ✅ User's explicit choices are respected - ✅ No breaking changes to existing functionality ## Testing - ✅ Code compiles - ⚠️ Requires manual UI testing: - [ ] Edit trader with empty system_prompt_template - [ ] Verify it doesn't reset to 'default' - [ ] Create new trader → should default to 'default' - [ ] Edit old trader (undefined field) → should default to 'default' ## Code Changes ``` web/src/components/TraderConfigModal.tsx: - Line 99: Changed !traderData.system_prompt_template → === undefined ``` * fix(trader): add missing HyperliquidTestnet configuration in loadSingleTrader 修复了 loadSingleTrader 函数中缺失的 HyperliquidTestnet 配置项, 确保 Hyperliquid 交易所的测试网配置能够正确传递到 trader 实例。 Changes: - 在 loadSingleTrader 中添加 HyperliquidTestnet 字段配置 - 代码格式优化(空格对齐) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: tinkle-community <tinklefund@gmail.com> * fix(trader): separate stop-loss and take-profit order cancellation to prevent accidental deletions ## Problem When adjusting stop-loss or take-profit levels, `CancelStopOrders()` deleted BOTH stop-loss AND take-profit orders simultaneously, causing: - **Adjusting stop-loss** → Take-profit order deleted → Position has no exit plan ❌ - **Adjusting take-profit** → Stop-loss order deleted → Position unprotected ❌ **Root cause:** ```go CancelStopOrders(symbol) { // Cancelled ALL orders with type STOP_MARKET or TAKE_PROFIT_MARKET // No distinction between stop-loss and take-profit } ``` ## Solution ### 1. Added new interface methods (trader/interface.go) ```go CancelStopLossOrders(symbol string) error // Only cancel stop-loss orders CancelTakeProfitOrders(symbol string) error // Only cancel take-profit orders CancelStopOrders(symbol string) error // Deprecated (cancels both) ``` ### 2. Implemented for all 3 exchanges **Binance (trader/binance_futures.go)**: - `CancelStopLossOrders`: Filters `OrderTypeStopMarket | OrderTypeStop` - `CancelTakeProfitOrders`: Filters `OrderTypeTakeProfitMarket | OrderTypeTakeProfit` - Full order type differentiation ✅ **Hyperliquid (trader/hyperliquid_trader.go)**: - ⚠️ Limitation: SDK's OpenOrder struct doesn't expose trigger field - Both methods call `CancelStopOrders` (cancels all pending orders) - Trade-off: Safe but less precise **Aster (trader/aster_trader.go)**: - `CancelStopLossOrders`: Filters `STOP_MARKET | STOP` - `CancelTakeProfitOrders`: Filters `TAKE_PROFIT_MARKET | TAKE_PROFIT` - Full order type differentiation ✅ ### 3. Usage in auto_trader.go When `update_stop_loss` or `update_take_profit` actions are implemented, they will use: ```go // update_stop_loss: at.trader.CancelStopLossOrders(symbol) // Only cancel SL, keep TP at.trader.SetStopLoss(...) // update_take_profit: at.trader.CancelTakeProfitOrders(symbol) // Only cancel TP, keep SL at.trader.SetTakeProfit(...) ``` ## Impact - ✅ Adjusting stop-loss no longer deletes take-profit - ✅ Adjusting take-profit no longer deletes stop-loss - ✅ Backward compatible: `CancelStopOrders` still exists (deprecated) - ⚠️ Hyperliquid limitation: still cancels all orders (SDK constraint) ## Testing - ✅ Compiles successfully across all 3 exchanges - ⚠️ Requires live testing: - [ ] Binance: Adjust SL → verify TP remains - [ ] Binance: Adjust TP → verify SL remains - [ ] Hyperliquid: Verify behavior with limitation - [ ] Aster: Verify order filtering works correctly ## Code Changes ``` trader/interface.go: +9 lines (new interface methods) trader/binance_futures.go: +133 lines (3 new functions) trader/hyperliquid_trader.go: +56 lines (3 new functions) trader/aster_trader.go: +157 lines (3 new functions) Total: +355 lines ``` * fix(binance): initialize dual-side position mode to prevent code=-4061 errors ## Problem When opening positions with explicit `PositionSide` parameter (LONG/SHORT), Binance API returned **code=-4061** error: ``` "No need to change position side." "code":-4061 ``` **Root cause:** - Binance accounts default to **single-side position mode** ("One-Way Mode") - In this mode, `PositionSide` parameter is **not allowed** - Code使用了 `PositionSide` 參數 (LONG/SHORT),但帳戶未啟用雙向持倉模式 **Position Mode Comparison:** | Mode | PositionSide Required | Can Hold Long+Short Simultaneously | |------|----------------------|------------------------------------| | One-Way (default) | ❌ No | ❌ No | | Hedge Mode | ✅ **Required** | ✅ Yes | ## Solution ### 1. Added setDualSidePosition() function Automatically enables Hedge Mode during trader initialization: ```go func (t *FuturesTrader) setDualSidePosition() error { err := t.client.NewChangePositionModeService(). DualSide(true). // Enable Hedge Mode Do(context.Background()) if err != nil { // Ignore "No need to change" error (already in Hedge Mode) if strings.Contains(err.Error(), "No need to change position side") { log.Printf("✓ Account already in Hedge Mode") return nil } return err } log.Printf("✓ Switched to Hedge Mode") return nil } ``` ### 2. Called in NewFuturesTrader() Runs automatically when creating trader instance: ```go func NewFuturesTrader(apiKey, secretKey string) *FuturesTrader { trader := &FuturesTrader{...} // Initialize Hedge Mode if err := trader.setDualSidePosition(); err != nil { log.Printf("⚠️ Failed to set Hedge Mode: %v", err) } return trader } ``` ## Impact - ✅ Prevents code=-4061 errors when opening positions - ✅ Enables simultaneous long+short positions (if needed) - ✅ Fails gracefully if account already in Hedge Mode - ⚠️ **One-time change**: Once enabled, cannot revert to One-Way Mode with open positions ## Testing - ✅ Compiles successfully - ⚠️ Requires Binance testnet/mainnet validation: - [ ] First initialization → switches to Hedge Mode - [ ] Subsequent initializations → ignores "No need to change" error - [ ] Open long position with PositionSide=LONG → succeeds - [ ] Open short position with PositionSide=SHORT → succeeds ## Code Changes ``` trader/binance_futures.go: - Line 3-12: Added strings import - Line 33-47: Modified NewFuturesTrader() to call setDualSidePosition() - Line 49-69: New function setDualSidePosition() Total: +25 lines ``` ## References - Binance Futures API: https://binance-docs.github.io/apidocs/futures/en/#change-position-mode-trade - Error code=-4061: "No need to change position side." - PositionSide ENUM: BOTH (One-Way) | LONG | SHORT (Hedge Mode) * fix(prompts): rename actions to match backend implementation ## Problem Backend code expects these action names: - `open_long`, `open_short`, `close_long`, `close_short` But prompts use outdated names: - `buy_to_enter`, `sell_to_enter`, `close` This causes all trading decisions to fail with unknown action errors. ## Solution Minimal changes to fix action name compatibility: ### prompts/nof1.txt - ✅ `buy_to_enter` → `open_long` - ✅ `sell_to_enter` → `open_short` - ✅ `close` → `close_long` / `close_short` - ✅ Explicitly list `wait` action - +18 lines, -6 lines (only action definitions section) ### prompts/adaptive.txt - ✅ `buy_to_enter` → `open_long` - ✅ `sell_to_enter` → `open_short` - ✅ `close` → `close_long` / `close_short` - +15 lines, -6 lines (only action definitions section) ## Impact - ✅ Trading decisions now execute successfully - ✅ Maintains all existing functionality - ✅ No new features added (minimal diff) ## Verification ```bash # Backend expects these actions: grep 'Action string' decision/engine.go # "open_long", "open_short", "close_long", "close_short", ... # Old names removed: grep -r "buy_to_enter\|sell_to_enter" prompts/ # (no results) ``` 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: tinkle-community <tinklefund@gmail.com> * fix(api): add balance sync endpoint with smart detection ## Summary - Add POST /traders/:id/sync-balance endpoint (Option B) - Add smart detection showing balance change percentage (Option C) - Fix balance display bug caused by commit |
||
|
|
f1e2eadd66 |
ci(docker): 添加Docker镜像构建和推送的GitHub Actions工作流 (#124)
* ci(docker): 添加Docker镜像构建和推送的GitHub Actions工作流 - 支持在main和develop分支及版本标签的push事件触发 - 支持Pull Request事件及手动触发工作流 - 配置了backend和frontend两个镜像的构建策略 - 使用QEMU和Docker Buildx实现多平台构建(amd64和arm64) - 集成GitHub Container Registry和Docker Hub登录 - 自动生成镜像元数据和多标签支持 - 支持基于GitHub Actions缓存提升构建速度 - 实现根据事件类型自动决定是否推送镜像 - 输出构建完成的镜像摘要信息 * Update Docker Hub login condition in workflow * Fix Docker Hub login condition in workflow * Simplify Docker Hub login step Removed conditional check for Docker Hub username. * Change branch names in Docker build workflow * Update docker-build.yml |
||
|
|
43816cc073 | Fix PR tpl | ||
|
|
c851e1c7cd |
feat(templates): add intelligent PR template selection system
- Created specialized PR templates for different change types: - Backend template for Go/API changes - Frontend template for UI/UX changes - Documentation template for docs updates - General template for mixed changes - Simplified default template from 270 to 115 lines - Added GitHub Action for automatic template suggestion based on file types - Auto-labels PRs with appropriate categories (backend/frontend/documentation) - Provides friendly suggestions when default template is used 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: tinkle-community <tinklefund@gmail.com> |
||
|
|
3843ed4842 |
Merge pull request #389 from NoFxAiOS/beta
Fix:fix the main branch history issue from November 3rd. |
||
|
|
9a2991fd92 | Fix owner | ||
|
|
f92d0cbe83 | fix owner | ||
|
|
0fb9fa8a2e | fix(readme): update readme and pr reviewer | ||
|
|
18d648a411 | Fix PR check | ||
|
|
98d3466836 |
Revert "Merge pull request #229 from xqliu/test/add-ut-infrastructure"
This reverts commit |
||
|
|
d6daad5708 |
Merge pull request #229 from xqliu/test/add-ut-infrastructure
test: Add minimal UT infrastructure and fix Issue #227 |
||
|
|
3a62c817b1 | fix comment | ||
|
|
972e5fb21a | Fix validation logic | ||
|
|
8caffefe54 | Fix validation | ||
|
|
fe25327ada | Fix backend check | ||
|
|
7d1b1b9245 | Fix validation error | ||
|
|
397df5e386 | fix(workflow): fix github workflow | ||
|
|
7171ea3912 | Change permissions from read to write for contents | ||
|
|
26a170935a |
Merge pull request #226 from xqliu/docs/enhance-bug-report-template
docs: Enhance bug report template and add troubleshooting guide |
||
|
|
3218c8dfcf |
fix(ci): Add comprehensive permissions to pr-checks workflow
Add workflow-level default permissions and explicit per-job permissions following the principle of least privilege: Workflow-level (default): - contents: read - Read repository contents - pull-requests: write - Manage PR labels and comments - issues: write - Manage issues (PRs are issues in GitHub API) Job-level overrides: - validate-pr: Inherits workflow defaults (needs issue/PR write access) - backend-tests: Downgrade to read-only (no write operations needed) - frontend-tests: Downgrade to read-only (no write operations needed) - auto-label: Add missing issues:write (labeler operates on PR issues) - security-check: Add security-events:write (upload SARIF results) - secrets-check: Downgrade to read-only (scanning only) - all-checks: Downgrade to read-only (status checking only) This fixes: 1. Potential 403 errors when auto-label tries to add labels to PR issues 2. Missing permission for uploading security scan results 3. Overly permissive access for read-only jobs Related: #282 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: tinkle-community <tinklefund@gmail.com> |
||
|
|
1fdf8142da |
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) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: tinkle-community <tinklefund@gmail.com> |
||
|
|
8d172d0993 | fix: github workflow permission | ||
|
|
b27bad4d74 |
docs: Enhance bug report template and add comprehensive troubleshooting guide
- Enhanced bug report template with detailed log capture instructions - Added bug categorization system (6 main categories) - Frontend error capture guide (DevTools Console/Network tabs) - Backend log capture for Docker and PM2 deployments - Trading/decision logs location and usage - Comprehensive environment information checklist - Quick diagnostic tips for faster issue resolution - Created bilingual troubleshooting guides (EN/ZH) - Common trading issues (e.g., Issue #202: only short positions) - Detailed explanation of Binance position mode requirements - AI decision problems and diagnostics - Connection and API error solutions - Frontend and database issues - Complete log capture instructions with commands - Emergency reset procedures - Updated documentation cross-references - Added troubleshooting guide links to bug report template - Added links in README Common Issues section - Bilingual support for better accessibility This reduces maintainer workload by helping users self-diagnose issues and submit higher-quality bug reports with all necessary information. Addresses Issue #202 root cause documentation. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: tinkle-community <tinklefund@gmail.com> |
||
|
|
a1bf54b952 | feat: pr validation | ||
|
|
2351bb95c3 |
Feat: Update docs
- 重构文档结构 - 更新文档内容 - 制定roadmap - 提供中/EN 双语文档 |
||
|
|
fefb2b7424 |
Docs: Add bounty templates for Hyperliquid and Aster exchange integration
Add comprehensive bounty documentation to recruit contributors for exchange integrations: **New Files:** - `.github/ISSUE_TEMPLATE/feature_request.md` - GitHub Issue template - `INTEGRATION_BOUNTY_HYPERLIQUID.md` - Complete Hyperliquid integration spec - `INTEGRATION_BOUNTY_ASTER.md` - Complete Aster integration spec - `HOW_TO_POST_BOUNTY.md` - Step-by-step guide for posting bounties **Bounty Documentation Includes:** - Clear task requirements and acceptance criteria - Technical specifications and interface definitions - File structure and implementation guidelines - Testing and documentation requirements - Contribution workflow - Support resources and community links **HOW_TO_POST_BOUNTY.md Guide:** - Two methods to post GitHub Issues (Web UI + GitHub CLI) - Bounty platform recommendations (Gitcoin, Bountysource, IssueHunt) - Social media promotion templates (Twitter, Telegram, Reddit) - Issue management best practices - Legal and quality control considerations **Benefits:** - Standardized contribution process - Clear technical requirements - Professional bounty presentation - Easy for maintainers to post and manage - Attractive for potential contributors Ready to recruit developers for multi-exchange support! 🚀 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: tinkle-community <tinklefund@gmail.com> |