Commit Graph

105 Commits

Author SHA1 Message Date
tinkle-community 2d272bb7b8 feat: migrate store layer to GORM with PostgreSQL support
- Migrate all store packages from raw database/sql to GORM ORM
- Add PostgreSQL support alongside SQLite
- Move EncryptedString type to crypto package for cleaner architecture
- Add automatic encryption/decryption for sensitive fields (API keys, secrets)
- Fix PostgreSQL AutoMigrate conflicts by skipping existing tables
- Fix duplicate /klines route registration
- Update tests to use GORM database connections
- Add database configuration support in config package
2026-01-01 19:32:49 +08:00
tinkle-community d547863ebb feat: add SQLite/PostgreSQL database switching support 2026-01-01 15:25:30 +08:00
tinkle-community 74adedbc64 feat: improve landing page UI and add pprof port mapping 2026-01-01 13:09:54 +08:00
tinkle-community 47bff87966 feat: add xyz dex balance calculation, market data providers, and UI improvements
- Fix xyz dex balance calculation (use marginSummary for isolated margin)
- Add Alpaca provider for US stocks market data
- Add TwelveData provider for forex & metals market data
- Add Hyperliquid kline provider
- Centralize API keys in config system
- Add builder fee for order routing
- Improve chart UI with compact design
- Fix position history fee display precision
- Add comprehensive balance calculation tests
2025-12-29 22:16:48 +08:00
tinkle-community d74867c220 feat: add position history API and frontend integration
- Add /positions/history API endpoint
- Add position history types and API client
- Add translations for position history page
- Integrate PositionHistory component in App
2025-12-28 21:05:18 +08:00
tinkle-community 0f3ba1382a feat: use coinank free API for kline data and show exchange badge
- Switch to coinank free/open kline API (no authentication required)
- Add exchange badge display with brand colors (Binance/Bybit/OKX/Hyperliquid/Aster)
- Auto-convert OKX symbol format (BTCUSDT -> BTC-USDT-SWAP)
- Fallback to Binance data for unsupported exchanges (Bitget/Lighter)
- Pass exchange prop from trader account to chart component
2025-12-27 23:35:15 +08:00
tinkle-community 8fb0d2e7e9 feat: order sync for multiple exchanges and position tracking improvements
- Add order sync support for Binance, Hyperliquid, Bybit, OKX, Bitget, Aster exchanges
- Fix weighted average exit price calculation for partial closes
- Handle position flip (翻仓) scenarios correctly
- Fix symbol normalization (ETH vs ETHUSDT)
- Skip order recording for exchanges with OrderSync to avoid duplicates
- Add chart timezone localization
2025-12-27 19:13:04 +08:00
tinkle-community 1744e7f38e feat: migrate to CoinAnk API and improve chart UI
- Chart improvements: professional styling, popular symbols quick selection, simplified B/S legend
- Data source migration: use CoinAnk API exclusively for all kline data
- Code cleanup: remove Binance WebSocket cache and related code (websocket_client.go, combined_streams.go, monitor.go)
- Log optimization: reduce hook spam, suppress 404 errors, increase P&L diff threshold
- Lighter integration: add order sync functionality, fix market order precision
- Remove ticker merge logic for simplicity
2025-12-26 00:58:12 +08:00
tinkle-community b169fcd3d2 feat: add time period selector to competition chart (1D/3D/7D/30D/All) 2025-12-17 03:51:21 +08:00
tinkle-community 3f084005e4 feat: upgrade Binance to Algo Order API and improve trading flow
- Upgrade go-binance to v2.8.9 with new Algo Order API
- Migrate SetStopLoss/SetTakeProfit to use AlgoOrderTypeStopMarket/TakeProfitMarket
- Update cancel functions to handle both legacy and Algo orders
- Fix Lighter stop orders using correct order types (type=2/4) with TriggerPrice
- Add CancelAllOrders before opening positions for Bybit and Lighter
- Fix decision limit selector in API handler
- Add stop_loss/take_profit/confidence fields to DecisionAction
- Store decisions array in database with proper serialization
- Redesign DecisionCard with beautiful entry/SL/TP display
2025-12-15 21:22:22 +08:00
tinkle-community 4725548a55 feat: fix Lighter V2 integration and improve error handling
- Fix Lighter API field name mismatches (position/size, avg_entry_price/entry_price, sign/side)
- Fix GetBalance return format to match standard fields (totalWalletBalance, totalUnrealizedProfit)
- Fix GetPositions return format to match standard fields (positionAmt, markPrice, unRealizedProfit)
- Add API Key Index field to frontend with explanation
- Update Lighter referral link
- Disable Lighter testnet (mainnet only)
- Add load error tracking for better error messages
- Remove old Lighter V1 implementation files
- Remove test credentials from test files
2025-12-14 20:50:10 +08:00
tinkle-community 1e135ea9c3 feat: redesign backtest module UI and fix 404 issue
- Fix backtest API 404 by registering routes in setupRoutes()
- Redesign BacktestPage with 3-step wizard configuration
- Add progress ring visualization with animation
- Add equity chart with trade markers using Recharts
- Add trade timeline with card-style display
- Add stats cards for equity, return, drawdown, sharpe
- Add tab navigation for overview/chart/trades/decisions
- Improve run history list with status icons
- Add lightweight-charts dependency (for future use)
2025-12-14 00:23:51 +08:00
tinkle-community dcc16fec82 feat: add Bitget futures trading support
- Add BitgetTrader with full trading implementation
- Support one-way position mode with proper API parameters
- Add Bitget to all exchange switch statements
- Update exchange icons (Bybit, OKX, Bitget, Lighter)
- Add Bitget to frontend exchange config modal
2025-12-12 18:59:09 +08:00
tinkle-community cc390706d0 feat: add OI ranking data support and fix trader config update issues
- Add OI ranking data fetching and formatting for AI prompts
- Fix trader update not saving strategy_id, ai_model_id, initial_balance
- Fix AI API key not set for non-qwen/deepseek providers
- Add strategy_id to trader config API response
- Remove old trader from memory before reloading on update
- Clean up unused useTraderActions.ts
2025-12-12 16:08:21 +08:00
tinkle-community f5ae22d85c feat: add debate arena and fix multiple issues
- Add AI debate arena for multi-AI trading decisions
- Fix debate consensus calculation and display
- Fix vote parsing to support both <decision> and <final_vote> tags
- Fix JSON field name compatibility (stop_loss/stop_loss_pct)
- Fix symbol validation to prevent AI hallucinating invalid symbols
- Fix Bybit position side display (was uppercase, now lowercase for consistency)
- Fix NOFX logo navigation to home page
- Add detailed logging for debugging trade execution
2025-12-12 11:24:32 +08:00
tinkle-community e5703ffab6 feat: add Grok, OpenAI, Claude, Gemini, Kimi AI providers
- Add new MCP clients for Grok (xAI), OpenAI, Claude, Gemini, Kimi
- Update auto_trader, backtest, and strategy to support all providers
- Add provider icons and fix SVG gradient conflicts
- Add API application links and hints in model config modal
- Show model version in AI model list cards
- Add Chinese/English translations for provider hints
- Remove deprecated traders component files
2025-12-11 15:16:59 +08:00
tinkle-community 78b5e73966 fix: competition chart data sync and display issues
- Add real-time data point to equity history API for chart/leaderboard consistency
- Fix chart legend showing 0% by finding each trader's last available data point
- Use consistent timestamp for all real-time data points in batch requests
- Increase chart trader limit from 5 to 10
- Remove Mini Stats Bar trader limit
2025-12-11 12:32:04 +08:00
tinkle-community 19937ee260 fix: improve trading and UI 2025-12-11 00:47:53 +08:00
tinkle-community ecbedc6525 fix: OKX trading issues and improve position tracking
- Add maxMktSz check for OKX market orders to prevent exceeding limits
- Increase margin safety buffer (0.1% fee + 1% buffer) for all exchanges
- Fix Binance position closure detection with direct trade queries
- Move Recent Completed Trades before Current Positions in AI prompt
- Update README screenshots with table layout for better alignment
2025-12-10 22:01:57 +08:00
tinkle-community 319ccb8ca3 fix: initial balance calculation and UI improvements
- Fix initial balance using available_balance instead of total_equity
- Fix WSMonitor nil pointer by starting market monitor before loading traders
- Add strategy name display on traders list and dashboard pages
- Various position sync and trading improvements
2025-12-10 14:40:08 +08:00
tinkle-community 8be44cdf6e fix: return default models and exchanges when database is empty
API now returns default AI models (deepseek, qwen, openai, claude, gemini, grok) and exchanges (binance, bybit, okx, hyperliquid, aster, lighter) when database has no data.
2025-12-09 21:11:51 +08:00
tinkle-community 6546264df9 fix: backend respect TRANSPORT_ENCRYPTION config for model/exchange updates 2025-12-09 19:30:00 +08:00
tinkle-community c720d663f1 feat: add TRANSPORT_ENCRYPTION toggle for easier deployment
- Add TRANSPORT_ENCRYPTION env config (default: false)
- Allow HTTP/IP access when transport encryption is disabled
- Add /api/crypto/config endpoint to expose encryption status
- Update WebCryptoEnvironmentCheck with 'disabled' status
- Update ExchangeConfigModal and AITradersPage to allow form submission when disabled
- Add i18n translations for disabled status (EN/CN)
- Update README with two deployment modes documentation
2025-12-09 18:04:42 +08:00
tinkle-community 9fa2432705 feat: improve strategy studio and fix trader deletion bug
- Add strategy export/import functionality to Strategy Studio
- Fix trader deletion not removing from memory (competition page ghost data)
- Simplify TraderConfigViewModal: remove unused fields, show strategy name
- Improve quant data formatting: OI/Netflow multi-timeframe display
- Add configurable OI/Netflow toggles in indicator settings
- Clean up unused frontend components and dead code
2025-12-09 16:46:58 +08:00
tinkle-community e55a6a6ff4 feat: fix competition chart with accurate PnL calculation and improved UI
Backend:
- Add GetByID method to TraderStore for fetching trader without userID
- Calculate total_pnl_pct in equity history API using initial_balance
- Falls back to first snapshot equity if initial_balance not set

