Commit Graph

33 Commits

Author SHA1 Message Date
ZhouYongyou
8a1e931857 fix: prevent initial_balance modification and fix equity history calculation
## 核心問題修復

1. **API 層保護** (api/server.go - handleUpdateTrader)
   - 檢測並阻止任何修改 initial_balance 的嘗試
   - 強制使用原始 initial_balance 值
   - 記錄詳細的警告日誌和嘗試修改的細節
   - 返回友善的錯誤訊息給用戶

2. **資料庫層保護** (config/database.go - UpdateTrader)
   - 從 UPDATE SQL 語句中移除 initial_balance 欄位
   - 雙重防護:即使 API 層被繞過,DB 也不會更新

3. **修復盈虧計算錯誤** (api/server.go - handleEquityHistory)
   -  修復:從資料庫讀取 initial_balance 作為唯一真實來源
   -  移除:錯誤的後備邏輯(使用 records[0].TotalBalance)
   -  重新計算:基於正確的 initial_balance 重算所有盈虧百分比

## 影響範圍

- 用戶無法再通過 UpdateTrader API 修改 initial_balance
- 解決「初始餘額異常變動」的根本原因
- 確保盈虧計算始終基於正確的基準值

## 技術細節

- 浮點數比較容差:0.01 USDT (避免浮點數精度問題)
- 錯誤碼:INITIAL_BALANCE_IMMUTABLE
- 日誌格式:包含 user_id, trader_id, 原值, 請求值, 差異

Related-Issue: 用戶報告「初始餘額變少」問題
2025-11-05 01:54:36 +08:00
ZhouYongyou
e36ffc5a18 feat(api): add manual balance sync endpoint to z-dev
- Add POST /traders/:id/sync-balance endpoint
- Query actual exchange balance and update initial_balance
- Smart detection: shows balance change percentage
- Supports Binance, Hyperliquid, Aster exchanges
- Reload trader into memory after update

