Commit Graph

75 Commits

Author SHA1 Message Date
tinkle-community b228412821 feat: add trading stats to AI context and one-click deployment data clearing
- Add historical trading statistics to AI decision context with language detection
- Remove win rate from metrics, focus on profit factor, sharpe ratio, win/loss ratio
- Add option to clear trading data tables during one-click deployment
- Add sqlite to Docker runtime for container-based data clearing
2025-12-28 22:09:47 +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 46922f8c53 feat: add multi-exchange order sync and position tracking
- Add order sync implementations for Hyperliquid, Bybit, OKX, Bitget, Aster
- Add position snapshot functionality for exchange position reset
- Update TraderOrder and TraderFill structures with exchange_type field
- Add exchange sync tests
- Update frontend charts components
- Remove deprecated position_sync.go
2025-12-27 02:09:48 +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 97f58b49f4 feat: add experience improvement module and system config storage (#1248)
- Add experience module for product telemetry
- Add system_config table for persistent settings
- Update privacy policy documentation
2025-12-19 13:57:08 +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 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 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 8a5744e0a0 fix: use actual fill price from exchange API for position records
- Remove trader_orders table and OrderSyncManager (never worked correctly)
- Poll GetOrderStatus to get actual avgPrice, executedQty, and commission
- Get entry price from exchange GetPositions API when closing positions
- Pass fee to trader_positions table on close
- Move TraderStats type to position.go
2025-12-08 12:15:41 +08:00
tinkle-community f39fc8af23 fix: save raw AI response for debugging and require calculated numbers
- Add RawResponse field to FullDecision and DecisionRecord
- Save raw AI response to database for debugging parse failures
- Add IMPORTANT note in prompt: all numeric values must be calculated numbers, not formulas
2025-12-08 11:29:31 +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 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 5d1d0b6842 Feature/custom strategy (#1173)
* 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
* feat: add quant data integration and fix position click navigation
- Integrate quant data API (netflow, OI, price changes) into Strategy Studio
- Add enable_quant_data toggle in indicator editor
- Fix position symbol click to navigate to chart (sync defaultSymbol prop)
- Fix TradingView chart fullscreen flickering
2025-12-06 07:47:03 +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 afb2d158ac feat: add exchange_id field to trader_positions table
- Add exchange_id column to track which exchange the position is from
- Update all SELECT/INSERT queries to include exchange_id
- Set exchange_id when creating position record in AutoTrader
- Add migration to add column to existing tables
2025-12-06 01:35:26 +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
0xYYBB | ZYY | Bobo ded86d831f feat(exchange): add Bybit Futures support (#1100)
* feat(exchange): add Bybit Futures support
- Add Bybit Go SDK dependency (github.com/bybit-exchange/bybit.go.api)
- Create trader/bybit_trader.go implementing Trader interface for USDT perpetual futures
- Update config/database.go to include Bybit in default exchanges
- Update manager/trader_manager.go to handle Bybit API key configuration
- Update trader/auto_trader.go to add BybitAPIKey/BybitSecretKey fields and bybit case
- Add Bybit icon to frontend ExchangeIcons.tsx
Bybit uses standard API Key/Secret Key authentication (similar to Binance).
Only USDT perpetual futures (category=linear) are supported.
Co-Authored-By: tinkle-community <tinklefund@gmail.com>
* test(bybit): add comprehensive unit tests for Bybit trader
- Add BybitTraderTestSuite following existing test patterns
- Interface compliance test (Trader interface)
- Symbol format validation tests
- FormatQuantity tests with 3-decimal precision
- API response parsing tests (success, error, permission denied)
- Position side conversion tests (Buy->long, Sell->short)
- Cache duration verification test
- Mock server integration tests for API endpoints
All 12 Bybit tests pass.
Co-Authored-By: tinkle-community <tinklefund@gmail.com>
* fix(frontend): add Bybit support to exchange config forms
修復前端對 Bybit 交易所的支持:
- 添加 Bybit 到 API Key/Secret Key 輸入欄位顯示邏輯
- 添加 Bybit 的表單驗證邏輯
- 修復 ExchangeConfigModal.tsx 和 AITradersPage.tsx
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-23 19:23:53 +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
Shui b96c86fce4 Improve(interface): replace some struct with interface for testing (#994)
* fix(trader): get peakPnlPct using posKey
* fix(docs): keep readme at the same page
* improve(interface): replace with interface
* refactor mcp
---------
Co-authored-by: zbhan <zbhan@freewheel.tv>
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
Shui 0ede0809ad fix(trader): get peakPnlPct using posKey (#955)
Co-authored-by: zbhan <zbhan@freewheel.tv>
2025-11-15 22:20:06 -05:00
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