Commit Graph

25 Commits

Author SHA1 Message Date
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 a12c0ae8c9 refactor: standardize code comments 2025-12-08 01:43:22 +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 57e31b2ace fix(trader): add mutex to prevent race condition in Meta refresh (#796)
* fix(trader): add mutex to prevent race condition in Meta refresh (issue #742)
**問題**:
根據 issue #742 審查標準,發現 BLOCKING 級別的並發安全問題:
- refreshMetaIfNeeded() 中的 `t.meta = meta` 缺少並發保護
- 多個 goroutine 同時調用 OpenLong/OpenShort 會造成競態條件
**修復**:
1. 添加 sync.RWMutex 保護 meta 字段
2. refreshMetaIfNeeded() 使用寫鎖保護 meta 更新
3. getSzDecimals() 使用讀鎖保護 meta 訪問
**符合標準**:
- issue #742: "並發安全問題需使用 sync.Once 等機制"
- 使用 RWMutex 實現讀寫分離,提升並發性能
Co-Authored-By: tinkle-community <tinklefund@gmail.com>
* test(trader): add comprehensive race condition tests for meta field mutex protection
- Test concurrent reads (100 goroutines accessing getSzDecimals)
- Test concurrent read/write (50 readers + 10 writers simulating meta refresh)
- Test nil meta edge case (returns default value 4)
- Test valid meta with multiple coins (BTC, ETH, SOL)
- Test massive concurrency (1000 iterations with race detector)
All 5 test cases passed, including -race verification with no data races detected.
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:50:56 -05:00
Icyoung 062184054d Dev remove admin mode (#723)
* feat: remove admin mode
* feat: bugfix
---------
Co-authored-by: icy <icyoung520@gmail.com>
2025-11-07 23:37:23 +08:00
0xYYBB | ZYY | Bobo 9ad3e99645 feat(hyperliquid): enhance Agent Wallet security model (#717)
## Background
Hyperliquid official documentation recommends using Agent Wallet pattern for API trading:
- Agent Wallet is used for signing only
- Main Wallet Address is used for querying account data
- Agent Wallet should not hold significant funds
Reference: https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/nonces-and-api-wallets
## Current Implementation
Current implementation allows auto-generating wallet address from private key,
which simplifies user configuration but may lead to potential security concerns
if users accidentally use their main wallet private key.
## Enhancement
Following the proven pattern already used in Aster exchange implementation
(which uses dual-address mode), this enhancement upgrades Hyperliquid to
Agent Wallet mode:
### Core Changes
1. **Mandatory dual-address configuration**
   - Agent Private Key (for signing)
   - Main Wallet Address (holds funds)
2. **Multi-layer security checks**
   - Detect if user accidentally uses main wallet private key
   - Validate Agent wallet balance (reject if > 100 USDC)
   - Provide detailed configuration guidance
3. **Design consistency**
   - Align with Aster's dual-address pattern
   - Follow Hyperliquid official best practices
### Code Changes
**config/database.go**:
- Add inline comments clarifying Agent Wallet security model
**trader/hyperliquid_trader.go**:
- Require explicit main wallet address (no auto-generation)
- Check if agent address matches main wallet address (security risk indicator)
- Query agent wallet balance and block if excessive
- Display both agent and main wallet addresses for transparency
**web/src/components/AITradersPage.tsx**:
- Add security alert banner explaining Agent Wallet mode
- Separate required inputs for Agent Private Key and Main Wallet Address
- Add field descriptions and validation
### Benefits
-  Aligns with Hyperliquid official security recommendations
-  Maintains design consistency with Aster implementation
-  Multi-layer protection against configuration mistakes
-  Detailed logging for troubleshooting
### Breaking Change
Users must now explicitly provide main wallet address (hyperliquid_wallet_addr).
Old configurations will receive clear error messages with migration guidance.
### Migration Guide
**Before** (single private key):
```json
{
  "hyperliquid_private_key": "0x..."
}
```
**After** (Agent Wallet mode):
```json
{
  "hyperliquid_private_key": "0x...",  // Agent Wallet private key
  "hyperliquid_wallet_addr": "0x..."   // Main Wallet address
}
```
Users can create Agent Wallet on Hyperliquid official website:
https://app.hyperliquid.xyz/ → Settings → API Wallets
Co-authored-by: tinkle-community <tinklefund@gmail.com>
2025-11-07 23:26:56 +08: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
0xYYBB | ZYY | Bobo 518339474f style: convert Traditional Chinese comments to Simplified Chinese (#662)
## Problem
The codebase contains mixed Traditional Chinese (繁體中文) and Simplified Chinese (简体中文)
in comments and error messages, causing:
- Inconsistent code style
- Reduced readability for mainland Chinese developers
- Maintenance overhead when reviewing diffs
### Affected Files
- **trader/hyperliquid_trader.go**: 8 occurrences
- **trader/binance_futures.go**: 2 occurrences
## Solution
Convert all Traditional Chinese characters to Simplified Chinese to unify code style.
### Conversion Map
| Traditional | Simplified | Context |
|-------------|-----------|---------|
| 處理 | 处理 | "正確處理" → "正确处理" |
| 總資產 | 总资产 | "總資產" → "总资产" |
| 餘額 | 余额 | "可用餘額" → "可用余额" |
| 實現 | 实现 | "未實現盈虧" → "未实现盈亏" |
| 來 | 来 | "僅來自" → "仅来自" |
| 現貨 | 现货 | "現貨餘額" → "现货余额" |
| 單獨 | 单独 | "單獨返回" → "单独返回" |
| 開倉 | 开仓 | "開倉金額" → "开仓金额" |
| 數量 | 数量 | "開倉數量" → "开仓数量" |
| 過 | 过 | "過小" → "过小" |
| 為 | 为 | "後為" → "后为" |
| 後 | 后 | "格式化後" → "格式化后" |
| 建議 | 建议 | "建議增加" → "建议增加" |
| 選擇 | 选择 | "選擇價格" → "选择价格" |
| 幣種 | 币种 | "幣種" → "币种" |
## Changes
### trader/hyperliquid_trader.go (8 locations)
**Line 173-181**: Balance calculation comments
```diff
-//  Step 5: 正確處理 Spot + Perpetuals 余额
-// 重要:Spot 只加到總資產,不加到可用餘額
+//  Step 5: 正确处理 Spot + Perpetuals 余额
+// 重要:Spot 只加到总资产,不加到可用余额
-result["totalWalletBalance"] = totalWalletBalance      // 總資產(Perp + Spot)
-result["availableBalance"] = availableBalance          // 可用餘額(僅 Perpetuals,不含 Spot)
-result["totalUnrealizedProfit"] = totalUnrealizedPnl   // 未實現盈虧(僅來自 Perpetuals)
-result["spotBalance"] = spotUSDCBalance                // Spot 現貨餘額(單獨返回)
+result["totalWalletBalance"] = totalWalletBalance      // 总资产(Perp + Spot)
+result["availableBalance"] = availableBalance          // 可用余额(仅 Perpetuals,不含 Spot)
+result["totalUnrealizedProfit"] = totalUnrealizedPnl   // 未实现盈亏(仅来自 Perpetuals)
+result["spotBalance"] = spotUSDCBalance                // Spot 现货余额(单独返回)
```
**Line 189-191**: Log output messages
```diff
-log.Printf("  • Perpetuals 可用余额: %.2f USDC (可直接用於開倉)", availableBalance)
-log.Printf("  • 總資產 (Perp+Spot): %.2f USDC", totalWalletBalance)
+log.Printf("  • Perpetuals 可用余额: %.2f USDC (可直接用于开仓)", availableBalance)
+log.Printf("  • 总资产 (Perp+Spot): %.2f USDC", totalWalletBalance)
```
### trader/binance_futures.go (2 locations)
**Line 301, 355**: Error messages for insufficient quantity
```diff
-return nil, fmt.Errorf("开倉數量過小,格式化後為 0 (原始: %.8f → 格式化: %s)。建議增加開倉金額或選擇價格更低的幣種", quantity, quantityStr)
+return nil, fmt.Errorf("开仓数量过小,格式化后为 0 (原始: %.8f → 格式化: %s)。建议增加开仓金额或选择价格更低的币种", quantity, quantityStr)
```
## Testing
-  Compilation: Passes `go build`
-  Verification: No Traditional Chinese characters remain in trader/*.go
-  Functionality: No logic changes, only text updates
## Impact
-  Unified code style (100% Simplified Chinese)
-  Improved readability and maintainability
-  Easier code review for Chinese developers
-  No functional changes or behavior modifications
---
Co-authored-by: tinkle-community <tinklefund@gmail.com>
2025-11-06 19:36:14 -05:00
ERIC LEUNG 5328166018 fix: 删除多定义的方法 (#528) 2025-11-05 20:11:50 +08:00
Icyoung c0cb37252b Merge pull request #434 from zhouyongyou/fix/stop-loss-take-profit-separation
fix(trader): separate stop-loss and take-profit order cancellation to prevent accidental deletions
2025-11-05 16:05:00 +08:00
Icyoung 87e2ba8214 Merge pull request #471 from zhouyongyou/fix/hyperliquid-complete-balance-fix
fix(hyperliquid): complete balance detection with 4 critical fixes
2025-11-05 15:47:15 +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
ZhouYongyou 40ae31b583 fix(hyperliquid): complete balance detection with 4 critical fixes
## 🎯 完整修復 Hyperliquid 餘額檢測的所有問題
### 修復 1:  動態選擇保證金摘要
**問題**: 硬編碼使用 MarginSummary,但預設全倉模式
**修復**: 根據 isCrossMargin 動態選擇
- 全倉模式 → CrossMarginSummary
- 逐倉模式 → MarginSummary
### 修復 2:  查詢 Spot 現貨帳戶
**問題**: 只查詢 Perpetuals,忽略 Spot 餘額
**修復**: 使用 SpotUserState() 查詢 USDC 現貨餘額
- 合併 Spot + Perpetuals 總餘額
- 解決用戶反饋「錢包有錢但顯示 0」的問題
### 修復 3:  使用 Withdrawable 欄位
**問題**: 簡單計算 availableBalance = accountValue - totalMarginUsed 不可靠
**修復**: 優先使用官方 Withdrawable 欄位
- 整合 PR #443 的邏輯
- 降級方案:Withdrawable 不可用時才使用簡單計算
- 防止負數餘額
### 修復 4:  清理混亂註釋
**問題**: 註釋說 CrossMarginSummary 但代碼用 MarginSummary
**修復**: 根據實際使用的摘要類型動態輸出日誌
## 📊 修復對比
| 問題 | 修復前 | 修復後 |
|------|--------|--------|
| 保證金摘要選擇 |  硬編碼 MarginSummary |  動態選擇 |
| Spot 餘額查詢 |  從未查詢 |  完整查詢 |
| 可用餘額計算 |  簡單相減 |  使用 Withdrawable |
| 日誌註釋 |  不一致 |  準確清晰 |
## 🧪 測試場景
-  Spot 有錢,Perp 沒錢 → 正確顯示 Spot 餘額
-  Spot 沒錢,Perp 有錢 → 正確顯示 Perp 餘額
-  兩者都有錢 → 正確合併顯示
-  全倉模式 → 使用 CrossMarginSummary
-  逐倉模式 → 使用 MarginSummary
## 相關 Issue
解決用戶反饋:「錢包中有幣卻沒被檢測到」
整合以下未合併的修復:
- PR #443: Withdrawable 欄位優先
- Spot 餘額遺漏問題
Co-Authored-By: tinkle-community <tinklefund@gmail.com>
2025-11-05 03:59:44 +08:00
ZhouYongyou c9d5aed1b6 fix(trader): separate stop-loss and take-profit order cancellation to prevent accidental deletions
## Problem
When adjusting stop-loss or take-profit levels, `CancelStopOrders()` deleted BOTH stop-loss AND take-profit orders simultaneously, causing:
- **Adjusting stop-loss** → Take-profit order deleted → Position has no exit plan 
- **Adjusting take-profit** → Stop-loss order deleted → Position unprotected 
**Root cause:**
```go
CancelStopOrders(symbol) {
  // Cancelled ALL orders with type STOP_MARKET or TAKE_PROFIT_MARKET
  // No distinction between stop-loss and take-profit
}
```
## Solution
### 1. Added new interface methods (trader/interface.go)
```go
CancelStopLossOrders(symbol string) error      // Only cancel stop-loss orders
CancelTakeProfitOrders(symbol string) error    // Only cancel take-profit orders
CancelStopOrders(symbol string) error          // Deprecated (cancels both)
```
### 2. Implemented for all 3 exchanges
**Binance (trader/binance_futures.go)**:
- `CancelStopLossOrders`: Filters `OrderTypeStopMarket | OrderTypeStop`
- `CancelTakeProfitOrders`: Filters `OrderTypeTakeProfitMarket | OrderTypeTakeProfit`
- Full order type differentiation 
**Hyperliquid (trader/hyperliquid_trader.go)**:
- ⚠️ Limitation: SDK's OpenOrder struct doesn't expose trigger field
- Both methods call `CancelStopOrders` (cancels all pending orders)
- Trade-off: Safe but less precise
**Aster (trader/aster_trader.go)**:
- `CancelStopLossOrders`: Filters `STOP_MARKET | STOP`
- `CancelTakeProfitOrders`: Filters `TAKE_PROFIT_MARKET | TAKE_PROFIT`
- Full order type differentiation 
### 3. Usage in auto_trader.go
When `update_stop_loss` or `update_take_profit` actions are implemented, they will use:
```go
// update_stop_loss:
at.trader.CancelStopLossOrders(symbol)  // Only cancel SL, keep TP
at.trader.SetStopLoss(...)
// update_take_profit:
at.trader.CancelTakeProfitOrders(symbol)  // Only cancel TP, keep SL
at.trader.SetTakeProfit(...)
```
## Impact
-  Adjusting stop-loss no longer deletes take-profit
-  Adjusting take-profit no longer deletes stop-loss
-  Backward compatible: `CancelStopOrders` still exists (deprecated)
- ⚠️ Hyperliquid limitation: still cancels all orders (SDK constraint)
## Testing
-  Compiles successfully across all 3 exchanges
- ⚠️ Requires live testing:
  - [ ] Binance: Adjust SL → verify TP remains
  - [ ] Binance: Adjust TP → verify SL remains
  - [ ] Hyperliquid: Verify behavior with limitation
  - [ ] Aster: Verify order filtering works correctly
## Code Changes
```
trader/interface.go: +9 lines (new interface methods)
trader/binance_futures.go: +133 lines (3 new functions)
trader/hyperliquid_trader.go: +56 lines (3 new functions)
trader/aster_trader.go: +157 lines (3 new functions)
Total: +355 lines
```
2025-11-04 19:05:54 +08:00
ZhouYongyou c4e72b124f fix: 修復 Hyperliquid CancelStopOrders 編譯錯誤
- OpenOrder 結構不暴露 trigger 字段
- 改為取消該幣種的所有掛單(安全做法)
2025-11-04 16:45:20 +08:00
ZhouYongyou 9884605c75 修復關鍵缺陷:添加 CancelStopOrders 方法避免多個止損單共存
問題:
- 調整止損/止盈時,直接調用 SetStopLoss/SetTakeProfit 會創建新訂單
- 但舊的止損/止盈單仍然存在,導致多個訂單共存
- 可能造成意外觸發或訂單衝突
解決方案(參考 PR #197):
1. 在 Trader 接口添加 CancelStopOrders 方法
2. 為三個交易所實現:
   - binance_futures.go: 過濾 STOP_MARKET/TAKE_PROFIT_MARKET 類型
   - aster_trader.go: 同樣邏輯
   - hyperliquid_trader.go: 過濾 trigger 訂單(有 triggerPx)
3. 在 executeUpdateStopLossWithRecord 和 executeUpdateTakeProfitWithRecord 中:
   - 先調用 CancelStopOrders 取消舊單
   - 然後設置新止損/止盈
   - 取消失敗不中斷執行(記錄警告)
優勢:
-  避免多個止損單同時存在
-  保留我們的價格驗證邏輯
-  保留執行價格記錄
-  詳細錯誤信息
-  取消失敗時繼續執行(更健壯)
測試建議:
- 開倉後調整止損,檢查舊止損單是否被取消
- 連續調整兩次,確認只有最新止損單存在
致謝:參考 PR #197 的實現思路
2025-11-04 16:40:23 +08:00
tangmengqiu 3bb6404fc0 fix pk prefix handle 2025-11-04 00:03:56 -05:00
tangmengqiu 045834dcbe feat(hyperliquid): Auto-generate wallet address from private key
Enable automatic wallet address generation from private key for Hyperliquid
exchange, simplifying user onboarding and reducing configuration errors.
Backend Changes (trader/hyperliquid_trader.go):
- Import crypto/ecdsa package for ECDSA public key operations
- Enable wallet address auto-generation when walletAddr is empty
- Use crypto.PubkeyToAddress() to derive address from private key
- Add logging for both auto-generated and manually provided addresses
Frontend Changes (web/src/components/AITradersPage.tsx):
- Remove wallet address required validation (only private key required)
- Update button disabled state to only check private key
- Add "Optional" label to wallet address field
- Add dynamic placeholder with bilingual hint
- Show context-aware helper text based on input state
- Remove HTML required attribute from input field
Translation Updates (web/src/i18n/translations.ts):
- Add 'optional' translation (EN: "Optional", ZH: "可选")
- Add 'hyperliquidWalletAddressAutoGenerate' translation
  EN: "Leave blank to automatically generate wallet address from private key"
  ZH: "留空将自动从私钥生成钱包地址"
Benefits:
 Simplified UX - Users only need to provide private key
 Error prevention - Auto-generated address always matches private key
 Backward compatible - Manual address input still supported
 Better UX - Clear visual indicators for optional fields
Technical Details:
- Uses Ethereum standard ECDSA public key to address conversion
- Implementation was already present but commented out (lines 37-43)
- No database schema changes required (hyperliquid_wallet_addr already nullable)
- Fallback behavior: manual input > auto-generation
Co-Authored-By: tinkle-community <tinklefund@gmail.com>
2025-11-03 23:15:38 -05:00
hzb1115 62ebd58a1f style(backend): go fmt code 2025-11-03 17:22:11 +00:00
icy 142863f554 Add MarginMode configration 2025-10-31 13:14:24 +08:00
henrylab ed9417195c 1. 修复hyperliquid 总盈亏,总净值计算错误问题
2. 修复持仓盈亏百分比错误,计算公式应该加入杠杆倍数
2025-10-30 22:23:05 +08:00
tinkle-community 5eba8471cf feat: Add trader enabled switch and fix critical bugs
New Features:
- Add 'enabled' field to trader config for selective startup
- Only enabled traders will be initialized and run
- Display skip messages for disabled traders in logs
Bug Fixes:
- Fix Hyperliquid account value calculation
  * AccountValue is total equity, no need to add TotalMarginUsed
  * Correctly calculate wallet balance without unrealized PnL
  * Fix available balance calculation (AccountValue - TotalMarginUsed)
- Fix frontend page refresh navigation issue
  * Use URL hash to persist page state across refreshes
  * Support browser back/forward buttons
  * Prevent Details page from reverting to Competition on refresh
Technical Changes:
- config/config.go: Add Enabled bool field to TraderConfig
- main.go: Skip disabled traders during initialization
- trader/hyperliquid_trader.go: Correct account value logic
- web/src/App.tsx: Implement hash-based routing
Co-Authored-By: tinkle-community <tinklefund@gmail.com>
2025-10-30 21:07:43 +08:00
tinkle-community 004ae60d31 Refactor: Extract availableBalance variable in Hyperliquid trader
Extract availableBalance calculation into a separate variable for better readability.
Co-Authored-By: tinkle-community <tinklefund@gmail.com>
2025-10-30 20:09:30 +08:00
刘 志 887899749f fix: hyperliquid余额不准确 2025-10-30 08:38:31 +00:00
nobody 0164ac6cc0 feat: Add Hyperliquid exchange support with unified trader interface
Major changes:
- Add full Hyperliquid trading support (long/short, leverage, SL/TP)
- Create unified Trader interface for multi-exchange support
- Implement automatic precision handling for orders and prices
- Fix balance calculation and unrealized P&L display
- Add comprehensive configuration guide in README
New features:
- Support for both Binance and Hyperliquid exchanges
- Automatic order size precision based on szDecimals
- Price formatting with 5 significant figures
- Non-custodial trading with Ethereum private key
- Seamless exchange switching via configuration
Technical details:
- Add trader/interface.go for unified trader interface
- Add trader/hyperliquid_trader.go for Hyperliquid implementation
- Update manager and auto_trader to support multiple exchanges
- Add go-hyperliquid SDK dependency
- Fix precision errors (float_to_wire, invalid price)
Fixes:
- Correct calculation of wallet balance and unrealized P&L
- Proper handling of AccountValue vs TotalRawUsd
- Frontend display issues for total equity and P&L
Documentation:
- Add Hyperliquid setup guide in README
- Update config.json.example with both exchanges
- Add troubleshooting section for common errors
Tested with live trading on Hyperliquid mainnet.
No breaking changes - backward compatible with existing configs.
2025-10-29 20:00:30 +08:00