This complements the existing auto-query feature (feat/query-actual-balance-v2):
- Auto-query: Prevents issue at creation time
- Manual sync: Fixes issue after deposits/withdrawals

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-04 20:11:40 +08:00
ZhouYongyou
3d565c993e feat: Add SystemPromptTemplate edit support (PR #339)
- Allow users to modify SystemPromptTemplate when editing Trader
- Enable dynamic strategy switching (default/aggressive/conservative)
- Support A/B testing of different trading strategies
- Maintain backward compatibility with existing data
- Complete full data flow from database through UI to persistence
2025-11-03 22:37:11 +08:00
ZhouYongyou
5f6ff9d914 feat: add system_prompt_template to GetTraderConfig response 2025-11-03 22:35:45 +08:00
ZhouYongyou
aef4cf5a09 style: fix alignment in server.go after merge 2025-11-03 22:35:19 +08:00
ZhouYongyou
0745fdf176 feat: Add scan_interval_minutes configuration support (PR #338)
- Allow users to customize AI decision scan interval (1-60 minutes)
- Default 3 minutes, recommended range 3-10 minutes
- Support both high-frequency and low-frequency trading strategies
- Improve trading flexibility and API call efficiency
- Merge with existing actual balance query functionality
2025-11-03 22:34:44 +08:00
Liu Xiang Qian
c1f080f59f feat: 添加前端对 SystemPromptTemplate 更新的完整支持
## 修改内容

### 后端 (api/server.go)
- handleGetTraderConfig 返回中添加 system_prompt_template 字段

### 前端类型定义 (web/src/types.ts)
- TraderConfigData 接口添加 system_prompt_template 字段

### 前端更新逻辑 (web/src/components/AITradersPage.tsx)
- handleSaveEditTrader 的更新请求中添加 system_prompt_template

## 完整数据流

```
后端数据库
  ↓ handleGetTraderConfig
前端 TraderConfigData (包含 system_prompt_template)
  ↓ TraderConfigModal (UI 编辑)
前端 UpdateRequest (包含 system_prompt_template)
  ↓ handleUpdateTrader
后端更新数据库
```

现在前后端已完全打通,用户可以在 UI 中编辑系统提示词模板了。
2025-11-03 22:19:58 +08:00
Liu Xiang Qian
b0de71bdf5 feat: 支持更新 Trader 的系统提示词模板
允许在编辑 Trader 时更新系统提示词模板(SystemPromptTemplate)。

系统提示词模板用于控制 AI 交易决策的行为模式。目前创建 Trader 时可以指定模板,但编辑时无法修改。

1. **UpdateTraderRequest** 添加 `SystemPromptTemplate` 字段
   ```go
   SystemPromptTemplate string `json:"system_prompt_template"`
   ```

2. **handleUpdateTrader** 添加处理逻辑
   - 如果请求中提供新模板,使用新值
   - 如果为空字符串,保持数据库中的原有值

   ```go
   systemPromptTemplate := req.SystemPromptTemplate
   if systemPromptTemplate == "" {
       systemPromptTemplate = existingTrader.SystemPromptTemplate
   }
   ```

3. **TraderRecord** 设置 SystemPromptTemplate 字段
   ```go
   SystemPromptTemplate: systemPromptTemplate,
   ```

-  支持在编辑 Trader 时更新系统提示词模板
-  空值时保持原有值不变(向后兼容)
-  与创建 Trader 时的行为保持一致
-  无破坏性变更

1. 用户创建 Trader 时使用了默认模板
2. 后续想切换到自定义模板(如更激进或保守的策略)
3. 通过编辑功能修改 SystemPromptTemplate 字段
4. 保存后,AI 将使用新的提示词模板进行决策

1. 创建 Trader(使用默认模板 "default")
2. 编辑 Trader,修改 system_prompt_template 为 "aggressive"
3. 保存并验证修改成功
4. 再次编辑,不修改 system_prompt_template(传空字符串)
5. 验证保持 "aggressive" 不变
2025-11-03 22:15:23 +08:00
ZhouYongyou
1d785532a0 fix: Fix AI model validation and 4h kline storage (PR #337)
- Fix AI model validation failure when editing trader
- Fix 4h kline data storage to correct database field
- Remove improper model ID conversion in API layer
- Resolve conflicts: keep complete model ID and continue on 4h fetch error
- Closes NoFxAiOS#335, NoFxAiOS#260
2025-11-03 22:05:32 +08:00
Liu Xiang Qian
8ad85a4a5b revert: 移除 SystemPromptTemplate 相关修改
将 SystemPromptTemplate 功能从扫描间隔 PR 中分离出来,
保持 PR 单一职责。

SystemPromptTemplate 功能将在单独的 PR 中处理。
2025-11-03 22:02:25 +08:00
Liu Xiang Qian
ddf6c44d65 feat: 添加 AI 扫描决策间隔配置支持
## 功能描述

在创建和编辑 Trader 时,支持配置 AI 扫描决策间隔(scan_interval_minutes),允许用户自定义 AI 决策的频率。

## 修改内容

### 后端修改 (api/server.go)

1. **CreateTraderRequest** 添加 `ScanIntervalMinutes` 字段
2. **UpdateTraderRequest** 添加 `ScanIntervalMinutes` 字段和 `SystemPromptTemplate` 字段
3. **handleCreateTrader** 处理扫描间隔默认值(默认 3 分钟)
4. **handleUpdateTrader** 支持更新扫描间隔
5. **handleGetTraderConfig** 返回中添加 `scan_interval_minutes` 字段

### 前端修改

#### web/src/types.ts
- `CreateTraderRequest` 添加 `scan_interval_minutes?` 可选字段
- `TraderConfigData` 添加 `scan_interval_minutes` 必填字段

#### web/src/components/TraderConfigModal.tsx
- 本地 `TraderConfigData` 接口添加 `scan_interval_minutes`
- 初始状态设置默认值为 3 分钟
- 添加 UI 输入框(范围 1-60 分钟)
- Label 优化为 "AI 扫描决策间隔 (分钟)"

#### web/src/components/AITradersPage.tsx
- `handleSaveEditTrader` 的更新请求中添加 `scan_interval_minutes`

#### web/src/components/landing/CommunitySection.tsx
- 修复 TypeScript 编译错误:定义 `CardProps` 接口
- 修正 `TestimonialCard` 组件的 prop 名称(author → authorName)

## 功能特性

-  支持 1-60 分钟的自定义间隔
-  默认值为 3 分钟
-  UI 提示建议范围:3-10 分钟
-  创建和编辑时均支持配置
-  后端验证和处理默认值

## 测试步骤

1. 创建新 Trader,设置自定义扫描间隔(如 10 分钟)
2. 验证 Trader 创建成功
3. 编辑现有 Trader,修改扫描间隔
4. 验证修改保存成功
5. 确认 AI 决策按照新的间隔执行
2025-11-03 21:55:26 +08:00
Liu Xiang Qian
3dfdd79a8c fix: 修复编辑 Trader 时 AI 模型验证失败的问题
## 问题描述
编辑 Trader 配置时,保存提示"AI模型配置不存在或未启用"错误。

## 根本原因
- 数据库存储的模型 ID 是完整格式(如 `admin_deepseek`)
- API 返回时将其转换为 provider 格式(`deepseek`)
- 前端 enabledModels 列表中是完整 ID
- 导致前端用 `deepseek` 查找 `admin_deepseek` 时失败

## 修复方案
移除 handleGetTraderConfig 中的模型 ID 转换逻辑,
返回完整的模型 ID,保持与前端模型列表格式一致。

Fixes #335
2025-11-03 21:52:44 +08:00
ZhouYongyou
7f87478ee1 refactor: align variable naming and add Binance time sync
1. Rename `traderRecord` to `trader` in handleCreateTrader
   - Aligns with upstream naming convention (nofxaios/dev)
   - Line 403: variable definition
   - Line 424: CreateTrader call

2. Add Binance server time synchronization (PR #145 simple fix)
   - Fixes timestamp errors (code=-1021)
   - Sets UseTestnet=false (ensure production network)
   - Syncs server time on trader initialization
   - Based on commit 64299c1 from pr-145 branch

Both changes improve compatibility with upstream and prevent
timestamp-related API failures.
2025-11-03 21:03:55 +08:00
ZhouYongyou
4e8af52a24 fix(api): query actual exchange balance when creating trader
Problem:
- Users could input arbitrary initial balance when creating traders
- This didn't reflect the actual available balance in exchange account
- Could lead to incorrect position sizing and risk calculations

Solution:
- Before creating trader, query exchange API for actual balance
- Use GetBalance() from respective trader implementation:
  * Binance: NewFuturesTrader + GetBalance()
  * Hyperliquid: NewHyperliquidTrader + GetBalance()
  * Aster: NewAsterTrader + GetBalance()
- Extract 'available_balance' or 'balance' from response
- Override user input with actual balance
- Fallback to user input if query fails

Changes:
- Added 'nofx/trader' import
- Query GetExchanges() to find matching exchange config
- Create temporary trader instance based on exchange type
- Call GetBalance() to fetch actual available balance
- Use actualBalance instead of req.InitialBalance
- Comprehensive error handling with fallback logic

Benefits:
-  Ensures accurate initial balance matches exchange account
-  Prevents user errors in balance input
-  Improves position sizing accuracy
-  Maintains data integrity between system and exchange

Example logs:
✓ 查询到交易所实际余额: 150.00 USDT (用户输入: 100.00 USDT)
⚠️ 查询交易所余额失败,使用用户输入的初始资金: connection timeout

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-03 20:30:00 +08:00
ZhouYongyou
366ae87077 style: format Go code with go fmt
- Fix formatting issues flagged by PR advisory checks
- Run go fmt ./... on all Go files
- No functional changes, code style improvements only

Files formatted:
- api/server.go
- auth/auth.go
- decision/engine.go
- logger/decision_logger.go
- manager/trader_manager.go
- market/monitor.go
- market/types.go
- mcp/client.go
- trader/*.go (aster, auto, binance, hyperliquid)
2025-11-03 19:35:41 +08:00
ZhouYongyou
ab3cab9a93 fix: 統一 handleTraderList 返回完整 AI model ID(保持與 handleGetTraderConfig 一致)
問題:
- handleTraderList 仍在截斷 AI model ID (admin_deepseek → deepseek)
- 與 handleGetTraderConfig 返回的完整 ID 不一致
- 導致前端 isModelInUse 檢查失效

修復:
- 移除 handleTraderList 中的截斷邏輯
- 返回完整 AIModelID (admin_deepseek)
- 與其他 API 端點保持一致

測試:
- GET /api/traders → ai_model: admin_deepseek ✓
- GET /api/traders/:id → ai_model: admin_deepseek ✓
- 模型使用檢查邏輯正確 ✓
2025-11-02 07:11:57 +08:00
ZhouYongyou
04419b47e6 fix: 修复编辑交易员时「AI模型配置不存在或未启用」错误
问题:
- 编辑交易员并修改系统提示词模板时,保存失败
- 错误提示:AI模型配置不存在或未启用

根本原因:
1. 后端 API 返回的 ai_model 被截断(admin_deepseek → deepseek)
2. 前端验证时找不到对应的模型 ID(enabledModels 存的是完整 ID)
3. API 缺少 system_prompt_template 字段

修复内容:
- api/server.go: 移除 AI model ID 截断逻辑,返回完整 ID
- api/server.go: 在 handleGetTraderConfig 中添加 system_prompt_template 字段
- web/src/types.ts: TraderConfigData 接口添加 system_prompt_template 字段
- web/src/components/AITradersPage.tsx: 添加 fallback 机制和详细日志

测试:
- 编辑交易员 → 修改系统提示词模板 → 保存成功
- Console 输出验证日志,不再报错
2025-11-02 04:51:30 +08:00
icy
2cc91d1701 Remote auth for prompt templates 2025-11-01 20:25:55 +08:00
icy
2538d2f928 Merge branch 'dev' of https://github.com/tinkle-community/nofx 2025-11-01 20:09:17 +08:00
SkywalkerJi
4250c11ddf Supports custom system prompts and custom models. 2025-11-01 19:45:54 +08:00
icy
996b152eba Resolve merge conflicts in AITradersPage.tsx
- Fixed import statement conflict (using 'type Language')
- Merged exchange configuration logic preserving support for multiple exchange types
- Kept comprehensive form handling for Binance, Hyperliquid, Aster, and OKX exchanges
- Updated security warning messages to use proper translation keys

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-01 19:01:44 +08:00
icy
f413f87f39 Fixed health check; Fixed dex config; Add rank trader info view; 2025-11-01 18:58:32 +08:00
SkywalkerJi
48d1320209 * Fixed the custom model URL.
*   Added functionality for custom model names.
2025-11-01 16:09:15 +08:00
icy
a7cc5e5ed4 竞赛fix、交易员新增参数 2025-11-01 02:17:11 +08:00
icy
d0621265aa Add MarginMode configration 2025-10-31 13:14:24 +08:00
icy
a85d38cb59 rename fix 2025-10-31 04:07:14 +08:00
icy
ac7c40632d account system、custom prompt 2025-10-31 03:42:01 +08:00
icy
ec25de08d6 Merge remote tracking branch into local development
- Resolved conflicts in README.md: Combined web-based config updates with multi-exchange support
- Resolved conflicts in main.go: Fixed database initialization and default coin settings
- Resolved conflicts in manager/trader_manager.go: Updated trader management for new database structure
- Resolved conflicts in web/src/App.tsx: Combined UI improvements with responsive design
- Resolved conflicts in web/.dockerignore: Merged dependency exclusions
- Removed deprecated files: Dockerfile, config/config.go, web/Dockerfile, ComparisonChart.tsx, CompetitionPage.tsx

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-30 20:57:57 +08:00
icy
4f5b8b250a sync fork 2025-10-30 20:51:22 +08:00
tinkle
9139407739 Fix: Resolve Trade History data loss and P&L calculation errors
Major fixes:
1. Trade History data loss issue
   - Root cause: Open records outside analysis window caused close matching failures
   - Solution: Pre-populate position state by reading 3x window of historical records
   - Ensures long-term positions (>5 hours) generate correct trade records

2. P&L calculation errors
   - Remove incorrect leverage multiplication from absolute P&L
   - Correct calculation: Futures P&L = quantity × price difference
   - Leverage only affects P&L percentage (relative to margin)

3. Other fixes
   - Break-even trades (pnl=0) no longer misclassified as losses
   - Perfect strategy shows Profit Factor as 999.0 instead of 0.0
   - Expand analysis window from 20 to 100 cycles (5 hours)

Files changed:
- logger/decision_logger.go: Core matching and calculation logic
- api/server.go: API analysis window
- trader/auto_trader.go: AI decision analysis window

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-30 17:58:25 +08:00
yiplee
b1ba52e15f Change health check endpoint to accept any HTTP method for improved flexibility. 2025-10-30 13:00:17 +08:00
tinkle
14ffb0593a Update: Merge nofx improvements
- Frontend trading records and UI enhancements
- Optimized AI prompts and decision engine
- Performance analysis and comparison features
- Binance-style UI improvements
2025-10-28 21:45:28 +08:00
tinkle
7e8a494ed3 Initial commit: NOFX AI Trading System
- Multi-AI competition mode (Qwen vs DeepSeek)
- Binance Futures integration
- AI self-learning mechanism
- Professional web dashboard
- Complete risk management system
2025-10-28 15:47:34 +08:00