Commit Graph

550 Commits

Author SHA1 Message Date
0xYYBB | ZYY | Bobo
b48dfe7bfd 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

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude <noreply@anthropic.com>
2025-11-07 23:26:56 +08:00
0xbigtang
28a63f4d48 fix: admin logout button visibility (#650) 2025-11-07 22:52:03 +08:00
SkywalkerJi
ec44477269 refactor(decision): use XML tags to separate reasoning from JSON decisions (#719)
* Separate the AI's thought process from the instruction JSON using XML tags.

* Avoid committing encryption key related materials to Git.

* Removing adaptive series prompts, awaiting subsequent modifications for compatibility.
2025-11-07 22:35:53 +08:00
0xYYBB | ZYY | Bobo
241c905203 refactor(prompts): upgrade to v6.0.0 with enhanced safety rules (#712)
## 🎯 Motivation

Based on extensive production usage and user feedback, we've developed a more comprehensive prompt system with:
- Stronger risk management rules
- Better handling of partial_close and update_stop_loss
- Multiple strategy templates for different risk profiles
- Enhanced decision quality and consistency

## 📊 What's Changed

### 1. Prompt System v6.0.0

All prompts now follow a standardized format with:
- **Version header**: Clear versioning (v6.0.0)
- **Strategy positioning**: Conservative/Moderate/Relaxed/Altcoin
- **Core parameters**: Confidence thresholds, cooldown periods, BTC confirmation requirements
- **Unified structure**: Consistent across all templates

### 2. New Strategy Templates

Added two new templates to cover different trading scenarios:

- `adaptive_altcoin.txt` - Optimized for altcoin trading
  - Higher leverage limits (10x-15x)
  - More aggressive position sizing
  - Faster decision cycles

- `adaptive_moderate.txt` - Balanced strategy
  - Medium risk tolerance
  - Flexible BTC confirmation
  - Suitable for most traders

### 3. Enhanced Safety Rules

#### partial_close Safety (Addresses #301)
```
⚠️ Mandatory Check:
- Before partial_close, calculate: remaining_value = current_value × (1 - close_percentage/100)
- If remaining_value ≤ $10 → Must use close_long/close_short instead
- Prevents "Order must have minimum value of $10" exchange errors
```

#### update_stop_loss Threshold Rules
```
⚠️ Strict Rules:
- Profit <3% → FORBIDDEN to move stop-loss (avoid premature trailing)
- Profit 3-5% → Can move to breakeven
- Profit ≥10% → Can move to entry +5% (lock partial profit)
```

#### TP/SL Restoration After partial_close
```
⚠️ Important:
- Exchanges auto-cancel TP/SL orders when position size changes
- Must provide new_stop_loss + new_take_profit with partial_close
- Otherwise remaining position has NO protection (liquidation risk)
```

### 4. Files Changed

- `prompts/adaptive.txt` - Conservative strategy (v6.0.0)
- `prompts/adaptive_relaxed.txt` - Relaxed strategy (v6.0.0)
- `prompts/adaptive_altcoin.txt` - NEW: Altcoin-optimized strategy
- `prompts/adaptive_moderate.txt` - NEW: Balanced strategy

## 🔗 Related Issues

- Closes #301 (Prompt layer safety rules)
- Related to #418 (Same validation issue)
- Complements PR #415 (Backend implementation)

##  Testing

- [x] All 4 templates follow v6.0.0 format
- [x] partial_close safety rules included
- [x] update_stop_loss threshold rules included
- [x] TP/SL restoration warnings included
- [x] Strategy-specific parameters validated

## 📝 Notes

This PR focuses on **prompt layer enhancements only**.

Backend safety checks (trader/auto_trader.go) will be submitted in a separate PR for easier review.

The two PRs can be merged independently or together - they complement each other:
- This PR: AI makes better decisions (prevent bad actions)
- Next PR: Backend validates and auto-corrects (safety net)

---

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude <noreply@anthropic.com>
2025-11-07 20:30:17 +08:00
Linden
a3b025f028 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
Shui
51e22c0c88 fix(bootstrap module): add bootstrap module to meet future function (#674)
* fix(bootstrap module): add bootstrap module to meet future function

* Fix readme

* Fix panic because log.logger is nil

* fix import

---------

Co-authored-by: zbhan <zbhan@freewheel.tv>
2025-11-07 10:53:10 +08:00
Shui
90af9dbca6 Revert "fix(web): prevent NaN% display in competition gap calculation (#633) …" (#676)
This reverts commit 8db6dc3b06.
2025-11-06 20:58:13 -05:00
0xYYBB | ZYY | Bobo
8db6dc3b06 fix(web): prevent NaN% display in competition gap calculation (#633) (#670)
**Problem:**
Competition page shows "NaN%" for gap difference when trader P&L
percentages are null/undefined.

**Root Cause:**
Line 227: `const gap = trader.total_pnl_pct - opponent.total_pnl_pct`
- If either value is `undefined` or `null`, result is `NaN`
- Display shows "领先 NaN%" or "落后 NaN%"

**Solution:**
Add null coalescing to default undefined/null values to 0:
```typescript
const gap = (trader.total_pnl_pct ?? 0) - (opponent.total_pnl_pct ?? 0)
```

**Impact:**
-  Gap calculation returns 0 when data is missing (shows 0.00%)
-  Prevents confusing "NaN%" display
-  Graceful degradation for incomplete data

Fixes #633

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude <noreply@anthropic.com>
2025-11-06 20:35:58 -05:00
0xYYBB | ZYY | Bobo
4f2177a0a0 fix(prompts): reduce margin usage from 95% to 88% for Hyperliquid liquidation buffer (#666)
## Problem
Users with small accounts (<$200) encounter Hyperliquid error:
"Insufficient margin to place order. asset=1"

Real case: $98.89 account failed to open position

## Root Cause
5% reserve insufficient for:
- Trading fees (~0.04%)
- Slippage (0.01-0.1%)
- Liquidation margin buffer (Hyperliquid requirement)

Additionally, undefined "Allocation %" parameter caused confusion.

## Solution
1. Reduce margin usage rate from 95% to 88% (reserve 12%)
2. Remove undefined "Allocation %" parameter
3. Add small account example ($98.89) for clarity

## Example ($98.89 account)
Before: $93.95 margin → $4.75 remaining 
After:  $87.02 margin → $11.87 remaining 

## Modified Files
- prompts/adaptive.txt
- prompts/default.txt
- prompts/nof1.txt

## Testing
Verified with $98.89 account on z-dev branch - successful order placement

Fixes #549
2025-11-07 09:19:20 +08:00
ZhouYongyou
8ce0adf62a fix(prompts): correct risk_usd formula - remove duplicate leverage multiplication
## Problem (Issue #592)
risk_usd formula incorrectly multiplies leverage twice:
- Incorrect: risk_usd = |Entry - Stop| × Position Size × Leverage 

This causes AI to calculate risk as 10x (or leverage倍) higher than actual.

## Root Cause
Position Size already includes leverage effect:
- Position Size (coins) = position_size_usd / price
- position_size_usd = margin × leverage
- Therefore: Position Size = (margin × leverage) / price

Multiplying leverage again amplifies risk calculation by "leverage" times.

## Example
Scenario: $100 margin, 10x leverage, 0.02 BTC position, $500 stop distance

**Correct calculation:**
risk_usd = $500 × 0.02 = $10 
Risk % = 10% of margin (reasonable)

**Incorrect calculation (current):**
risk_usd = $500 × 0.02 × 10 = $100 
Risk % = 100% of margin (completely wrong!)

## Impact
- AI miscalculates risk as "leverage" times higher
- May refuse valid trades thinking risk is too high
- Risk control logic becomes ineffective
- Potential for position sizing errors

## Solution
Correct formula: risk_usd = |Entry - Stop| × Position Size (coins)

Added warnings:
- CN: ⚠️ 不要再乘杠杆:仓位数量已包含杠杆效应
- EN: ⚠️ Do NOT multiply by leverage: Position Size already includes leverage effect

## Modified Files
- prompts/adaptive.txt (line 404)
- prompts/nof1.txt (line 104)

Closes #592
2025-11-07 08:46:37 +08:00
0xYYBB | ZYY | Bobo
4d7b28a600 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

---

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude <noreply@anthropic.com>
2025-11-06 19:36:14 -05:00
SkywalkerJi
12512ff7f3 fix: Fixed go vet issues. (#658)
* Fixed vet ./... errors.

* Fixed ESLint issues.
2025-11-07 02:28:01 +08:00
SkywalkerJi
26d7c337fe Add Terms of Service (#656)
* Add Privacy Policy

* Add Terms of Service
2025-11-07 02:16:05 +08:00
SkywalkerJi
25f971aeb8 Add Privacy Policy (#655) 2025-11-07 01:54:25 +08:00
0xYYBB | ZYY | Bobo
cad984b220 fix(web): restore ESLint, Prettier, and Husky code quality tools (#648)
## Problem
PR #647 accidentally removed all code quality tools when adding test dependencies:
-  ESLint (9 packages) - code linting
-  Prettier - code formatting
-  Husky - Git hooks
-  lint-staged - pre-commit checks
-  Related scripts (lint, format, prepare)

This significantly impacts code quality and team collaboration.

## Root Cause
When adding test dependencies (vitest, @testing-library/react), the package.json
was incorrectly edited, removing all existing devDependencies.

## Solution
Restore all code quality tools while keeping the new test dependencies:

###  Restored packages:
- @eslint/js
- @typescript-eslint/eslint-plugin
- @typescript-eslint/parser
- eslint + plugins (prettier, react, react-hooks, react-refresh)
- prettier
- husky
- lint-staged

###  Kept test packages:
- @testing-library/jest-dom
- @testing-library/react
- jsdom
- vitest

###  Restored scripts:
```json
{
  "lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
  "lint:fix": "eslint . --ext ts,tsx --fix",
  "format": "prettier --write \"src/**/*.{ts,tsx,css,json}\"",
  "format:check": "prettier --check \"src/**/*.{ts,tsx,css,json}\"",
  "test": "vitest run",
  "prepare": "husky"
}
```

###  Restored lint-staged config

## Impact
This fix restores:
- Automated code style enforcement
- Pre-commit quality checks
- Consistent code formatting
- Team collaboration standards

## Testing
- [x] npm install succeeds
- [x] npm run build succeeds
- [x] All scripts are functional

Related-To: PR #647

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude <noreply@anthropic.com>
2025-11-07 01:30:13 +08:00
tinkle
fa0cc5e064 update link 2025-11-07 01:26:18 +08:00
0xYYBB | ZYY | Bobo
d4f1e6a4d4 fix(web): resolve TypeScript type error in crypto.ts and add missing test dependencies (#647)
```
src/lib/crypto.ts(66,32): error TS2345: Argument of type 'Uint8Array<ArrayBuffer>'
is not assignable to parameter of type 'ArrayBuffer'.
```

`arrayBufferToBase64` function expected `ArrayBuffer` but received `Uint8Array.buffer`.
TypeScript strict type checking flagged the mismatch.

1. Update `arrayBufferToBase64` signature to accept `ArrayBuffer | Uint8Array`
2. Pass `result` directly instead of `result.buffer` (more accurate)
3. Add runtime type check with instanceof

```
error TS2307: Cannot find module 'vitest'
error TS2307: Cannot find module '@testing-library/react'
```

Install missing devDependencies:
- vitest
- @testing-library/react
- @testing-library/jest-dom

 Frontend builds successfully
 TypeScript compilation passes
 No type errors

Related-To: Docker frontend build failures
2025-11-07 01:19:48 +08:00
ZhouYongyou
617f08c9c6 refactor(crypto): simplify to local encryption only (remove KMS)
## 🎯 簡化方案(社區友好)

### 移除雲端 KMS
-  刪除 crypto/aliyun_kms.go
-  不包含 GCP KMS
-  僅保留本地 AES-256-GCM 加密

### 更新 SQLite 驅動
-  modernc.org/sqlite(純 Go,無 CGO)
-  與上游保持一致

## 📦 保留核心功能

 crypto/encryption.go        - RSA + AES 加密
 crypto/secure_storage.go    - 數據庫加密層
 api/crypto_handler.go       - API 端點
 web/src/lib/crypto.ts       - 前端加密
 scripts/migrate_encryption.go - 數據遷移

## 🚀 部署方式

```bash
# 僅需一個環境變量
export NOFX_MASTER_KEY=$(openssl rand -base64 32)
go run main.go
```

##  優點

-  零雲服務依賴
-  簡單易部署
-  適合社區用戶
-  保持核心安全功能
2025-11-06 23:58:27 +08:00
ZhouYongyou
8c575a0613 feat(security): add end-to-end encryption for sensitive data
## Summary
Add comprehensive encryption system to protect private keys and API secrets.

## Core Components
- `crypto/encryption.go`: RSA-4096 + AES-256-GCM encryption manager
- `crypto/secure_storage.go`: Database encryption layer + audit logs
- `crypto/aliyun_kms.go`: Optional Aliyun KMS integration
- `api/crypto_handler.go`: Encryption API endpoints
- `web/src/lib/crypto.ts`: Frontend two-stage encryption
- `scripts/migrate_encryption.go`: Data migration tool
- `deploy_encryption.sh`: One-click deployment

## Security Architecture
```
Frontend: Two-stage input + clipboard obfuscation
    ↓
Transport: RSA-4096 + AES-256-GCM hybrid encryption
    ↓
Storage: Database encryption + audit logs
```

## Features
 Zero breaking changes (backward compatible)
 Automatic migration of existing data
 <25ms overhead per operation
 Complete audit trail
 Optional cloud KMS support

## Migration
```bash
./deploy_encryption.sh  # 5 minutes, zero downtime
```

## Testing
```bash
go test ./crypto -v
```

Related-To: security-enhancement
2025-11-06 23:55:33 +08:00
Lawrence Liu
0b5d08f18a fix(web): 修正 FAQ 翻译文件中的错误信息 (#552)
- 删除 OKX 虚假支持声明(后端未实现)
- 补充 Aster DEX 的 API 配置说明
- 修正测试网说明为暂时不支持
2025-11-06 21:59:10 +08:00
Burt
f863d4e389 Fix: 提示词, 竞赛数据接口在管理员模式下转为公开 (#607)
* 提示词, 竞赛数据接口在管理员模式下转为公开

* Fix "go vet" error
2025-11-06 20:42:43 +08:00
ZhouYongyou
c5bd2d9d98 Merge branch 'dev' of https://github.com/NoFxAiOS/nofx into fix/stop-loss-take-profit-method-calls 2025-11-06 14:20:35 +08:00
Ember
ef12e9153a bugfix/ fix delete AI Model issue (#594)
* fix: 修复删除AI模型/交易所后UI未刷新的问题

问题描述:
在配置界面删除AI模型或交易所后,虽然后端数据已更新,但前端UI仍然显示已删除的配置项。

根本原因:
React的状态更新机制可能无法检测到数组内容的变化,特别是当API返回的数据与之前的引用相同时。

修复方案:
在 handleDeleteModelConfig 和 handleDeleteExchangeConfig 中使用数组展开运算符 [...items] 创建新数组,确保React能够检测到状态变化并触发重新渲染。

修改文件:
- web/src/components/AITradersPage.tsx

影响范围:
- AI模型删除功能
- 交易所删除功能

Fixes #591

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* fix: 删除重复的确认对话框

问题描述:
删除AI模型或交易所时,确认对话框会弹出两次

根本原因:
1. ModelConfigModal 的删除按钮 onClick 中有一个 confirm
2. handleDeleteConfig 函数内部也有一个 confirm

修复方案:
移除 Modal 组件中的 confirm,保留 handleDeleteConfig 内部的确认逻辑,因为它包含了更完整的依赖检查功能

修改内容:
- 移除 ModelConfigModal 删除按钮中的 confirm
- 移除 ExchangeConfigModal 删除按钮中的 confirm
- 更新 title 属性为更合适的翻译键

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

---------

Co-authored-by: Claude <noreply@anthropic.com>
2025-11-06 12:25:25 +08:00
Sue
7edc636d3f fix: validate config.db is file not directory (#586)
修复 config.db 验证逻辑,处理误创建为目录的情况:
- 检测 config.db 是否为目录,如果是则删除并重建为文件
- 保留已存在的数据库文件不受影响
- 修复 Docker volume 挂载可能导致的目录创建问题

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude <noreply@anthropic.com>
2025-11-06 10:38:53 +08:00
Diego
ed737e08d6 fix: 修复删除模型/交易所时界面卡死问题并增强依赖检查 (#578)
* fix: 修复删除模型/交易所时界面卡死问题并增强依赖检查

## 问题描述
1. 删除唯一的AI模型或交易所配置时,界面会卡死数秒
2. 删除后配置仍然显示在列表中
3. 可以删除被交易员使用的配置,导致数据不一致

## 修复内容

### 后端性能优化 (manager/trader_manager.go)
- 将循环内的重复数据库查询移到循环外
- 减少N次重复查询(GetAIModels + GetExchanges)为1次查询
- 大幅减少锁持有时间,从数秒降至毫秒级

### 前端显示修复 (web/src/components/AITradersPage.tsx)
- 过滤显示列表,只显示真正配置过的模型/交易所(有apiKey的)
- 删除后重新从后端获取最新数据,确保界面同步

### 前端依赖检查 (web/src/components/AITradersPage.tsx)
- 新增完整的依赖检查,包括停止状态的交易员
- 删除前检查是否有交易员使用该配置
- 显示使用该配置的交易员名称列表
- 阻止删除被使用的配置,保证数据一致性

### 多语言支持 (web/src/i18n/translations.ts)
- 添加依赖检查相关的中英文提示文本
- cannotDeleteModelInUse / cannotDeleteExchangeInUse
- tradersUsing / pleaseDeleteTradersFirst

## 测试建议
1. 创建交易员后尝试删除其使用的模型/交易所,应显示警告并阻止删除
2. 删除未使用的模型/交易所,应立即从列表消失且界面不卡死
3. 刷新页面后,已删除的配置不应再出现

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor: 重构删除配置函数减少重复代码

## 重构内容
- 创建通用的 handleDeleteConfig 函数
- 使用配置对象模式处理模型和交易所的删除逻辑
- 消除 handleDeleteModelConfig 和 handleDeleteExchangeConfig 之间的重复代码

## 重构效果
- 减少代码行数约 40%
- 提高代码可维护性和可读性
- 便于未来添加新的配置类型

## 功能保持不变
- 依赖检查逻辑完全相同
- 删除流程完全相同
- 用户体验完全相同

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

---------

Co-authored-by: Claude <noreply@anthropic.com>
2025-11-06 10:32:30 +08:00
ZhouYongyou
ad603388d8 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
ZhouYongyou
82cb85eb4b fix: 修复 update_stop_loss/update_take_profit 未删除旧订单的BUG
## 问题描述
更新止损止盈时,旧订单没有被删除,导致订单累积。
用户看到多个止损/止盈订单同时存在(如截图所示有4个订单)。

## 根本原因
币安Futures采用双向持仓模式(Hedge Mode),每个symbol可以同时持有LONG和SHORT两个方向的仓位。
取消订单时:
- 创建订单时指定了 PositionSide(LONG/SHORT)
- 取消订单时未遍历所有订单,导致部分订单残留

## 修复内容

### 1. binance_futures.go
- CancelStopLossOrders: 取消所有方向(LONG+SHORT)的止损订单
- CancelTakeProfitOrders: 取消所有方向(LONG+SHORT)的止盈订单
- 添加错误收集机制,记录每个失败的订单
- 增强日志输出,显示订单方向(PositionSide)
- 仅当所有取消都失败时才返回错误

### 2. aster_trader.go
- 同步应用相同的修复逻辑
- 保持多交易所一致性

## 预期效果
- 更新止损时,所有旧止损订单被删除
- 更新止盈时,所有旧止盈订单被删除
- 不会出现订单累积问题
- 更详细的日志输出,方便排查问题

## 测试建议
1. 在双向持仓模式下测试 update_stop_loss
2. 验证旧订单是否全部删除
3. 检查日志中的 positionSide 输出

Related: 用户反馈截图显示4个订单同时存在
2025-11-06 02:57:02 +08:00
杜仲
15da7532c4 Add public routes for supported models and exchanges (#554) 2025-11-06 02:08:24 +08:00
SkywalkerJi
6d26a5cf15 fix: Fixed redundant key input fields and corrected formatting on the frontend. (#566)
* Eliminate redundant key input fields in the front-end.

* go / react Formatting.
2025-11-06 01:16:04 +08:00
0xYYBB | ZYY | Bobo
724366a894 fix(prompts): correct confidence scale from 0-1 to 0-100 to match backend schema (#564)
## Problem

The prompts specified confidence range as 0-1 (float), but the backend code
expects 0-100 (integer). This causes JSON parsing errors when AI outputs
values like 0.85:

```
Error: json: cannot unmarshal number 0.85 into Go struct field Decision.confidence of type int
Result: confidence defaults to 0
```

## Root Cause

**Backend Definition** (decision/engine.go:103):
```go
Confidence int `json:"confidence,omitempty"` // 信心度 (0-100)
```

**Prompts (before fix)**:
- adaptive.txt: "confidence (信心度 0-1)"
- nof1.txt: "confidence (float, 0-1)"

**buildHardSystemPrompt** (decision/engine.go:336):
```go
sb.WriteString("- `confidence`: 0-100(开仓建议≥75)\n")
```

The dynamic system prompt was correct, but the base prompts contradicted it.

## Solution

Update prompt files to use consistent 0-100 integer scale:

### adaptive.txt
- `confidence (信心度 0-1)` → `confidence (信心度 0-100)`
- `<0.85` → `<85`
- `0.85-0.90` → `85-90`
- etc.

### nof1.txt
- `confidence (float, 0-1)` → `confidence (int, 0-100)`
- `0.0-0.3` → `0-30`
- `0.3-0.6` → `30-60`
- etc.

## Impact

-  Fixes JSON parsing errors when AI outputs float values
-  Aligns prompts with backend schema
-  Consistent with buildHardSystemPrompt() output format
-  No breaking changes (backend already expects 0-100)

## Testing

```bash
# Verify backend expects 0-100
grep "Confidence int" decision/engine.go
# Output: Confidence int `json:"confidence,omitempty"` // 信心度 (0-100)

# Verify buildHardSystemPrompt uses 0-100
grep "confidence.*0-100" decision/engine.go
# Output: sb.WriteString("- `confidence`: 0-100(开仓建议≥75)\n")

# Build test
go build ./decision/...  #  PASS
```

## Related

- Addresses schema mismatch mentioned in Issue #557
- Note: confidence field is currently not validated by backend (validateDecision
  does not check confidence value), but correct schema prevents parsing errors

---

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude <noreply@anthropic.com>
2025-11-06 00:35:53 +08:00
SkywalkerJi
1542374b73 fix: Fix README link (#563)
* Resolved front-end linting issues.

* Streamlining Docker Build Scripts

* Leveraging Native ARM64 Runners on GitHub.

* Use lowercase framework names.

* Streamlining dependencies within the README.
2025-11-06 00:31:05 +08:00
0xYYBB | ZYY | Bobo
ca2c428357 fix(decision): add safe fallback when AI outputs only reasoning without JSON (#561)
## 问题 (Problem)
当 AI 只输出思维链分析没有 JSON 决策时,系统会崩溃并报错:
"无法找到JSON数组起始",导致整个交易周期失败,前端显示红色错误。

## 解决方案 (Solution)
1. 添加安全回退机制 (Safe Fallback)
   - 当检测不到 JSON 数组时,自动生成保底决策
   - Symbol: "ALL", Action: "wait"
   - Reasoning 包含思维链摘要(最多 240 字符)

2. 统一注释为简体中文 + 英文对照
   - 关键修复 (Critical Fix)
   - 安全回退 (Safe Fallback)
   - 退而求其次 (Fallback)

## 效果 (Impact)
- 修复前:系统崩溃,前端显示红色错误 "获取AI决策失败"
- 修复后:系统稳定,自动进入 wait 状态,前端显示绿色成功
- 日志记录:[SafeFallback] 标记方便监控和调试

## 设计考量 (Design Considerations)
- 仅在完全找不到 JSON 时触发(区分于格式错误)
- 有 JSON 但格式错误仍然报错(提示需要改进 prompt)
- 保留完整思维链摘要供后续分析
- 避免隐藏真正的问题(格式错误应该暴露)

## 测试 (Testing)
-  正常 JSON 输出:解析成功
-  纯思维链输出:安全回退到 wait
-  JSON 格式错误:继续报错(预期行为)
-  编译通过

## 监控建议 (Monitoring)
可通过日志统计 fallback 频率:
```bash
grep "[SafeFallback]" logs/nofx.log | wc -l
```

如果频率 > 5% 的交易周期,建议检查并改进 prompt 质量。

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude <noreply@anthropic.com>
2025-11-06 00:08:23 +08:00
Ember
b2e4be9152 Feature/faq (#546)
* feat(web): add FAQ page with search, sidebar, and i18n integration; update navigation and routes; include user feedback analysis docs (faq.md)

* docs: add filled frontend PR template for FAQ feature (PR_FRONTEND_FAQ.md)

* docs(web): add Contributing & Tasks FAQ category near top with guidance on using GitHub Projects and PR contribution standards

* feat(web,api): dynamically embed GitHub Projects roadmap in FAQ via /api/roadmap and RoadmapWidget; add env vars for GitHub token/org/project

* chore(docker): pass GitHub roadmap env vars into backend container

* docs(web): update FAQ with fork-based PR workflow, yellow links to roadmap/task dashboard, and contribution incentives; remove dynamic roadmap embed\n\nchore(api,docker): remove /api/roadmap endpoint and related env wiring

* chore: revert unintended changes (.env.example, api/server.go, docker-compose.yml); remove local-only files (PR_FRONTEND_FAQ.md, web/faq.md) from PR

* feat: 添加对重置密码页面的路由支持
2025-11-05 22:39:42 +08:00
SkywalkerJi
e0f1950fe0 fix: Increase Docker build speed by 98%. (#545)
* Resolved front-end linting issues.

* Streamlining Docker Build Scripts

* Leveraging Native ARM64 Runners on GitHub.

* Use lowercase framework names.
2025-11-05 22:24:56 +08:00
Burt
be768d91a3 Feat: Enable admin password in admin mode (#540)
* WIP: save local changes before merging

* Enable admin password in admin mode #374
2025-11-05 21:48:28 +08:00
Sue
db68689475 feat(auth): implement password reset with Google Authenticator verification (#537)
实现忘记密码功能,用户可以通过邮箱和Google Authenticator验证码重置密码。

**后端改动:**
- 添加 `/api/reset-password` 接口
- 实现 `UpdateUserPassword` 数据库方法
- 验证邮箱、OTP和新密码

**前端改动:**
- 新增 `ResetPasswordPage` 组件
- 在登录页面添加"忘记密码"链接
- 实现密码重置表单(新密码、确认密码、OTP验证)
- 添加密码可见性切换功能
- 支持中英文国际化

**安全特性:**
- 要求Google Authenticator验证
- 密码强度验证(最少6位)
- 密码确认匹配检查
- 密码哈希存储

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude <noreply@anthropic.com>
2025-11-05 21:01:18 +08:00
SkywalkerJi
eb515d74e9 Resolved front-end linting issues. (#533) 2025-11-05 20:41:41 +08:00
SkywalkerJi
696e9f6187 Add ja docs (#530)
* docs: add Japanese README

* docs: Update README.ja.md

* docs: add DOCKER_DEPLOY.ja.md

---------

Co-authored-by: Ikko Ashimine <ashimine_ikko_bp@tenso.com>
2025-11-05 20:14:26 +08:00
ERIC LEUNG
2755eb733a fix: 删除多定义的方法 (#528) 2025-11-05 20:11:50 +08:00
CoderMageFox
86d2a07040 docs: clarify Aster only supports EVM wallets, not Solana wallets (#524) 2025-11-05 19:37:27 +08:00
Ember
a7385e5256 fix(web): remove undefined setHyperliquidWalletAddr call in ExchangeConfigModal (#525) 2025-11-05 19:35:57 +08:00
0xYYBB | ZYY | Bobo
0f98e06d9e Revert "fix: hard system prompt (#401)" (#522)
This reverts commit 7dd669a907.
2025-11-05 19:05:09 +08:00
GitBib
dab933faee fix: update go.sum with missing modernc.org/sqlite dependencies (#523) 2025-11-05 19:03:32 +08:00
Theshyx11
df4af06bc7 docs: 添加 config.db Docker 启动失败 bug 修复文档 (#210)
## 问题描述
Docker Compose 首次启动时,config.db 被创建为目录而非文件,
导致 SQLite 数据库初始化失败,容器不断重启。

错误信息: "unable to open database file: is a directory"

## 发现时间
2025-11-02 00:14 (UTC+8)

## 根本原因
docker-compose.yml 中的卷挂载配置:
  - ./config.db:/app/config.db

当本地 config.db 不存在时,Docker 会自动创建同名**目录**。

## 临时解决方案
1. docker-compose down
2. rm -rf config.db
3. touch config.db
4. docker-compose up -d

## 修复时间
2025-11-02 00:22 (UTC+8)

## 新增文件
- BUGFIX_CONFIG_DB_2025-11-02.md: 详细的 bug 修复报告

## 建议改进
- 在 DOCKER_DEPLOY.md 中添加预启动步骤说明
- 考虑在 Dockerfile 中添加自动初始化脚本

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: shy <shy@nofx.local>
Co-authored-by: Claude <noreply@anthropic.com>
2025-11-05 18:21:05 +08:00
Sue
77c99499d7 feat(api): add server IP display for exchange whitelist configuration (#520)
Added functionality to display server public IP address for users to configure exchange API whitelists, specifically for Binance integration.

Backend changes (api/server.go):
- Add GET /api/server-ip endpoint requiring authentication
- Implement getPublicIPFromAPI() with fallback to multiple IP services
- Implement getPublicIPFromInterface() for local network interface detection
- Add isPrivateIP() helper to filter private IP addresses
- Import net package for IP address handling

Frontend changes (web/):
- Add getServerIP() API method in api.ts
- Display server IP in ExchangeConfigModal for Binance
- Add IP copy-to-clipboard functionality
- Load and display server IP when Binance exchange is selected
- Add i18n translations (en/zh) for whitelist IP messages:
  - whitelistIP, whitelistIPDesc, serverIPAddresses
  - copyIP, ipCopied, loadingServerIP

User benefits:
- Simplifies Binance API whitelist configuration
- Shows exact server IP to add to exchange whitelist
- One-click IP copy for convenience

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude <noreply@anthropic.com>
2025-11-05 18:15:33 +08:00
Jupiteriana
7dd669a907 fix: hard system prompt (#401) 2025-11-05 17:45:18 +08:00
CoderMageFox
f7391adff9 feat: add i18n support for candidate coins warnings (#516)
- Add 13 translation keys for candidate coins warnings in both English and Chinese
- Update App.tsx to use t() function for all warning text
- Update AITradersPage.tsx to use t() function for signal source warnings
- Ensure proper internationalization for all user-facing messages

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude <noreply@anthropic.com>
2025-11-05 17:35:38 +08:00
PoorThoth
0c371c834a Change SQLite driver in database configuration (#441)
* Change SQLite driver in database configuration

Replace SQLite driver from 'github.com/mattn/go-sqlite3' to 'modernc.org/sqlite'.

* Update go.mod

---------

Co-authored-by: tinkle-community <tinklefund@gmail.com>
2025-11-05 17:34:29 +08:00
CoderMageFox
2299a0e34f feat: 添加候选币种为0时的前端警告提示 (#515)
* feat: add frontend warnings for zero candidate coins

当候选币种数量为0时,在前端添加详细的错误提示和诊断信息

主要改动:
1. 决策日志中显示候选币种数量,为0时标红警告
2. 候选币种为0时显示详细警告卡片,包含可能原因和解决方案
3. 交易员列表页面添加信号源未配置的全局警告
4. 更新TraderInfo类型定义,添加use_coin_pool和use_oi_top字段

详细说明:
- 在App.tsx的账户状态摘要中添加候选币种显示
- 当候选币种为0时,显示详细的警告卡片,列出:
  * 可能原因(API未配置、连接超时、数据为空等)
  * 解决方案(配置自定义币种、配置API、禁用选项等)
- 在AITradersPage中添加信号源配置检查
  * 当交易员启用了币种池但未配置API时显示全局警告
  * 提供"立即配置信号源"快捷按钮
- 不改变任何后端逻辑,纯UI层面的用户提示改进

影响范围:
- web/src/App.tsx: 决策记录卡片中的警告显示
- web/src/components/AITradersPage.tsx: 交易员列表页警告
- web/src/types.ts: TraderInfo类型定义更新

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* fix: import AlertTriangle from lucide-react in App.tsx

修复TypeScript编译错误:Cannot find name 'AlertTriangle'

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

---------

Co-authored-by: Claude <noreply@anthropic.com>
2025-11-05 17:11:04 +08:00
zcan
986886b291 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