Commit Graph

34 Commits

Author SHA1 Message Date
ZhouYongyou
0eb05ddba2 fix: 过滤幽灵持仓 - 跳过 quantity=0 的持仓防止 AI 误判
问题:
- 止损/止盈触发后,交易所返回 positionAmt=0 的持仓记录
- 这些幽灵持仓被传递给 AI,导致 AI 误以为仍持有该币种
- AI 可能基于错误信息做出决策(如尝试调整已不存在的止损)

修复:
- buildTradingContext() 中添加 quantity==0 检查
- 跳过已平仓的持仓,确保只传递真实持仓给 AI
- 触发清理逻辑:撤销孤儿订单、清理内部状态

影响范围:
- trader/auto_trader.go:487-490

测试:
- 编译成功
- 容器重建并启动正常
2025-11-02 22:08:39 +08:00
ZhouYongyou
e76792c7db fix: 修復 Hyperliquid CancelStopOrders 編譯錯誤
問題:order.TriggerPx 字段不存在
原因:Hyperliquid SDK 的 OpenOrder 結構不暴露 trigger 相關字段

解決方案:
- 簡化 CancelStopOrders 實現
- 取消該幣種所有掛單(包括止盈止損單)
- 這是安全的,因為在設置新止盈止損前應清理舊訂單

影響:
-  編譯通過
-  功能正常(取消訂單邏輯更簡單但有效)
-  與 Binance/Aster 實現一致(都是取消相關訂單)
2025-11-02 07:40:33 +08:00
ZhouYongyou
ed34201c2d 修復關鍵缺陷:添加 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-02 06:23:02 +08:00
ZhouYongyou
82660b12c5 feat: 添加部分平仓和动态止盈止损功能
新增功能:
- update_stop_loss: 调整止损价格(追踪止损)
- update_take_profit: 调整止盈价格(技术位优化)
- partial_close: 部分平仓(分批止盈)

实现细节:
- Decision struct 新增字段:NewStopLoss, NewTakeProfit, ClosePercentage
- 新增执行函数:executeUpdateStopLossWithRecord, executeUpdateTakeProfitWithRecord, executePartialCloseWithRecord
- 修复持仓字段获取 bug(使用 "side" 并转大写)
- 更新 adaptive.txt 文档,包含详细使用示例和策略建议
- 优先级排序:平仓 > 调整止盈止损 > 开仓

命名统一:
- 与社区 PR #197 保持一致,使用 update_* 而非 adjust_*
- 独有功能:partial_close(部分平仓)

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-02 05:32:23 +08:00
ZhouYongyou
a58be23a29 fix: 修正盈亏百分比计算错误(未考虑杠杆)
问题:
- 旧算法只计算价格变化百分比,未考虑杠杆倍数
- 例:10倍杠杆,价格涨1% → 显示+1%(错误),实际应该是+10%
- 导致 AI 收到错误的盈亏数据,影响决策

修复:
- 使用实际盈亏除以保证金计算百分比
- 公式:pnlPct = (unrealizedPnl / marginUsed) * 100
- 优点:
  ✓ 考虑杠杆倍数
  ✓ 使用 API 提供的实际盈亏(含手续费、资金费率)
  ✓ 更准确反映真实盈亏百分比

示例对比:
- 入场:100,000,当前:101,000(+1%),10倍杠杆
- 旧算法:显示 +1%(错误)
- 新算法:显示 +10%(正确)

感谢用户反馈 @1711z