Frontend (ComparisonChart):
- Redesign with modern UI: gradient fills, glow effects, rounded corners
- Add mini stats bar showing all traders with current PnL
- Improved tooltip with date, time, and trend icons
- Better Y-axis domain calculation ensuring zero is visible
- Bottom stats grid: Leader, Lead PnL, Gap, Data Points
- Use ComposedChart with Area + Line for visual depth
- Animated loading state with spinning indicator
2025-12-08 13:36:52 +08:00
tinkle-community 4a0f56f1ee refactor: remove database pre-population and add i18n strategy templates
- Remove initDefaultData() for exchanges, ai_models, strategies tables
- Change supported exchanges/models API to return static lists
- Add GetDefaultStrategyConfig(lang) with Chinese/English prompt templates
- Frontend passes language parameter when creating new strategy
2025-12-08 02:37:29 +08:00
tinkle-community d780c2a988 refactor: simplify log format 2025-12-08 02:13:58 +08:00
tinkle-community a12c0ae8c9 refactor: standardize code comments 2025-12-08 01:43:22 +08:00
tinkle-community 2334d78e4a refactor: simplify config and remove unused database tables
- Remove system_config, beta_codes, signal_source tables and related code
- Simplify config.go to only read from .env (APIServerPort, JWTSecret, RegistrationEnabled)
- Remove GetCustomCoins, use all USDT perpetual contracts for WSMonitor
- Add trader_equity_snapshots table for equity tracking
- Remove signal source modal from frontend AITradersPage
- Fix WSMonitor nil panic by restoring initialization in main.go
2025-12-07 20:17:03 +08:00
tinkle-community a77c54dbef feat: add one-click close position for all exchanges
- Add handleClosePosition API endpoint in server.go
- Add closePosition API function in frontend
- Add close position button to positions table in App.tsx and TraderDashboard.tsx
- Fix GetFullConfig to include passphrase field for OKX
- Fix OKX CloseLong/CloseShort to use position quantity directly (already in contracts)
2025-12-06 19:16:37 +08:00
tinkle-community 1e5ece947c Feature/okx trading (#1177)
* feat: add OKX exchange trading support
- Add OKX trader client with full trading API integration
- Support API Key, Secret Key, and Passphrase authentication
- Add OKX icon and frontend configuration modal
- Update exchange store and types for OKX fields
* fix: add passphrase column migration and fix exchange type mapping
* fix: show OKX input fields in exchange config modal
* fix: ensure all supported exchanges exist for user when listing
* fix: simplify exchange type check condition for OKX
* debug: add visible debug info for exchange id
* fix: remove debug info from exchange config modal
* fix: add OKX to exchange type condition in AITradersPage
* feat: complete OKX trading support and fix exchange config issues
- Add LIGHTER exchange UI support in AITradersPage
- Add passphrase field to UpdateExchangeConfigRequest type
- Fix OKX HTTP client to bypass proxy (disable system proxy)
- Auto-fetch initial balance from exchange when not set
- Support multiple balance field names for different exchanges
- Add detailed error messages when trader fails to load
- Add lighter_api_key_private_key field to exchange store
2025-12-06 18:04:59 +08:00
tinkle-community 5cff32e4f2 Feature/custom strategy (#1172)
* feat: add Strategy Studio with multi-timeframe support
- Add Strategy Studio page with three-column layout for strategy management
- Support multi-timeframe K-line data selection (5m, 15m, 1h, 4h, etc.)
- Add GetWithTimeframes() function in market package for fetching multiple timeframes
- Add TimeframeSeriesData struct for storing per-timeframe technical indicators
- Update formatMarketData() to display all selected timeframes in AI prompt
- Add strategy API endpoints for CRUD operations and test run
- Integrate real AI test runs with configured AI models
- Support custom AI500 and OI Top API URLs from strategy config
* docs: add Strategy Studio screenshot to README files
* fix: correct strategy-studio.png filename case in README
* refactor: remove legacy signal source config and simplify trader creation
- Remove signal source configuration from traders page (now handled by strategy)
- Remove advanced options (legacy config) from TraderConfigModal
- Rename default strategy to "默认山寨策略" with AI500 coin pool URL
- Delete SignalSourceModal and SignalSourceWarning components
- Clean up related stores, hooks, and page components
2025-12-06 07:20:11 +08:00
tinkle-community f4ece051e7 Refactor/trading actions (#1169)
* refactor: 简化交易动作,移除 update_stop_loss/update_take_profit/partial_close
- 移除 Decision 结构体中的 NewStopLoss, NewTakeProfit, ClosePercentage 字段
- 删除 executeUpdateStopLossWithRecord, executeUpdateTakeProfitWithRecord, executePartialCloseWithRecord 函数
- 简化 logger 中的 partial_close 聚合逻辑
- 更新 AI prompt 和验证逻辑,只保留 6 个核心动作
- 清理相关测试代码
保留的交易动作: open_long, open_short, close_long, close_short, hold, wait
* refactor: 移除 AI学习与反思 模块
- 删除前端 AILearning.tsx 组件和相关引用
- 删除后端 /performance API 接口
- 删除 logger 中 AnalyzePerformance、calculateSharpeRatio 等函数
- 删除 PerformanceAnalysis、TradeOutcome、SymbolPerformance 等结构体
- 删除 Context 中的 Performance 字段
- 移除 AI prompt 中夏普比率自我进化相关内容
- 清理 i18n 翻译文件中的相关条目
该模块基于磁盘存储计算,经常出错,做减法移除
* refactor: 将数据库操作统一迁移到 store 包
- 新增 store/ 包,统一管理所有数据库操作
  - store.go: 主 Store 结构,懒加载各子模块
  - user.go, ai_model.go, exchange.go, trader.go 等子模块
  - 支持加密/解密函数注入 (SetCryptoFuncs)
- 更新 main.go 使用 store.New() 替代 config.NewDatabase()
- 更新 api/server.go 使用 *store.Store 替代 *config.Database
- 更新 manager/trader_manager.go:
  - 新增 LoadTradersFromStore, LoadUserTradersFromStore 方法
  - 删除旧版 LoadUserTraders, LoadTraderByID, loadSingleTrader 等方法
  - 移除 nofx/config 依赖
- 删除 config/database.go 和 config/database_test.go
- 更新 api/server_test.go 使用 store.Trader 类型
- 清理 logger/ 包中未使用的 telegram 相关代码
* refactor: unify encryption key management via .env
- Remove redundant EncryptionManager and SecureStorage
- Simplify CryptoService to load keys from environment variables only
  - RSA_PRIVATE_KEY: RSA private key for client-server encryption
  - DATA_ENCRYPTION_KEY: AES-256 key for database encryption
  - JWT_SECRET: JWT signing key for authentication
- Update start.sh to auto-generate missing keys on first run
- Remove secrets/ directory and file-based key storage
- Delete obsolete encryption setup scripts
- Update .env.example with all required keys
* refactor: unify logger usage across mcp package
- Add MCPLogger adapter in logger package to implement mcp.Logger interface
- Update mcp/config.go to use global logger by default
- Remove redundant defaultLogger from mcp/logger.go
- Keep noopLogger for testing purposes
* chore: remove leftover test RSA key file
* chore: remove unused bootstrap package
* refactor: unify logging to use logger package instead of fmt/log
- Replace all fmt.Print/log.Print calls with logger package
- Add auto-initialization in logger package init() for test compatibility
- Update main.go to initialize logger at startup
- Migrate all packages: api, backtest, config, decision, manager, market, store, trader
* refactor: rename database file from config.db to data.db
- Update main.go, start.sh, docker-compose.yml
- Update migration script and documentation
- Update .gitignore and translations
* fix: add RSA_PRIVATE_KEY to docker-compose environment
* fix: add registration_enabled to /api/config response
* fix: Fix navigation between login and register pages
Use window.location.href instead of react-router's navigate() to fix
the issue where URL changes but the page doesn't reload due to App.tsx
using custom route state management.
* fix: Switch SQLite from WAL to DELETE mode for Docker compatibility
WAL mode causes data sync issues with Docker bind mounts on macOS due
to incompatible file locking mechanisms between the container and host.
DELETE mode (traditional journaling) ensures data is written directly
to the main database file.
* refactor: Remove default user from database initialization
The default user was a legacy placeholder that is no longer needed now
that proper user registration is in place.
* feat: Add order tracking system with centralized status sync
- Add trader_orders table for tracking all order lifecycle
- Implement GetOrderStatus interface for all exchanges (Binance, Bybit, Hyperliquid, Aster, Lighter)
- Create OrderSyncManager for centralized order status polling
- Add trading statistics (Sharpe ratio, win rate, profit factor) to AI context
- Include recent completed orders in AI decision input
- Remove per-order goroutine polling in favor of global sync manager
* feat: Add TradingView K-line chart to dashboard
- Create TradingViewChart component with exchange/symbol selectors
- Support Binance, Bybit, OKX, Coinbase, Kraken, KuCoin exchanges
- Add popular symbols quick selection
- Support multiple timeframes (1m to 1W)
- Add fullscreen mode
- Integrate with Dashboard page below equity chart
- Add i18n translations for zh/en
* refactor: Replace separate charts with tabbed ChartTabs component
- Create ChartTabs component with tab switching between equity curve and K-line
- Add embedded mode support for EquityChart and TradingViewChart
- User can now switch between account equity and market chart in same area
* fix: Use ChartTabs in App.tsx and fix embedded mode in EquityChart
- Replace EquityChart with ChartTabs in App.tsx (the actual dashboard renderer)
- Fix EquityChart embedded mode for error and empty data states
- Rename interval state to timeInterval to avoid shadowing window.setInterval
- Add debug logging to ChartTabs component
* feat: Add position tracking system for accurate trade history
- Add trader_positions table to track complete open/close trades
- Add PositionSyncManager to detect manual closes via polling
- Record position on open, update on close with PnL calculation
- Use positions table for trading stats and recent trades (replacing orders table)
- Fix TradingView chart symbol format (add .P suffix for futures)
- Fix DecisionCard wait/hold action color (gray instead of red)
- Auto-append USDT suffix for custom symbol input
* update
---------
2025-12-06 01:04:26 +08:00
tinkle-community 1dab5ef2ee Revert "feat: 添加 OKX 交易所支持 (#1150)"
This reverts commit 174f59b90721572dcdd03a9527fa86a48395018c.
2025-12-03 11:31:50 +08:00
0xYYBB | ZYY | Bobo 62bce32d1f feat: 添加 OKX 交易所支持 (#1150)
* feat: 添加 OKX 交易所支持(USDT Perpetual Swap)
## 新增功能
- 實現完整的 OKX API v5 REST 客戶端(純 Go 標準庫,無外部依賴)
- 支持 USDT 永續合約交易(BTC-USDT-SWAP 等)
- 實現 Trader 接口的 13 個核心方法
## 技術細節
### trader/okx_trader.go (NEW)
- HMAC-SHA256 簽名機制(完全符合 OKX API v5 規範)
- 餘額和持倉緩存(15秒,參考 Binance 實現)
- 支持 Demo Trading(testnet 模式)
- Symbol 格式轉換(BTCUSDT ↔ BTC-USDT-SWAP)
- 全倉模式(Cross Margin)支持
- 自動槓桿設置
### 實現的接口方法:
-  GetBalance() - 獲取賬戶餘額
-  GetPositions() - 獲取所有持倉
-  OpenLong() / OpenShort() - 開倉
-  CloseLong() / CloseShort() - 平倉
-  SetLeverage() - 設置槓桿
-  SetMarginMode() - 設置保證金模式
-  GetMarketPrice() - 獲取市場價格
-  FormatQuantity() - 格式化數量
- ⚠️  止盈止損功能標記為 TODO(非核心交易功能)
### config/database.go (MODIFIED)
- 添加 "okx" 到預設交易所列表
- 新增 okx_passphrase 字段(OKX 需要 3 個認證參數)
- 更新 ExchangeConfig 結構
- 添加數據庫遷移語句(ALTER TABLE)
### api/server.go (MODIFIED)
- 在 handleCreateTrader() 添加 OKX 初始化邏輯
- switch case "okx" 分支
## 代碼品質
- 代碼行數:~450 行
- 外部依賴:0 個
- 編譯狀態: 通過
- 測試覆蓋:待實現(下一步)
## 待完成事項
- [ ] 撰寫單元測試(目標 >80% 覆蓋率)
- [ ] 完善數據庫查詢邏輯(GetExchanges 添加 OKX passphrase 掃描)
- [ ] 實現止盈止損功能(可選)
* refactor: 完善 OKX passphrase 數據庫和 API 支持
- config/database.go:
  • GetExchanges() 添加 okx_passphrase 查詢和解密
  • UpdateExchange() 函數簽名添加 okxPassphrase 參數
  • UpdateExchange() UPDATE 邏輯添加 okx_passphrase SET 子句
  • UpdateExchange() INSERT 添加 okx_passphrase 加密和列
- api/server.go:
  • UpdateExchangeConfigRequest 添加 OKXPassphrase 字段
  • UpdateExchange 調用添加 OKXPassphrase 參數
- api/utils.go:
  • SanitizeExchangeConfigForLog 添加 OKXPassphrase 脫敏
 編譯測試通過,OKX 完整功能支持完成
* test: 添加 OKX Trader 完整單元測試套件
📊 測試覆蓋率:92.6% (遠超 80% 目標)
 完成的測試:
- 接口兼容性測試
- NewOKXTrader 構造函數測試(5個場景)
- 符號格式轉換測試(5個場景)
- HMAC-SHA256 簽名一致性測試
- GetBalance 測試(含字段驗證)
- GetPositions 測試(含標準化數據驗證)
- GetMarketPrice 測試(3個場景)
- FormatQuantity 測試(5個場景)
- SetLeverage/SetMarginMode 測試
- OpenLong/OpenShort 測試
- CloseLong/CloseShort 測試
- 緩存機制測試
- 錯誤處理測試(API錯誤、網絡錯誤、JSON錯誤)
🔧 測試套件架構:
- OKXTraderTestSuite 繼承 TraderTestSuite
- Mock HTTP 服務器模擬 OKX API v5 響應
- 完整覆蓋所有公開方法
- 包含邊界條件和錯誤場景測試
📈 方法覆蓋率明細:
- request: 90.0%
- GetBalance: 97.0%
- GetPositions: 83.3%
- formatSymbol, OpenLong, OpenShort, CloseLong, CloseShort: 100%
- placeOrder, SetMarginMode, FormatQuantity, clearCache: 100%
- Cancel* 方法系列: 100%
- SetLeverage: 81.8%
- GetMarketPrice: 85.7%
---------
Co-authored-by: the-dev-z <the-dev-z@users.noreply.github.com>
Co-authored-by: Claude <noreply@anthropic.com>
2025-12-02 10:18:13 +08:00
0xYYBB | ZYY | Bobo 52e4ff6921 fix(bybit): complete Bybit integration by adding API layer support (#1149) 2025-12-02 05:00:20 +08:00
Professor-Chen c34a6c6bcf fix: resolve multiple bugs preventing trader creation (#1138)
* fix: resolve multiple bugs preventing trader creation
Bug fixes:
1. Fix time.Time scanning error - SQLite stores datetime as TEXT, now parsing manually
2. Fix foreign key mismatch - traders table referenced exchanges(id) but exchanges uses composite primary key (id, user_id)
3. Add missing backtestManager field to Server struct
4. Add missing Shutdown method to Server struct
5. Fix NewFuturesTrader call - pass userId parameter
6. Fix UpdateExchange call - pass all required parameters
7. Add migrateTradersTable() to fix existing databases
These issues prevented creating new traders with 500 errors.
* fix(api): fix balance extraction field name mismatch
Binance API returns 'availableBalance' (camelCase) but code was looking for
'available_balance' (snake_case). Now supports both formats.
Also added 'totalWalletBalance' as fallback for total balance extraction.
* fix(frontend): add missing ConfirmDialogProvider to App
The delete trader button required ConfirmDialogProvider to be wrapped
around the App component for the confirmation dialog to work.
---------
Co-authored-by: NOFX Trader <nofx@local.dev>
2025-11-30 12:22:20 +08:00
Rick 11b6c6ba3e Dev backtest (#1134) 2025-11-28 21:34:27 +08:00
0xYYBB | ZYY | Bobo e7e972a442 feat(lighter): 完整集成 LIGHTER DEX - SDK + 前端配置 UI (#1085)
* feat(trader): add LIGHTER DEX integration (initial implementation)
Add pure Go implementation of LIGHTER DEX trader following NOFX architecture
Features:
-  Account management with Ethereum wallet authentication
-  Order operations: market/limit orders, cancel, query
-  Position & balance queries
-  Zero-fee trading support (Standard accounts)
-  Up to 50x leverage for BTC/ETH
Implementation:
- Pure Go (no CGO dependencies) for easy deployment
- Based on hyperliquid_trader.go architecture
- Uses Ethereum ECDSA signatures (like Hyperliquid)
- API base URL: https://mainnet.zklighter.elliot.ai
Files:
- lighter_trader.go: Core trader structure & auth
- lighter_orders.go: Order management (create/cancel/query)
- lighter_account.go: Balance & position queries
Status: ⚠️ Partial implementation
-  Core structure complete
- ⏸️ Auth token generation needs implementation
- ⏸️ Transaction signing logic needs completion
- ⏸️ Config integration pending
Next steps:
1. Complete auth token generation
2. Add to config/exchange registry
3. Add frontend UI support
4. Create test suite
Co-Authored-By: tinkle-community <tinklefund@gmail.com>
* feat: Add LIGHTER DEX integration (快速整合階段)
## 🚀 新增功能
-  添加 LIGHTER DEX 作為第四個支持的交易所 (Binance, Hyperliquid, Aster, LIGHTER)
-  完整的數據庫配置支持(ExchangeConfig 新增 LighterWalletAddr, LighterPrivateKey 字段)
-  交易所註冊與初始化(initDefaultData 註冊 "lighter")
-  TraderManager 集成(配置傳遞邏輯完成)
-  AutoTrader 支持(NewAutoTrader 添加 "lighter" case)
## 📝 實現細節
### 後端整合
1. **數據庫層** (config/database.go):
   - ExchangeConfig 添加 LIGHTER 字段
   - 創建表時添加 lighter_wallet_addr, lighter_private_key 欄位
   - ALTER TABLE 語句用於向後兼容
   - UpdateExchange/CreateExchange/GetExchanges 支持 LIGHTER
   - migrateExchangesTable 支持 LIGHTER 字段
2. **API 層** (api/server.go, api/utils.go):
   - UpdateExchangeConfigRequest 添加 LIGHTER 字段
   - SanitizeExchangeConfigForLog 添加脫敏處理
3. **Trader 層** (trader/):
   - lighter_trader.go: 核心結構、認證、初始化
   - lighter_account.go: 餘額、持倉、市場價格查詢
   - lighter_orders.go: 訂單管理(創建、取消、查詢)
   - lighter_trading.go: 交易功能實現(開多/空、平倉、止損/盈)
   - 實現完整 Trader interface (13個方法)
4. **Manager 層** (manager/trader_manager.go):
   - addTraderFromDB 添加 LIGHTER 配置設置
   - AutoTraderConfig 添加 LIGHTER 字段
### 實現的功能(快速整合階段)
 基礎交易功能 (OpenLong, OpenShort, CloseLong, CloseShort)
 餘額查詢 (GetBalance, GetAccountBalance)
 持倉查詢 (GetPositions, GetPosition)
 訂單管理 (CreateOrder, CancelOrder, CancelAllOrders)
 止損/止盈 (SetStopLoss, SetTakeProfit, CancelStopLossOrders)
 市場數據 (GetMarketPrice)
 格式化工具 (FormatQuantity)
## ⚠️ TODO(完整實現階段)
- [ ] 完整認證令牌生成邏輯 (refreshAuthToken)
- [ ] 完整交易簽名邏輯(參考 Python SDK)
- [ ] 從 API 獲取幣種精度
- [ ] 區分止損/止盈訂單類型
- [ ] 前端 UI 支持
- [ ] 完整測試套件
Co-Authored-By: tinkle-community <tinklefund@gmail.com>
* feat: 完整集成 LIGHTER DEX with SDK
- 集成官方 lighter-go SDK (v0.0.0-20251104171447-78b9b55ebc48)
- 集成 Poseidon2 Goldilocks 簽名庫 (poseidon_crypto v0.0.11)
- 實現完整的 LighterTraderV2 使用官方 SDK
- 實現 17 個 Trader 接口方法(賬戶、交易、訂單管理)
- 支持雙密鑰系統(L1 錢包 + API Key)
- V1/V2 自動切換機制(向後兼容)
- 自動認證令牌管理(8小時有效期)
- 添加完整集成文檔 LIGHTER_INTEGRATION.md
新增文件:
- trader/lighter_trader_v2.go - V2 核心結構和初始化
- trader/lighter_trader_v2_account.go - 賬戶查詢方法
- trader/lighter_trader_v2_trading.go - 交易操作方法
- trader/lighter_trader_v2_orders.go - 訂單管理方法
- LIGHTER_INTEGRATION.md - 完整文檔
修改文件:
- trader/auto_trader.go - 添加 LighterAPIKeyPrivateKey 配置
- config/database.go - 添加 API Key 字段支持
- go.mod, go.sum - 添加 SDK 依賴
🤖 Generated with Claude Code
Co-Authored-By: tinkle-community <tinklefund@gmail.com>
* feat(lighter): 實現完整 HTTP 調用與動態市場映射
### 實現的功能
#### 1. submitOrder() - 真實訂單提交
- 使用 POST /api/v1/sendTx 提交已簽名訂單
- tx_type: 14 (CREATE_ORDER)
- 價格保護機制 (price_protection)
- 完整錯誤處理與響應解析
#### 2. GetActiveOrders() - 查詢活躍訂單
- GET /api/v1/accountActiveOrders
- 使用認證令牌 (Authorization header)
- 支持按市場索引過濾
#### 3. CancelOrder() - 真實取消訂單
- 使用 SDK 簽名 CancelOrderTxReq
- POST /api/v1/sendTx with tx_type: 15 (CANCEL_ORDER)
- 自動 nonce 管理
#### 4. getMarketIndex() - 動態市場映射
- 從 GET /api/v1/orderBooks 獲取市場列表
- 內存緩存 (marketIndexMap) 提高性能
- 回退到硬編碼映射(API 失敗時)
- 線程安全 (sync.RWMutex)
### 技術實現
**數據結構**:
- SendTxRequest/SendTxResponse - sendTx 請求響應
- MarketInfo - 市場信息緩存
**並發安全**:
- marketMutex - 保護市場索引緩存
- 讀寫鎖優化性能
**錯誤處理**:
- API 失敗回退機制
- 詳細日誌記錄
- HTTP 狀態碼驗證
### 測試
 編譯通過 (CGO_ENABLED=1)
 所有 Trader 接口方法實現完整
 HTTP 調用格式符合 LIGHTER API 規範
Co-Authored-By: tinkle-community <tinklefund@gmail.com>
* feat(lighter): 數據庫遷移與前端類型支持
### 數據庫變更
#### 新增欄位
- `exchanges.lighter_api_key_private_key` TEXT DEFAULT ''
- 支持 LIGHTER V2 的 40 字節 API Key 私鑰
#### 遷移腳本
- 📄 `migrations/002_add_lighter_api_key.sql`
- 包含完整的驗證和統計查詢
- 向後兼容現有配置(默認為空,使用 V1)
#### Schema 更新
- `config/database.go`:
  - 更新 CREATE TABLE 語句
  - 更新 exchanges_new 表結構
  - 新增 ALTER TABLE 遷移命令
### 前端類型更新
#### types.ts
- 新增 `Exchange` 接口字段:
  - `lighterWalletAddr?: string` - L1 錢包地址
  - `lighterPrivateKey?: string` - L1 私鑰
  - `lighterApiKeyPrivateKey?: string` - API Key 私鑰(新增)
### 技術細節
**數據庫兼容性**:
- 使用 ALTER TABLE ADD COLUMN IF NOT EXISTS
- 默認值為空字符串
- 不影響現有數據
**類型安全**:
- TypeScript 可選字段
- 與後端 ExchangeConfig 結構對齊
### 下一步
 **待完成**:
1. ExchangeConfigModal 組件更新
2. API 調用參數傳遞
3. V1/V2 狀態顯示
Co-Authored-By: tinkle-community <tinklefund@gmail.com>
* docs(lighter): 更新 LIGHTER_INTEGRATION.md 文檔狀態
* feat(lighter): 前端完整實現 - API Key 配置與 V1/V2 狀態
**英文**:
- `lighterWalletAddress`, `lighterPrivateKey`, `lighterApiKeyPrivateKey`
- `lighterWalletAddressDesc`, `lighterPrivateKeyDesc`, `lighterApiKeyPrivateKeyDesc`
- `lighterApiKeyOptionalNote` - V1 模式提示
- `lighterV1Description`, `lighterV2Description` - 狀態說明
- `lighterPrivateKeyImported` - 導入成功提示
**中文(繁體)**:
- 完整的中文翻譯對應
- 專業術語保留原文(L1、API Key、Poseidon2)
**Exchange 接口**:
- `lighterWalletAddr?: string`
- `lighterPrivateKey?: string`
- `lighterApiKeyPrivateKey?: string`
**UpdateExchangeConfigRequest 接口**:
- `lighter_wallet_addr?: string`
- `lighter_private_key?: string`
- `lighter_api_key_private_key?: string`
**狀態管理**:
- 添加 3 個 LIGHTER 狀態變量
- 更新 `secureInputTarget` 類型包含 'lighter'
**表單字段**:
- L1 錢包地址(必填,text input)
- L1 私鑰(必填,password + 安全輸入)
- API Key 私鑰(可選,password,40 字節)
**V1/V2 狀態顯示**:
- 動態背景顏色(V1: 橙色 #3F2E0F,V2: 綠色 #0F3F2E)
- 圖標指示(V1: ⚠️,V2: )
- 狀態說明文字
**驗證邏輯**:
- 必填字段:錢包地址 + L1 私鑰
- API Key 為可選字段
- 自動 V1/V2 檢測
**安全輸入**:
- 支持通過 TwoStageKeyModal 安全導入私鑰
- 導入成功後顯示 toast 提示
**handleSaveExchange**:
- 添加 3 個 LIGHTER 參數
- 更新交易所對象(新增/更新)
- 構建 API 請求(snake_case 字段)
**V1 模式(無 API Key)**:
```
┌────────────────────────────────────────┐
│ ⚠️ LIGHTER V1                          │
│ 基本模式 - 功能受限,僅用於測試框架       │
└────────────────────────────────────────┘
背景: #3F2E0F (橙色調)
邊框: #F59E0B (橙色)
```
**V2 模式(有 API Key)**:
```
┌────────────────────────────────────────┐
│  LIGHTER V2                          │
│ 完整模式 - 支持 Poseidon2 簽名和真實交易 │
└────────────────────────────────────────┘
背景: #0F3F2E (綠色調)
邊框: #10B981 (綠色)
```
1. **類型安全**
   - 完整的 TypeScript 類型定義
   - Props 接口正確對齊
   -  無 LIGHTER 相關編譯錯誤
2. **用戶體驗**
   - 清晰的必填/可選字段區分
   - 實時 V1/V2 狀態反饋
   - 安全私鑰輸入支持
3. **向後兼容**
   - 不影響現有交易所配置
   - 所有字段為可選(Optional)
   - API 請求格式統一
 TypeScript 編譯通過(無 LIGHTER 錯誤)
 類型定義完整且正確
 所有必需文件已更新
 與後端 API 格式對齊
Modified:
- `web/src/i18n/translations.ts` - 中英文翻譯
- `web/src/types.ts` - 類型定義
- `web/src/components/traders/ExchangeConfigModal.tsx` - Modal 組件
- `web/src/hooks/useTraderActions.ts` - Actions hook
Co-Authored-By: tinkle-community <tinklefund@gmail.com>
* test(lighter): 添加 V1 測試套件與修復 SafeFloat64 缺失
- 新增 trader/helpers.go: 添加 SafeFloat64/SafeString/SafeInt 輔助函數
- 新增 trader/lighter_trader_test.go: LIGHTER V1 測試套件
  -  測試通過 (7/10):
    - NewTrader 驗證 (無效私鑰, 有效私鑰格式)
    - FormatQuantity
    - GetExchangeType
    - InvalidQuantity 驗證
    - InvalidLeverage 驗證
    - HelperFunctions (SafeFloat64)
  - ⚠️ 待改進 (3/10):
    - GetBalance (需要調整 mock 響應格式)
    - GetPositions (需要調整 mock 響應格式)
    - GetMarketPrice (需要調整 mock 響應格式)
- 修復 Bug: lighter_account.go 和 lighter_trader_v2_account.go 中未定義的 SafeFloat64
- 測試框架: httptest.Server mock LIGHTER API
- 安全: 使用固定測試私鑰 (不含真實資金)
Co-Authored-By: tinkle-community <tinklefund@gmail.com>
---------
Co-authored-by: the-dev-z <the-dev-z@users.noreply.github.com>
Co-authored-by: tinkle-community <tinklefund@gmail.com>
2025-11-20 19:29:01 +08:00
0xYYBB | ZYY | Bobo c1cf44b98f fix(api): use UUID to ensure traderID uniqueness (#893) (#1008)
## Problem
When multiple users create traders with the same exchange + AI model
combination within the same second, they generate identical traderIDs,
causing data conflicts.
Old code (Line 496):
```go
traderID := fmt.Sprintf("%s_%s_%d", req.ExchangeID, req.AIModelID, time.Now().Unix())
```
## Solution
Use UUID to guarantee 100% uniqueness while preserving prefix for debugging:
```go
traderID := fmt.Sprintf("%s_%s_%s", req.ExchangeID, req.AIModelID, uuid.New().String())
```
Example output: `binance_gpt-4_a1b2c3d4-e5f6-7890-abcd-ef1234567890`
## Changes
- `api/server.go:495-497`: Use UUID for traderID generation
- `api/traderid_test.go`: New test file with 3 comprehensive tests
## Tests
 All tests passed (0.189s)
 TestTraderIDUniqueness - 100 unique IDs generated
 TestTraderIDFormat - 3 exchange/model combinations validated
 TestTraderIDNoCollision - 1000 iterations without collision
Fixes #893
Co-authored-by: the-dev-z <the-dev-z@users.noreply.github.com>
2025-11-15 22:20:06 -05:00
Diego a574717f7b fix(stats): fixed the PNL calculation (#963) 2025-11-15 22:20:06 -05:00
Lawrence Liu 217ccb08dd feat(dashboard): 在交易者详情页显示系统提示词模板名称 (#775)
* feat(dashboard): display system prompt template and extract color constant
* style(api): format server.go with go fmt
2025-11-15 22:20:06 -05:00
Lawrence Liu ced6c3d9de feat: add whether to enable self registration toggle (#760)
* refactor(frontend): extract RegistrationDisabled as reusable component
- Create RegistrationDisabled component with i18n support
- Add registrationClosed and registrationClosedMessage translations
- Replace inline JSX in App.tsx with new component
- Improve code maintainability and reusability
- Add hover effect to back button for better UX
* fix(frontend): add registration toggle to LoginModal component
- Add useSystemConfig hook to LoginModal
- Conditionally render registration button based on registration_enabled config
- Ensures consistency with HeaderBar and LoginPage registration controls
- Completes registration toggle feature implementation across all entry points
* feat(frontend): add registration toggle UI support
- Add registration disabled page in App.tsx when registration is closed
- Hide registration link in LoginPage when registration is disabled
- Add registration_enabled field to SystemConfig interface
- Frontend conditionally shows/hides registration UI based on backend config
* feat: add registration toggle feature
Add system-level registration enable/disable control:
- Add registration_enabled config to system_config table (default: true)
- Add registration check in handleRegister API endpoint
- Expose registration_enabled status in /api/config endpoint
- Frontend can use this config to conditionally show/hide registration UI
This allows administrators to control user registration without code changes.
* fix(frontend): add registration toggle to HeaderBar and RegisterPage
- Add useSystemConfig hook and registrationEnabled check to HeaderBar
- Conditionally show/hide signup buttons in both desktop and mobile views
- Add registration check to RegisterPage to show RegistrationDisabled component
- This completes the registration toggle feature across all UI components
* test(frontend): add comprehensive unit tests for registration toggle feature
- Add RegistrationDisabled component tests (rendering, navigation, styling)
- Add registrationToggle logic tests (config handling, edge cases, multi-location consistency)
- Configure Vitest with jsdom environment for React component testing
- All 80 tests passing (9 new tests for RegistrationDisabled + 21 for toggle logic)
2025-11-15 22:18:57 -05:00
Icy 905c3ed8b4 merge fix 2025-11-13 00:44:26 +08:00
Icy 9933e3164d 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
2025-11-12 23:20:25 +08:00
Lawrence Liu 9d721621f2 feat: Add decision limit selector with 5/10/20/50 options (#638)
## Summary
Allow users to select the number of decision records to display (5/10/20/50)
in the Web UI, with persistent storage in localStorage.
## Changes
### Backend
- api/server.go: Add 'limit' query parameter support to /api/decisions/latest
  - Default: 5 (maintains current behavior)
  - Max: 50 (prevents excessive data loading)
  - Fully backward compatible
### Frontend
- web/src/lib/api.ts: Update getLatestDecisions() to accept limit parameter
- web/src/pages/TraderDashboard.tsx:
  - Add decisionLimit state management with localStorage persistence
  - Add dropdown selector UI (5/10/20/50 options)
  - Pass limit to API calls and update SWR cache key
## Time Coverage
- 5 records = 15 minutes (default, quick check)
- 10 records = 30 minutes (short-term review)
- 20 records = 1 hour (medium-term analysis)
- 50 records = 2.5 hours (deep pattern analysis)
2025-11-11 20:34:29 -05:00
Lawrence Liu 6efe733127 feat(decision): auto-reload prompt templates when starting trader (#833)
* feat: 启动交易员时自动重新加载系统提示词模板
## 改动内容
- 在 handleStartTrader 中调用 decision.ReloadPromptTemplates()
- 每次启动交易员时从硬盘重新加载 prompts/ 目录下的所有 .txt 模板文件
- 添加完整的单元测试和端到端集成测试
## 测试覆盖
- 单元测试:模板加载、获取、重新加载功能
- 集成测试:文件修改 → 重新加载 → 决策引擎使用新内容的完整流程
- 并发测试:验证多 goroutine 场景下的线程安全性
- Race detector 测试通过
## 用户体验改进
- 修改 prompt 文件后无需重启服务
- 只需停止交易员再启动即可应用新的 prompt
- 控制台会输出重新加载成功的日志提示
* feat: 在重新加载日志中显示当前使用的模板名称
* feat: fallback 到 default 模板时明确显示原因
* fix: correct GetTraderConfig return type to get SystemPromptTemplate
* refactor: extract reloadPromptTemplatesWithLog as reusable method
2025-11-10 21:37:46 -05:00
0xYYBB | ZYY | Bobo bb2d81cbd4 fix(auth): allow re-fetching OTP for unverified users (#653)
* fix(auth): allow re-fetching OTP for unverified users
**Problem:**
- User registers but interrupts OTP setup
- Re-registration returns "邮箱已被注册" error
- User stuck, cannot retrieve QR code to complete setup
**Root Cause:**
- handleRegister rejects all existing emails without checking OTPVerified status
- No way for users to recover from interrupted registration
**Fix:**
- Check if existing user has OTPVerified=false
- If unverified, return original OTP QR code instead of error
- User can continue completing registration with same user_id
- If verified, still reject with "邮箱已被注册" (existing behavior)
**Code Changes:**
```go
// Before:
_, err := s.database.GetUserByEmail(req.Email)
if err == nil {
    c.JSON(http.StatusConflict, gin.H{"error": "邮箱已被注册"})
    return
}
// After:
existingUser, err := s.database.GetUserByEmail(req.Email)
if err == nil {
    if !existingUser.OTPVerified {
        // Return OTP to complete registration
        qrCodeURL := auth.GetOTPQRCodeURL(existingUser.OTPSecret, req.Email)
        c.JSON(http.StatusOK, gin.H{
            "user_id": existingUser.ID,
            "otp_secret": existingUser.OTPSecret,
            "qr_code_url": qrCodeURL,
            "message": "检测到未完成的注册,请继续完成OTP设置",
        })
        return
    }
    c.JSON(http.StatusConflict, gin.H{"error": "邮箱已被注册"})
    return
}
```
**Testing Scenario:**
1. User POST /api/register with email + password
2. User receives OTP QR code but closes browser (interrupts)
3. User POST /api/register again with same email + password
4.  Now returns original OTP instead of error
5. User can complete registration via /api/complete-registration
**Security:**
 No security issue - still requires OTP verification
 Only returns OTP for unverified accounts
 Password not validated on re-fetch (same as initial registration)
**Impact:**
 Users can recover from interrupted registration
 Better UX for registration flow
 No breaking changes to existing verified users
**API Changes:**
- POST /api/register response for unverified users:
  - Status: 200 OK (was: 409 Conflict)
  - Body includes: user_id, otp_secret, qr_code_url, message
Fixes #615
Co-Authored-By: tinkle-community <tinklefund@gmail.com>
* test(api): add comprehensive unit tests for OTP re-fetch logic
- Test OTP re-fetch logic for unverified users
- Test OTP verification state handling
- Test complete registration flow scenarios
- Test edge cases (ID=0, empty OTPSecret, verified users)
All 11 test cases passed, covering:
1. OTPRefetchLogic (3 cases): new user, unverified refetch, verified rejection
2. OTPVerificationStates (2 cases): verified/unverified states
3. RegistrationFlow (3 cases): first registration, interrupted resume, duplicate attempt
4. EdgeCases (3 cases): validates behavior with edge conditions
Related to PR #653 - ensures proper OTP re-fetch behavior for unverified users.
Co-Authored-By: tinkle-community <tinklefund@gmail.com>
* style: apply go fmt after rebase
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>
2025-11-10 20:29:02 -05:00
Diego 9f2c62d692 should not load all user traders when create/update trader (#854) 2025-11-10 14:02:36 +08:00
Lawrence Liu 486ff5e909 fix(trader): 修复编辑交易员时系统提示词模板无法更新和回显的问题 (#841)
## 问题描述
1. ⚠️ **无法更新**(最严重):用户修改系统提示词模板并保存后,更新被忽略,仍保持旧值
2. 编辑时显示错误的默认值:打开编辑对话框时该字段显示为 Default 而非实际保存的值(如 nof1)
## 根本原因
1. UpdateTraderRequest 结构体缺少 SystemPromptTemplate 字段 - 后端无法接收更新请求
2. handleGetTraderConfig 返回值中缺少 system_prompt_template 字段 - 前端无法获取实际值
3. handleUpdateTrader 强制使用原值,不接受请求中的更新 - 即使前端发送也被忽略
## 修复内容
1. 在 UpdateTraderRequest 中添加 SystemPromptTemplate 字段 - 现在可以接收更新
2. 在 handleUpdateTrader 中支持从请求读取并更新该字段 - 用户可以修改了
3. 在 handleGetTraderConfig 返回值中添加 system_prompt_template 字段 - 前端可以正确显示
## 测试
- 添加 3 个单元测试验证修复
- 所有测试通过,无回归
- 覆盖 nof1, default, custom 等不同模板场景
## 影响范围
- api/server.go: UpdateTraderRequest, handleUpdateTrader, handleGetTraderConfig
- 新增 api/server_test.go: 3 个单元测试
Closes #838
2025-11-10 01:20:30 +08:00