-
Notifications
You must be signed in to change notification settings - Fork 2.5k
fix(market): add data staleness detection and API fallback for WebSocket klines #1107
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: dev
Are you sure you want to change the base?
Conversation
…iquid-testnet-clean fix(trader): add missing HyperliquidTestnet configuration in loadSing…
…p-422 fix: resolve login redirect loop issue (NoFxAiOS#422)
Updates dependencies by replacing ioutil with io. Adds .tool-versions and web/yarn.lock to .gitignore.
## Fixes ### 1. Typewriter Component - Missing First Character - Fix character loss issue where first character of each line was missing - Add proper state reset logic before starting typing animation - Extract character before setState to avoid closure issues - Add setTimeout(0) to ensure state is updated before typing starts - Change dependency from `lines` to `sanitizedLines` for correct updates - Use `??` instead of `||` for safer null handling ### 2. Chinese Translation - Leading Spaces - Remove leading spaces from startupMessages1/2/3 in Chinese translations - Ensures proper display of startup messages in terminal simulation ### 3. Dynamic GitHub Stats with Animation - Add useGitHubStats hook to fetch real-time GitHub repository data - Add useCounterAnimation hook with easeOutExpo easing for smooth number animation - Display dynamic star count with smooth counter animation (2s duration) - Display dynamic days count (static, no animation) - Support bilingual display (EN/ZH) with proper formatting ## Changes - web/src/components/Typewriter.tsx: Fix first character loss bug - web/src/i18n/translations.ts: Remove leading spaces in Chinese messages - web/src/components/landing/HeroSection.tsx: Add dynamic GitHub stats - web/src/hooks/useGitHubStats.ts: New hook for GitHub API integration - web/src/hooks/useCounterAnimation.ts: New hook for number animations Fixes NoFxAiOS#365 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
- Install ESLint 9 with TypeScript and React support - Install Prettier with custom configuration (no semicolons) - Add husky and lint-staged for pre-commit hooks - Configure lint-staged to auto-fix and format on commit - Relax ESLint rules to avoid large-scale code changes - Format all existing code with Prettier (no semicolons) Co-Authored-By: Claude <[email protected]>
Feature/eslint&prettier
用户在使用Aster交易员时发现,即使没有开始交易,P&L统计也显示了12.5 USDT (83.33%)的盈亏。经过调查发现: **根本原因**: - 实际Aster账户余额:27.5 USDT - Web界面配置的InitialBalance:15 USDT ❌ - 错误的P&L计算:27.5 - 15 = 12.5 USDT (83.33%) **问题根源**: 1. Web界面创建交易员时默认initial_balance为1000 USDT 2. 用户手动修改时容易输入错误的值 3. 缺少自动获取实际余额的功能 4. 缺少明确的警告提示 **文件**: `trader/aster_trader.go` - ✅ 验证Aster API完全兼容Binance格式 - 添加详细的注释说明字段含义 - 添加调试日志以便排查问题 - 确认balance字段不包含未实现盈亏(与Binance一致) **关键确认**: ```go // ✅ Aster API完全兼容Binance API格式 // balance字段 = wallet balance(不包含未实现盈亏) // crossUnPnl = unrealized profit(未实现盈亏) // crossWalletBalance = balance + crossUnPnl(全仓钱包余额,包含盈亏) ``` **文件**: `web/src/components/TraderConfigModal.tsx` **新增功能**: 1. **编辑模式**:添加"获取当前余额"按钮 - 一键从交易所API获取当前账户净值 - 自动填充到InitialBalance字段 - 显示加载状态和错误提示 2. **创建模式**:添加警告提示 -⚠️ 提醒用户必须输入交易所的当前实际余额 - 警告:如果输入不准确,P&L统计将会错误 3. **改进输入体验**: - 支持小数输入(step="0.01") - 必填字段标记(创建模式) - 实时错误提示 **代码实现**: ```typescript const handleFetchCurrentBalance = async () => { const response = await fetch(`/api/account?trader_id=${traderData.trader_id}`); const data = await response.json(); const currentBalance = data.total_equity; // 当前净值 setFormData(prev => ({ ...prev, initial_balance: currentBalance })); }; ``` 通过查阅Binance官方文档确认: | 项目 | Binance | Aster (修复后) | |------|---------|----------------| | **余额字段** | balance = 钱包余额(不含盈亏) | ✅ 相同 | | **盈亏字段** | crossUnPnl = 未实现盈亏 | ✅ 相同 | | **总权益** | balance + crossUnPnl | ✅ 相同 | | **P&L计算** | totalEquity - initialBalance | ✅ 相同 | 1. 编辑交易员配置 2. 点击"获取当前余额"按钮 3. 系统自动填充正确的InitialBalance 4. 保存配置 1. 查看交易所账户的实际余额 2. 准确输入到InitialBalance字段 3. 注意查看警告提示 4. 完成创建 - [x] 确认Aster API返回格式与Binance一致 - [x] 验证"获取当前余额"功能正常工作 - [x] 确认P&L计算公式正确 - [x] 前端构建成功 - [x] 警告提示正常显示 - **修复**: 解决InitialBalance配置错误导致的P&L统计不准确问题 - **改进**: 提升用户体验,减少配置错误 - **兼容**: 完全向后兼容,不影响现有功能 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
Added interactive help icons with tooltips for Aster exchange fields (user, signer, privateKey) to guide users through correct configuration. Changes: - Added HelpCircle icon from lucide-react - Created reusable Tooltip component with hover/click interaction - Added bilingual help descriptions in translations.ts - User field: explains main wallet address (login address) - Signer field: explains API wallet address generation - Private Key field: clarifies local-only usage, never transmitted This prevents user confusion and configuration errors when setting up Aster exchange. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
Added warning message to inform users that Aster only tracks USDT balance, preventing P&L calculation errors from asset price fluctuations. Why this is important: - Aster trader only tracks USDT balance (aster_trader.go:453) - If users use BNB/ETH as margin, price fluctuations will cause: * Initial balance becomes inaccurate * P&L statistics will be wrong * Example: 10 BNB @ $100 = $1000, if BNB drops to $90, real equity is $900 but system still shows $1000 Changes: - Added asterUsdtWarning translation in both EN and ZH - Added red warning box below Aster private key field - Clear message: "Please use USDT as margin currency" 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
主要优化点: 强化风险控制框架 明确单笔风险≤2%,总风险≤6% 添加连续亏损后的仓位调整规则 设置单日和每周最大亏损限制 提高开仓标准 要求至少3个技术指标支持 必须有多时间框架趋势确认 入场时机要求更具体 完善决策流程 增加市场环境评估环节 明确风险回报比计算要求 添加资金保护检查点 细化行为准则 明确等待最佳机会的重要性 强调分批止盈和严格止损 添加情绪控制具体方法 增强绩效反馈机制 不同夏普比率区间的具体行动指南 亏损状态下的仓位控制要求 盈利状态下的纪律保持提醒 这个优化版本更加注重风险控制和稳健性,同时保持了交易的专业性和灵活性。
Merged standalone USDT warning into existing security warning section for cleaner UI. Changes: - Removed separate red warning box for USDT - Added USDT warning as first item in security warning box (conditional on Aster exchange) - Now shows 4 warnings for Aster: USDT requirement + 3 general security warnings - Cleaner, more organized warning presentation 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
Added direct links to Aster API wallet page in help tooltips for easier access. Changes: - Added English link: https://www.asterdex.com/en/api-wallet - Added Chinese link: https://www.asterdex.com/zh-CN/api-wallet - Updated asterSignerDesc with API wallet URL - Updated asterPrivateKeyDesc with API wallet URL and security note - Users can now directly access the API wallet page from tooltips 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
## Fixes ### 1. Typewriter Component - Missing First Character - Fix character loss issue where first character of each line was missing - Add proper state reset logic before starting typing animation - Extract character before setState to avoid closure issues - Add setTimeout(0) to ensure state is updated before typing starts - Change dependency from `lines` to `sanitizedLines` for correct updates - Use `??` instead of `||` for safer null handling ### 2. Chinese Translation - Leading Spaces - Remove leading spaces from startupMessages1/2/3 in Chinese translations - Ensures proper display of startup messages in terminal simulation ### 3. Dynamic GitHub Stats with Animation - Add useGitHubStats hook to fetch real-time GitHub repository data - Add useCounterAnimation hook with easeOutExpo easing for smooth number animation - Display dynamic star count with smooth counter animation (2s duration) - Display dynamic days count (static, no animation) - Support bilingual display (EN/ZH) with proper formatting ## Changes - web/src/components/Typewriter.tsx: Fix first character loss bug - web/src/i18n/translations.ts: Remove leading spaces in Chinese messages - web/src/components/landing/HeroSection.tsx: Add dynamic GitHub stats - web/src/hooks/useGitHubStats.ts: New hook for GitHub API integration - web/src/hooks/useCounterAnimation.ts: New hook for number animations Fixes NoFxAiOS#365 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
- Extract formattedStars calculation to avoid duplication - Keep tabular-nums span for consistent number width during animation - Address code review feedback from @xqliu 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
feat(log): add logrus log lib and add telegram notification push as an option
…-help-tooltips feat: add help tooltips for Aster exchange configuration fields
增加 稳健和风险控制均衡基础策略提示词
…ore-v2 feat: 部分平倉和動態止盈止損核心實現 / Partial Close & Dynamic TP/SL Core
…tpsl feat(logger): 添加動態 TP/SL 日誌支持 [依賴 NoFxAiOS#415]
…tial-close-guidance refactor(prompts): 增強部分平倉使用指導 [依賴 NoFxAiOS#415]
…lance-v2 feat(api): query actual exchange balance when creating trader
…leness fix(market): resolve price staleness causing trade failures
…-threshold feat(decision): configurable OI threshold + relaxed trading template
…haracters fix(decision): handle fullwidth JSON characters from AI responses
…lete-balance-fix fix(hyperliquid): complete balance detection with 4 critical fixes
…xAiOS#986) ## Problem PR NoFxAiOS#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 NoFxAiOS#906 made two commits: 1. First commit (3af8760): `curl` → `wget` (✅ correct fix) 2. Second commit (333b2ef): `wget` → `curl` (❌ introduced bug) The second commit was based on incorrect assumption that "curl is more widely available than wget in Docker images". This is false for Alpine. ## Solution Revert healthcheck commands back to `wget` to match: 1. Alpine's pre-installed tools 2. Dockerfile.backend healthcheck (line 68) 3. Docker and Kubernetes best practices ## Testing ✅ Verified `wget` exists in Alpine containers: ```bash docker run --rm alpine:latest which wget # Output: /usr/bin/wget ``` ✅ Added new CI workflow to prevent regression: - `.github/workflows/pr-docker-compose-healthcheck.yml` - Validates healthcheck compatibility with Alpine - Ensures containers reach healthy status ## Impact - **Before**: Containers show (unhealthy), potential auto-restart loops - **After**: Containers show (healthy), monitoring systems happy - **Scope**: Only affects docker-compose deployments - **Breaking**: None - this is a bug fix ## References - PR NoFxAiOS#906: Original (incorrect) fix - Alpine Linux: https://alpinelinux.org/about/ - Dockerfile.backend L68: Existing `wget` healthcheck 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: the-dev-z <[email protected]> Co-authored-by: Claude <[email protected]> Co-authored-by: Shui <[email protected]>
* improve(interface): replace with interface * feat(mcp): 添加构建器模式支持 新增功能: - RequestBuilder 构建器,支持流式 API - 多轮对话支持(AddAssistantMessage) - Function Calling / Tools 支持 - 精细参数控制(temperature, top_p, penalties 等) - 3个预设场景(Chat, CodeGen, CreativeWriting) - 完整的测试套件(19个新测试) 修复问题: - Config 字段未使用(MaxRetries、Temperature 等) - DeepSeek/Qwen SetAPIKey 的冗余 nil 检查 向后兼容: - 保留 CallWithMessages API - 新增 CallWithRequest API 测试: - 81 个测试全部通过 - 覆盖率 80.6% 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]> --------- Co-authored-by: zbhan <[email protected]> Co-authored-by: Claude <[email protected]>
…ing (NoFxAiOS#1061) * fix(web): remove duplicate PasswordChecklist in error block - Remove duplicate PasswordChecklist component from error message area - Keep only the real-time password validation checklist - Error block now displays only the error message text Bug was introduced in commit aa0bd93 (PR NoFxAiOS#872) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]> * refactor(web): redesign httpClient with axios and unified error handling Major refactoring to improve error handling architecture: ## Changes ### 1. HTTP Client Redesign (httpClient.ts) - Replaced native fetch with axios for better interceptor support - Implemented request/response interceptors for centralized error handling - Added automatic Bearer token injection in request interceptor - Network errors and system errors (404, 403, 500) now intercepted and shown via toast - Only business logic errors (4xx except 401/403/404) returned to caller - New ApiResponse<T> interface for type-safe responses ### 2. API Migration (api.ts) - Migrated all 31 API methods from legacy fetch-style to new httpClient - Updated pattern: from `res.ok/res.json()` to `result.success/result.data` - Removed getAuthHeaders() helper (token now auto-injected) - Added TypeScript generics for better type safety ### 3. Component Updates - AuthContext.tsx: Updated register() to use new API - TraderConfigModal.tsx: Migrated 3 API calls (config, templates, balance) - RegisterPage.tsx: Simplified error display (error type handling now in API layer) ### 4. Removed Legacy Code - Removed legacyHttpClient compatibility wrapper (~30 lines) - Removed legacyRequest() method - Clean separation: API layer handles all error classification ## Benefits - Centralized error handling - no need to check network/system errors in components - Better UX - automatic toast notifications for system errors - Type safety - generic ApiResponse<T> provides compile-time checks - Cleaner business components - only handle business logic errors - Consistent error messages across the application 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]> --------- Co-authored-by: Claude <[email protected]>
* 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 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]> * 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 支持 - [ ] 完整測試套件 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]> * 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: Claude <[email protected]> * 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 規範 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]> * 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 狀態顯示 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]> * 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 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]> * 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 - 安全: 使用固定測試私鑰 (不含真實資金) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]> --------- Co-authored-by: the-dev-z <[email protected]> Co-authored-by: Claude <[email protected]>
* 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. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]> * 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. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]> * fix(frontend): add Bybit support to exchange config forms 修復前端對 Bybit 交易所的支持: - 添加 Bybit 到 API Key/Secret Key 輸入欄位顯示邏輯 - 添加 Bybit 的表單驗證邏輯 - 修復 ExchangeConfigModal.tsx 和 AITradersPage.tsx 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]> --------- Co-authored-by: the-dev-z <[email protected]> Co-authored-by: Claude <[email protected]>
…ket klines ## Problem Users reported that WebSocket data stops updating but the system continues using stale cached data for AI trading decisions. Two consecutive trading cycles showed identical BTC prices (96307.60) and indicators, causing the AI to make decisions based on outdated information. ## Root Cause - Kline data was stored without timestamps - No freshness check before returning cached data - No fallback mechanism when WebSocket stops working ## Solution 1. Added `KlineCacheEntry` struct to store klines with `ReceivedAt` timestamp 2. Reduced freshness threshold from 15 minutes to **5 minutes** for faster detection 3. Added **API fallback**: when data is stale, automatically fetch from REST API 4. Added warning logs when stale data is detected ## Impact - Prevents AI from making decisions on stale data - Automatic recovery when WebSocket fails - Quick detection (within 5 minutes) of data staleness Fixes NoFxAiOS#1028 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
🤖 Advisory Check ResultsThese are advisory checks to help improve code quality. They won't block your PR from being merged. 📋 PR InformationTitle Format: ✅ Good - Follows Conventional Commits 🔧 Backend ChecksGo Formatting: Files needing formattingGo Vet: ✅ Good Fix locally: go fmt ./... # Format code
go vet ./... # Check for issues
go test ./... # Run tests⚛️ Frontend ChecksBuild & Type Check: ✅ Success Fix locally: cd web
npm run build # Test build (includes type checking)📖 ResourcesQuestions? Feel free to ask in the comments! 🙏 These checks are advisory and won't block your PR from being merged. This comment is automatically generated from pr-checks-run.yml. |
43aad91 to
5517269
Compare
9384ffd to
5391f39
Compare
|
Icy seems not to be a GitHub user. You need a GitHub account to be able to sign the CLA. If you have already a GitHub account, please add the email address used for this commit to your account. You have signed the CLA already but the status is still pending? Let us recheck it. |
Summary
Problem (Issue #1028)
Users reported that WebSocket data stops updating but the system continues using stale cached data:
Root Cause
Solution
KlineCacheEntrystruct to store klines withReceivedAttimestampChanges
market/monitor.go: Added staleness detection and API fallback logicTest Plan
Fixes #1028
🤖 Generated with Claude Code