🤖 Generated with Claude Code
2025-11-02 00:23:59 +08:00
Z
4fbb4ecea5 Merge branch 'dev' into dev 2025-11-01 20:17:20 +08:00
SkywalkerJi
4250c11ddf Supports custom system prompts and custom models. 2025-11-01 19:45:54 +08:00
SkywalkerJi
48d1320209 * Fixed the custom model URL.
*   Added functionality for custom model names.
2025-11-01 16:09:15 +08:00
Z
1cc43cec60 Merge branch 'tinkle-community:dev' into dev 2025-11-01 02:57:18 +08:00
icy
a7cc5e5ed4 竞赛fix、交易员新增参数 2025-11-01 02:17:11 +08:00
ZhouYongyou
17ad15ca4e refactor: unify to simplified Chinese in logs 2025-11-01 00:25:58 +08:00
ZhouYongyou
396df86367 Cancel orphan orders when position is closed
Added logic to automatically cancel all orders for a symbol when its position disappears, ensuring orphan stop-loss/take-profit orders are cleaned up. This improves order management and prevents unintended trades after a position is closed.
2025-11-01 00:01:38 +08:00
icy
d0621265aa Add MarginMode configration 2025-10-31 13:14:24 +08:00
icy
3f686dec2e Merge branch 'main' of github.com:Icyoung/nofx
# Conflicts:
#	config.json.example
#	config/config.go
#	main.go
#	trader/auto_trader.go
#	web/src/App.tsx
#	web/src/components/CompetitionPage.tsx
2025-10-31 03:59:58 +08:00
icy
ac7c40632d account system、custom prompt 2025-10-31 03:42:01 +08:00
henrylab
4db1a3adb1 1. 修复hyperliquid 总盈亏,总净值计算错误问题
2. 修复持仓盈亏百分比错误,计算公式应该加入杠杆倍数
2025-10-30 22:23:05 +08:00
tinkle
007fa2567d 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

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-30 21:07:43 +08:00
tinkle
b83e027eb0 Refactor: Extract availableBalance variable in Hyperliquid trader
Extract availableBalance calculation into a separate variable for better readability.

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-30 20:09:30 +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
刘 志
d9f99a6fcd fix: hyperliquid余额不准确 2025-10-30 08:38:31 +00:00
tpkeeper
1083c06d1f Fix mcp defaultConfig override issue in multi-trader, multi-AI model scenario 2025-10-30 15:46:17 +08:00
SkywalkerJi
1171a4643c Reduce the request frequency to the Binance API and add backend caching. 2025-10-30 14:01:06 +08:00
mxyhi
a9f61328a0 🐛 fix(order): 开仓前先撤销所有挂单
- 先在开仓前取消所有挂单,防止残留挂单导致仓位叠加
- 取消挂单失败时记录警告,但仍继续开仓
2025-10-30 13:08:26 +08:00
mxyhi
571ceff0f0 feat(trader): aster平仓后自动取消挂单
- 调整 CloseLong/CloseShort 逻辑, 在平仓后调用 CancelAllOrders 清理挂单
2025-10-30 13:06:14 +08:00
nobody
5770059ab6 Update readmes. 2025-10-30 00:41:14 +08:00
nobody
8a6013016a feat: Add Aster DEX exchange support + fix precision issues
## Features
- Add full Aster DEX integration with Binance-compatible API
- Support Web3 authentication with API wallet system
- Add comprehensive Aster integration guide (ASTER_INTEGRATION.md)
- Add example Aster configuration (config.aster.example.json)

## Bug Fixes
- Fix precision error (code -1111) for all order types
- Implement proper float-to-string conversion with exchange precision
- Add automatic precision fetching from /exchangeInfo endpoint
- Remove trailing zeros from formatted values

## Documentation
- Update README.md with Aster quick start guide
- Add detailed setup instructions for creating API wallet
- Include troubleshooting FAQ and security best practices
- Update core features to mention three supported exchanges

## Technical Details
- Added formatFloatWithPrecision() helper function
- Updated all order functions to use proper precision formatting
- Added precision logging for debugging
- Fully backward compatible with existing configurations

Closes #[issue number if applicable]
2025-10-30 00:27:33 +08:00
btcman
2cdfb87144 Feature: Add support for custom OpenAI-compatible API
This update enables users to configure any OpenAI-compatible API endpoint,
allowing the use of:
- OpenAI official API (GPT-4, GPT-4o, etc.)
- OpenRouter (access to multiple models)
- Local deployed models (Ollama, LM Studio, etc.)
- Other OpenAI-format compatible API services

