Commit Graph

445 Commits

Author SHA1 Message Date
Icyoung 19628fa9df Merge pull request #385 from zhouyongyou/fix/market-price-staleness
fix(market): resolve price staleness causing trade failures
2025-11-05 15:45:52 +08:00
Icyoung cdfe8956ce Merge pull request #414 from zhouyongyou/feat/query-actual-balance-v2
feat(api): query actual exchange balance when creating trader
2025-11-05 15:45:09 +08:00
Icyoung 678392fab1 Merge pull request #325 from zhouyongyou/refactor/enhance-partial-close-guidance
refactor(prompts): 增強部分平倉使用指導 [依賴 #415]
2025-11-05 15:43:08 +08:00
Icyoung 2c122f0c5c Merge pull request #273 from zhouyongyou/feat/logger-dynamic-tpsl
feat(logger): 添加動態 TP/SL 日誌支持 [依賴 #415]
2025-11-05 15:42:33 +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
tinkle-community 07be9065d5 Merge pull request #501 from Hansen1018/add-Hansen-prompt
增加 稳健和风险控制均衡基础策略提示词
2025-11-05 15:33:02 +08:00
tinkle-community 6910a25ae6 Merge pull request #500 from CoderMageFox/feature/aster-field-help-tooltips
feat: add help tooltips for Aster exchange configuration fields
2025-11-05 15:04:27 +08:00
tinkle-community 89b0f71ef6 Merge pull request #498 from tangmengqiu/dev_logs
feat(log): add logrus log lib and add telegram notification push as an option
2025-11-05 14:15:47 +08:00
CoderMageFox c7d7884d2b feat: add Aster API wallet links to help tooltips
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
Co-Authored-By: tinkle-community <tinklefund@gmail.com>
2025-11-05 13:26:05 +08:00
CoderMageFox 6bc9a16f4c refactor: merge USDT warning into security warning box
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
Co-Authored-By: tinkle-community <tinklefund@gmail.com>
2025-11-05 13:19:39 +08:00
Hansen1018 deca0e5427 增加 稳健和风险控制均衡基础策略提示词
主要优化点:

强化风险控制框架 明确单笔风险≤2%,总风险≤6%
添加连续亏损后的仓位调整规则

设置单日和每周最大亏损限制

提高开仓标准 要求至少3个技术指标支持
必须有多时间框架趋势确认

入场时机要求更具体

完善决策流程 增加市场环境评估环节
明确风险回报比计算要求

添加资金保护检查点

细化行为准则 明确等待最佳机会的重要性
强调分批止盈和严格止损

添加情绪控制具体方法

增强绩效反馈机制 不同夏普比率区间的具体行动指南
亏损状态下的仓位控制要求

盈利状态下的纪律保持提醒

这个优化版本更加注重风险控制和稳健性,同时保持了交易的专业性和灵活性。
2025-11-05 13:19:07 +08:00
CoderMageFox 9349438e82 feat: add USDT warning for Aster exchange configuration
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"
Co-Authored-By: tinkle-community <tinklefund@gmail.com>
2025-11-05 13:15:49 +08:00
CoderMageFox 13dc0213f3 feat: add help tooltips for Aster exchange configuration fields
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.
Co-Authored-By: tinkle-community <tinklefund@gmail.com>
2025-11-05 13:03:41 +08:00
CoderMageFox 81e3d3cdb4 fix: 修复InitialBalance配置错误导致的P&L统计不准确问题
用户在使用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统计不准确问题
- **改进**: 提升用户体验,减少配置错误
- **兼容**: 完全向后兼容,不影响现有功能
Co-Authored-By: tinkle-community <tinklefund@gmail.com>
2025-11-05 12:49:55 +08:00
tangmengqiu 9658785c6b log: add logrus log lib and add telegram notification push as an option 2025-11-04 23:48:32 -05:00
SkywalkerJi 638238eb12 Merge pull request #489 from 0xEmberZz/feature/eslint&prettier
Feature/eslint&prettier
2025-11-05 13:01:29 +09:00
Ember b79878ab36 feat: add ESLint and Prettier with pre-commit hook
- 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: tinkle-community <tinklefund@gmail.com>
2025-11-05 11:41:14 +08:00
Ember aaf1243f20 test: verify pre-commit hook formatting 2025-11-05 11:40:05 +08:00
Ember a89cd722c9 test: add eslint and prettier configuration with pre-commit hook 2025-11-05 11:40:05 +08:00
Ember d1f7ced7e1 fix: resolve Web UI display issues (#365)
## 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 #365
Co-Authored-By: tinkle-community <tinklefund@gmail.com>
2025-11-05 11:40:05 +08:00
Shui 572bc3292d Merge pull request #444 from 0xEmberZz/fix/login-redirect-loop-422
fix: resolve login redirect loop issue (#422)
2025-11-04 22:08:27 -05:00
Shui 8afbf0b891 Merge pull request #421 from Im-Sue/fix/trader-manager-hyperliquid-testnet-clean
fix(trader): add missing HyperliquidTestnet configuration in loadSing…
2025-11-04 22:04:13 -05:00
Diego bb6a1ac073 Merge pull request #399 from tangmengqiu/fix/hyperliquid_setup
fix(setup): hyperliquid setup, no need to enter the wallet address, improve user experience
2025-11-05 10:23:26 +08:00
tangmengqiu 88dae4d87a fix conflict 2025-11-04 21:22:44 -05:00
SkywalkerJi 7fa8414d16 Merge pull request #480 from SkywalkerJi/dev
fix(AI): Change the default model to qwen3-max to mitigate output quality issues caused by model downgrading.
2025-11-05 11:02:06 +09:00
Shui aecc875d09 Merge pull request #477 from xqliu/fix/ai-max-tokens-env-var
fix: add AI_MAX_TOKENS environment variable to prevent response truncation
2025-11-04 20:54:15 -05:00
Shui e3a9219a4c Merge pull request #478 from ERIC961/docs/config-file-name
docs: config.example.jsonc替换成config.json.example
2025-11-04 20:52:46 -05:00
SkywalkerJi 308f469b9c Change the default model to qwen3-max to mitigate output quality issues caused by model downgrading. 2025-11-05 09:50:05 +08:00
Liu Xiang Qian f8edc0ec11 fix: add AI_MAX_TOKENS environment variable to prevent response truncation
## Problem
AI responses were being truncated due to a hardcoded max_tokens limit of 2000,
causing JSON parsing failures. The error occurred when:
1. AI's thought process analysis was cut off mid-response
2. extractDecisions() incorrectly extracted MACD data arrays from the input prompt
3. Go failed to unmarshal numbers into Decision struct
Error message:
```
json: cannot unmarshal number into Go value of type decision.Decision
JSON内容: [-867.759, -937.406, -1020.435, ...]
```
## Solution
- Add MaxTokens field to mcp.Client struct
- Read AI_MAX_TOKENS from environment variable (default: 2000)
- Set AI_MAX_TOKENS=4000 in docker-compose.yml for production use
- This provides enough tokens for complete analysis with the 800-line trading strategy prompt
## Testing
- Verify environment variable is read correctly
- Confirm AI responses are no longer truncated
- Check decision logs for complete JSON output
2025-11-05 09:31:58 +08:00
liangjiahao 5efc9fc7c5 docs: config.example.jsonc替换成config.json.example 2025-11-05 09:24:38 +08:00
Shui 54f5637e34 Merge pull request #476 from hzb1115/dev
fix(workflow): simplify PR template
2025-11-04 20:18:35 -05:00
Shui 4ff618e424 Merge pull request #3 from hzb1115/feature/pr-template-automation
feat(templates): add intelligent PR template selection system
2025-11-04 16:05:50 -05:00
zbhan 97935a8e07 Fix PR tpl 2025-11-04 16:05:29 -05:00
zbhan caa42ec1a1 feat(templates): add intelligent PR template selection system
- Created specialized PR templates for different change types:
  - Backend template for Go/API changes
  - Frontend template for UI/UX changes
  - Documentation template for docs updates
  - General template for mixed changes
- Simplified default template from 270 to 115 lines
- Added GitHub Action for automatic template suggestion based on file types
- Auto-labels PRs with appropriate categories (backend/frontend/documentation)
- Provides friendly suggestions when default template is used
Co-Authored-By: tinkle-community <tinklefund@gmail.com>
2025-11-04 15:52:01 -05:00
Icyoung 3e91aa8176 Merge pull request #466 from zhouyongyou/fix/websocket-crash
fix(market): prevent program crash on WebSocket failure
2025-11-05 02:14:23 +08:00
ZhouYongyou bb2a4c720e fix(market): prevent program crash on WebSocket failure
## Problem
- Program crashes with log.Fatalf when WebSocket connection fails
- Triggered by WebSocket hijacking issue (157.240.12.50)
- Introduced in commit 3b1db6f (K-line WebSocket migration)
## Solution
- Replace 4x log.Fatalf with log.Printf in monitor.go
- Lines 177, 183, 189, 215
- Program now logs error and continues running
## Changes
1. Initialize failure: Fatalf → Printf (line 177)
2. Connection failure: Fatalf → Printf (line 183)
3. Subscribe failure: Fatalf → Printf (line 189)
4. K-line subscribe: Fatalf → Printf + dynamic period (line 215)
## Fallback
- System automatically uses API when WebSocket cache is empty
- GetCurrentKlines() has built-in degradation mechanism
- No data loss, slightly slower API calls as fallback
## Impact
-  Program stability: Won't crash on network issues
-  Error visibility: Clear error messages in logs
-  Data integrity: API fallback ensures K-line availability
Related: websocket-hijack-fix.md, auto-stop-bug-analysis.md
2025-11-05 02:06:54 +08:00
SkywalkerJi 476e91bc52 Merge pull request #464 from SkywalkerJi/dev
fix: Fix code formatting to avoid PR Checks / Backend Code Quality (Go) checks reporting errors.
2025-11-05 03:03:09 +09:00
SkywalkerJi 77a217e8ec Fixed go fmt code formatting issues. 2025-11-05 01:42:36 +08:00
SkywalkerJi 35ea18e927 log.Printf mandates that its first argument must be a compile-time constant string. 2025-11-05 01:36:44 +08:00
Ember 284d4f9b58 fix: resolve login redirect loop issue (#422)
- Redirect to /traders instead of / after successful login/registration
- Make 'Get Started Now' button redirect logged-in users to /traders
- Prevent infinite loop where logged-in users are shown landing page repeatedly
Fixes issue where after login success, clicking "Get Started Now" would
show login modal again instead of entering the main application.
Co-Authored-By: tinkle-community <tinklefund@gmail.com>
2025-11-04 22:30:31 +08:00
SkywalkerJi 735db88ae5 Merge pull request #425 from zhouyongyou/fix/prompts-action-names-minimal
fix(prompts): rename actions to match backend implementation
提示词对齐
2025-11-04 21:27:50 +09:00
ZhouYongyou f99052e780 fix(prompts): rename actions to match backend implementation
## Problem
Backend code expects these action names:
- `open_long`, `open_short`, `close_long`, `close_short`
But prompts use outdated names:
- `buy_to_enter`, `sell_to_enter`, `close`
This causes all trading decisions to fail with unknown action errors.
## Solution
Minimal changes to fix action name compatibility:
### prompts/nof1.txt
-  `buy_to_enter` → `open_long`
-  `sell_to_enter` → `open_short`
-  `close` → `close_long` / `close_short`
-  Explicitly list `wait` action
- +18 lines, -6 lines (only action definitions section)
### prompts/adaptive.txt
-  `buy_to_enter` → `open_long`
-  `sell_to_enter` → `open_short`
-  `close` → `close_long` / `close_short`
- +15 lines, -6 lines (only action definitions section)
## Impact
-  Trading decisions now execute successfully
-  Maintains all existing functionality
-  No new features added (minimal diff)
## Verification
```bash
# Backend expects these actions:
grep 'Action string' decision/engine.go
# "open_long", "open_short", "close_long", "close_short", ...
# Old names removed:
grep -r "buy_to_enter\|sell_to_enter" prompts/
# (no results)
```
Co-Authored-By: tinkle-community <tinklefund@gmail.com>
2025-11-04 19:41:23 +08:00
sue 616c350835 fix(trader): add missing HyperliquidTestnet configuration in loadSingleTrader
修复了 loadSingleTrader 函数中缺失的 HyperliquidTestnet 配置项,
确保 Hyperliquid 交易所的测试网配置能够正确传递到 trader 实例。
Changes:
- 在 loadSingleTrader 中添加 HyperliquidTestnet 字段配置
- 代码格式优化(空格对齐)
Co-Authored-By: tinkle-community <tinklefund@gmail.com>
2025-11-04 19:02:39 +08:00
ZhouYongyou 3f5bb5ca84 fix(market): resolve price staleness issue in GetCurrentKlines
## Problem
GetCurrentKlines had two critical bugs causing price data to become stale:
1. Incorrect return logic: returned error even when data fetch succeeded
2. Race condition: returned slice reference instead of deep copy, causing concurrent data corruption
## Impact
- BTC price stuck at 106xxx while actual market price was 107xxx+
- LLM calculated take-profit based on stale prices → orders failed validation
- Statistics showed incorrect P&L (0.00%) due to corrupted historical data
- Alt-coins filtered out due to failed market data fetch
## Solution
1. Fixed return logic: only return error when actual failure occurs
2. Return deep copy instead of reference to prevent race conditions
3. Downgrade subscription errors to warnings (non-blocking)
## Test Results
 Price updates in real-time
 Take-profit orders execute successfully
 P&L calculations accurate
 Alt-coins now tradeable
Related: Price feed mechanism, concurrent data access
2025-11-04 17:21:47 +08:00
ZhouYongyou 5d2d849226 refactor(prompts): add comprehensive partial_close guidance to adaptive.txt
Add detailed guidance chapter for dynamic TP/SL management and partial close operations.
## Changes
- New chapter: "动态止盈止损与部分平仓指引" (Dynamic TP/SL & Partial Close Guidance)
- Inserted between "可用动作" (Actions) and "决策流程" (Decision Flow) sections
- 4 key guidance points covering:
  1. Partial close best practices (use clear percentages like 25%/50%/75%)
  2. Reassessing remaining position after partial exit
  3. Proper use cases for update_stop_loss / update_take_profit
  4. Multi-stage exit strategy requirements
## Benefits
-  Provides concrete operational guidelines for AI decision-making
-  Clarifies when and how to use partial_close effectively
-  Emphasizes remaining position management (prevents "orphan" positions)
-  Aligns with existing backend support for partial_close action
## Background
While adaptive.txt already lists partial_close as an available action,
it lacked detailed operational guidance. This enhancement fills that gap
by providing specific percentages, use cases, and multi-stage exit examples.
Backend (decision/engine.go) already validates partial_close with
close_percentage field, so this is purely a prompt enhancement with
no code changes required.
Co-Authored-By: tinkle-community <tinklefund@gmail.com>
2025-11-04 17:20:57 +08:00
ZhouYongyou c0c0688805 更新 logger:支持新增的三個動作類型
更新內容:
1. DecisionAction 註釋:添加 update_stop_loss, update_take_profit, partial_close
2. GetStatistics:partial_close 計入 TotalClosePositions
3. AnalyzePerformance 預填充邏輯:處理 partial_close(不刪除持倉記錄)
4. AnalyzePerformance 分析邏輯:
   - partial_close 正確判斷持倉方向
   - 記錄部分平倉的盈虧統計
   - 保留持倉記錄(因為還有剩餘倉位)
說明:partial_close 會記錄盈虧,但不刪除 openPositions,
      因為還有剩餘倉位可能繼續交易
2025-11-04 17:19:58 +08:00
ZhouYongyou c26463c4c4 fix: remove unnecessary prompts/adaptive.txt changes
- This PR should only contain backend core functionality
- prompts/adaptive.txt v2.0 is already in upstream
- Prompt enhancements will be in separate PR (Batch 3)
2025-11-04 16:58:28 +08:00
ZhouYongyou c4e72b124f fix: 修復 Hyperliquid CancelStopOrders 編譯錯誤
- OpenOrder 結構不暴露 trigger 字段
- 改為取消該幣種的所有掛單(安全做法)
2025-11-04 16:45:20 +08:00
ZhouYongyou b9a4bfceca fix: 修复部分平仓盈利计算错误
问题:部分平仓时,历史记录显示的是全仓位盈利,而非实际平仓部分的盈利
根本原因:
- AnalyzePerformance 使用开仓总数量计算部分平仓的盈利
- 应该使用 action.Quantity(实际平仓数量)而非 openPos["quantity"](总数量)
修复:
- 添加 actualQuantity 变量区分完整平仓和部分平仓
- partial_close 使用 action.Quantity
- 所有相关计算(PnL、PositionValue、MarginUsed)都使用 actualQuantity
影响范围:logger/decision_logger.go:428-465
Co-Authored-By: tinkle-community <tinklefund@gmail.com>
2025-11-04 16:40:28 +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