Commit Graph

21 Commits

Author SHA1 Message Date
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