Changes:
- config: Add custom_api_url, custom_api_key, custom_model_name fields
- mcp: Add SetCustomAPI function and ProviderCustom constant
- trader: Update AI initialization logic to support custom API
- manager: Pass custom API config to trader instances
- Add CUSTOM_API.md documentation with usage examples
- Update config.json.example with custom API sample

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-29 22:48:28 +08:00
PorunC
6fb65b43c6 Merge upstream/main: Integrate Hyperliquid support with leverage config
Resolved conflicts in manager/trader_manager.go by combining:
- Upstream: Exchange field, Hyperliquid API keys, Hyperliquid testnet
- Local: BTCETHLeverage and AltcoinLeverage fields

Both features are now working together.
2025-10-29 21:01:05 +08:00
PorunC
36840d52dd Feat: Integrate leverage configuration across trading system
- Pass leverage config through TraderManager to AutoTrader
- Add BTCETHLeverage and AltcoinLeverage fields to Context and AutoTraderConfig
- Update decision validation to use configured leverage limits
- Display configured leverage in startup message
- Update error messages to show current leverage limits

Changes:
- main.go: Pass leverage config to AddTrader, update startup message
- manager/trader_manager.go: Accept and forward leverage config
- trader/auto_trader.go: Store leverage config, pass to Context
- decision/engine.go: Use dynamic leverage limits in validation

This completes the leverage configuration feature implementation.

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-29 20:30:04 +08:00
nobody
e1d5a6405c 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
tinkle
68c0c62d04 Feature: Add position holding duration to AI decision context
Track and display how long each position has been held to help AI make better timing decisions.

**Implementation**:
- Added UpdateTime field to PositionInfo struct (decision/engine.go:26)
- Added positionFirstSeenTime map to AutoTrader for tracking (trader/auto_trader.go:60)
- Record opening time when position is created successfully:
  - executeOpenLongWithRecord: Records timestamp for long positions (trader/auto_trader.go:540-541)
  - executeOpenShortWithRecord: Records timestamp for short positions (trader/auto_trader.go:593-594)
- Fallback tracking in buildTradingContext for program restart scenarios (trader/auto_trader.go:386-392)
- Auto-cleanup closed positions from tracking map (trader/auto_trader.go:409-414)
- Display duration in user prompt with smart formatting:
  - Under 60 min: "持仓时长25分钟"
  - Over 60 min: "持仓时长2小时15分钟"

**Example Output**:
```
1. TAOUSDT LONG | 入场价435.5300 当前价433.1900 | 盈亏-0.54% | 杠杆20x | 保证金25 | 强平价418.1528 | 持仓时长2小时15分钟
```

**Benefits**:
- AI can see how long positions have been held
- Helps enforce minimum holding period (30-60 min) from system prompt
- Simple implementation with minimal overhead
- Auto-cleanup prevents memory leaks

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-29 14:20:40 +08:00
tinkle
f3a87b5a7a Refactor: Modularize codebase with separate decision and MCP packages
Architecture improvements:
- Extract AI decision engine to dedicated `decision` package
- Create `mcp` package for Model Context Protocol client
- Separate market data structures into `market/data.go`
- Update trader to use new modular structure

New packages:
- `decision/engine.go` - AI decision logic and prompt building
- `mcp/client.go` - Unified AI API client (DeepSeek/Qwen)
- `market/data.go` - Market data type definitions

Benefits:
- Better separation of concerns
- Improved code organization and maintainability
- Easier to test individual components
- More flexible AI provider integration
- Cleaner dependency management

Updated imports:
- trader/auto_trader.go now uses decision and mcp packages
- Consistent API across different AI providers

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-29 06:14:57 +08:00
tinkle
102d9f438d Refactor: Improve AI decision system and Sharpe ratio calculation
Major improvements:
- Use period-level Sharpe ratio (range -2 to +2) instead of annualized
- Save full user prompt in decision logs for debugging
- Format complete market data (3m + 4h candles) for AI analysis
- Prevent position stacking with duplicate position checks
- Update Sharpe ratio interpretation thresholds

Market data enhancements:
- Display full technical indicators in user prompt
- Include 3-minute and 4-hour timeframe data
- Add OI (Open Interest) change and funding rate signals

Risk control:
- Block opening duplicate positions (same symbol + direction)
- Suggest close action first before opening new position
- Prevent margin usage from exceeding limits

UI improvements:
- Update multi-language translations
- Refine AI learning dashboard display

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-29 04:44:17 +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