Commit Graph

74 Commits

Author SHA1 Message Date
tinkle-community
2bf3e18ca8 Merge pull request #25 from Im-Sue/main
add 常见问题.md 提示如何处理币安API 4061问题
2025-10-30 02:57:40 +08:00
sue
66b8eb416b fix: 修复配置硬编码问题
## 修复内容

### 1. AI决策杠杆配置动态化 (decision/engine.go)
- **问题**: System Prompt 中硬编码 50x/20x 杠杆,导致 AI 生成的决策不符合用户配置(5x)
- **修复**:
  - buildSystemPrompt() 新增 btcEthLeverage, altcoinLeverage 参数
  - System Prompt 文本使用动态杠杆值(第225-226行)
  - 示例 JSON 使用配置杠杆值(第299行)
  - 调用时传入实际配置值(第100行)
- **影响**: AI 现在会根据用户配置的杠杆限制生成决策

### 2. 前端初始余额显示优化 (web/src/components/EquityChart.tsx)
- **问题**: 初始余额硬编码为 1000 USDT,与用户配置的 100 USDT 不符
- **修复**: 实现三级回退机制
  1. 优先使用历史数据第一个点的 total_equity
  2. 备用使用当前账户 account.total_equity
  3. 最后使用默认值 100(匹配常见配置)
- **影响**: 前端显示的初始余额现在与实际配置一致

## 技术细节

**函数签名变更**:
```go
// 修改前
func buildSystemPrompt(accountEquity float64) string

// 修改后
func buildSystemPrompt(accountEquity float64, btcEthLeverage, altcoinLeverage int) string
```

**React 状态优化**:
```typescript
// 修改前
const initialBalance = history[0]?.total_equity || 1000;

// 修改后
const initialBalance = history[0]?.total_equity || account?.total_equity || 100;
```

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-30 02:43:14 +08:00
sue
273769e046 add 常见问题.md 提示如何处理币安API 4061问题 2025-10-30 02:35:52 +08:00
tinkle-community
b7a70d8ccd Merge pull request #24 from Im-Sue/main
fix: 修复AI学习数据加载失败问题-前端硬编码api
2025-10-30 02:15:10 +08:00
sue
ddda972d86 Merge branch 'main' of https://github.com/tinkle-community/nofx 2025-10-30 02:07:41 +08:00
tinkle
b8f9d9cd72 Docs: Add screenshots section to all README files
Add professional UI screenshots to demonstrate the trading platform:
- Competition mode: Multi-AI leaderboard with real-time performance charts
- Trader details: Complete dashboard with equity curves and decision logs

Screenshots added to all language versions:
- README.md (English)
- README.zh-CN.md (Chinese)
- README.ru.md (Russian)
- README.uk.md (Ukrainian)

Images organized in screenshots/ directory with descriptive filenames:
- competition-page.png (AI battle interface)
- details-page.png (trader dashboard)

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-30 01:42:38 +08:00
sue
755b5a5942 fix: 修复AI学习数据加载失败问题
问题描述:
- AILearning组件直接使用硬编码的localhost:8080地址
- 绕过了Vite代理配置,导致加载失败
- 在生产环境无法正常工作

修复内容:
1. api.ts: 添加统一的getPerformance()方法
2. AILearning.tsx: 移除硬编码URL,使用统一API
3. 删除多余的fetcher函数

技术改进:
- 使用Vite代理配置,避免CORS问题
- 统一API管理,提高可维护性
- 支持开发和生产环境

影响范围:
- web/src/lib/api.ts: +11行 (新增getPerformance方法)
- web/src/components/AILearning.tsx: -4行, +2行 (重构API调用)

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-30 01:36:51 +08:00
tinkle-community
d76d4f6598 Merge pull request #22 from hrzisme/feat/aster-dex-support
Feat/aster dex support
2025-10-30 01:01:54 +08:00
nobody
0eb2694887 Delete COMMIT_MESSAGE.txt 2025-10-30 00:45:39 +08:00
nobody
5770059ab6 Update readmes. 2025-10-30 00:41:14 +08:00
nobody
c9346e960a Delete HOW_TO_SUBMIT_PR.md 2025-10-30 00:32:13 +08:00
nobody
e17cdac49c change the config 2025-10-30 00:29:39 +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
tinkle-community
939acb9566 Merge pull request #20 from fanyinghao/fix-docker-compose
Enhance Docker setup
2025-10-30 00:07:38 +08:00
tinkle
27e522cc8d Fix: Add input_prompt display in decision cards
Previously, the frontend DecisionRecord type was missing the input_prompt
field that exists in the backend DecisionLog, causing the input context
sent to AI to not be displayed in the UI.

Changes:
- Add input_prompt field to DecisionRecord interface in both type files
- Add collapsible Input Prompt section in DecisionCard component
- Display input_prompt before AI Chain of Thought with blue styling
- Use same expand/collapse interaction pattern as CoT trace

Now users can view both the input context and AI's reasoning process
in the decision cards.

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-29 23:59:11 +08:00
Yinghao Fan
7caab663e7 Merge remote-tracking branch 'upstream/main' into fix-docker-compose 2025-10-29 23:47:18 +08:00
Yinghao Fan
602e447882 Enhance Docker setup: Add shared volume for frontend files and update Dockerfile for dependencies
Changes:
- Updated `docker-compose.yml` to include a new shared volume `frontend-dist` for frontend files.
- Modified the `nofx` service command to copy frontend files to the shared volume.
- Updated `Dockerfile` to use Go 1.25 and added necessary build dependencies for TA-Lib installation.

These changes improve the Docker environment by facilitating shared access to frontend assets and ensuring the build process is up-to-date with the latest Go version.
2025-10-29 23:34:21 +08:00
tinkle-community
87cd245876 Merge pull request #18 from manwallet/feature/custom-api-support
Feature: Add support for custom OpenAI-compatible API
2025-10-29 23:03:52 +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
tinkle
d2edc5e0a4 Refactor: Improve AI prompt with more technical analysis methods
Changes to decision/engine.go:
- Clean up Context struct field alignment for better readability
- Enhance system prompt to include more technical analysis methods:
  * Added: technical resistance levels, Fibonacci, volatility bands
  * Changed wording from "you can do X" to "you can do but not limited to X"
  to encourage AI to use broader range of analysis techniques

This gives the AI decision engine more explicit guidance on available
technical analysis tools while maintaining flexibility.

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-29 22:05:58 +08:00
tinkle
51b04a8418 Fix: Support dynamic number of traders in ComparisonChart
Previously, ComparisonChart was hardcoded to only fetch equity history
data for the first 2 traders, causing the 3rd and subsequent traders'
data to not be displayed on the chart.

Changes:
- Replaced multiple individual useSWR calls with single consolidated call
- Use Promise.all() to fetch all traders' equity data concurrently
- Generate dynamic cache key based on all trader IDs
- Maintain backward compatibility with existing component structure
- Update useMemo dependencies to properly track data changes

This fix allows the comparison chart to properly display any number of
competing traders, not just 2.

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-29 21:42:34 +08:00
tinkle-community
0c6f1bc408 Merge pull request #17 from PorunC/main
引入了可配置的杠杆倍数设置、Docker 部署优化以及前端关键 Bug 修复
2025-10-29 21:18:14 +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
48ab69befc Fix: Resolve React Hook violation in ComparisonChart component
Root cause:
ComparisonChart was calling useSWR hooks dynamically inside a .map() loop,
which violates React's Rules of Hooks. When the traders array length changed
(e.g., from 0 to 2, or during initial load), the number of hook calls would
change between renders, triggering React Error #310.

Previous code:
```tsx
const traderHistories = traders.map((trader) => {
  return useSWR(`equity-history-${trader.trader_id}`, ...);  //  Dynamic hooks
});
```

The eslint-disable comment on line 24 was masking this critical issue.

Fix:
- Always call exactly 2 useSWR hooks (trader1, trader2) unconditionally
- Pass null as the key when trader doesn't exist (SWR handles this gracefully)
- Build traderHistories array from these fixed hooks
- Ensures same number of hooks called on every render

This follows React's Rules of Hooks:
 Only call hooks at the top level
 Don't call hooks inside loops, conditions, or nested functions
 Call hooks in the same order every render

Fixes: React Error #310 (Rendered more hooks than during previous render)

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-29 20:49:22 +08:00
PorunC
8aa305290a Fix: Add comprehensive null safety checks to CompetitionPage component
Root cause analysis:
The previous fix (0cb1f37) only addressed App.tsx Debug Info section,
but missed CompetitionPage.tsx which also directly accesses trader data
fields without null safety checks.

When competition data is loading or incomplete, trader objects may exist
but contain undefined fields (total_pnl, total_equity, etc.), causing:
"TypeError: Cannot read properties of undefined (reading 'total_pnl')"

Fixed locations in CompetitionPage.tsx:
1. Line 76-77: Leader display in header (total_pnl, total_pnl_pct)
2. Line 142: Leaderboard total_equity display
3. Line 151-157: Leaderboard P&L section (total_pnl checks and displays)
4. Line 229-230: Head-to-Head comparison (total_pnl display)

Changes applied:
- Replace direct property access with optional chaining (?.)
- Use nullish coalescing (?? 0) for numeric comparisons
- Add fallback values ('0.00') for undefined fields
- Ensure consistent null safety across all trader data displays

This completes the null safety coverage for the entire frontend.

Fixes: TypeError in CompetitionPage at index-R21Yay1P.js:116:51447

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-29 20:46:08 +08:00
tinkle-community
cd0166896d Merge pull request #16 from hrzisme/feature/hyperliquid-support
feat: Add Hyperliquid exchange support with unified trader interface
2025-10-29 20:43:16 +08:00
PorunC
0cb1f37b55 Fix: Add null safety checks to Debug Info section in frontend
Previously fixed StatCard components but missed the Debug Info section,
causing "Cannot read properties of undefined (reading 'total_pnl')" error
when account data is loading or incomplete.

Root cause:
- Frontend uses SWR with async data fetching (5s refresh interval)
- During initial load or API delays, account object may exist but fields undefined
- Previous fix (93e331a) only covered StatCard section (lines 369-384)
- Debug Info section (lines 360-362) still used direct property access

Changes:
- Add optional chaining (?.) to all account field accesses in Debug Info
- Add fallback values ('0.00') for undefined fields
- Ensures consistent null safety across all account data displays

This prevents runtime errors during data loading and API failures.

Fixes: TypeError: Cannot read properties of undefined (reading 'total_pnl')

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-29 20:39:28 +08:00
PorunC
75b106d439 Docs: Sync leverage configuration guide to all language versions
- Update Chinese (README.zh-CN.md) with leverage configuration documentation
- Update Russian (README.ru.md) with leverage configuration documentation
- Update Ukrainian (README.uk.md) with leverage configuration documentation

All language versions now include:
- Updated risk management section (fixed → configurable leverage)
- Leverage configuration in JSON examples
- New leverage fields in configuration tables
- Comprehensive leverage configuration section with:
  - Configuration format and examples
  - Binance subaccount restriction warnings (≤5x)
  - Recommended settings for different account types
  - Safe and aggressive configuration examples
  - Explanation of AI leverage usage

This ensures all users can read the leverage documentation in their preferred language.

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-29 20:34:43 +08:00
PorunC
184d18f154 Docs: Add comprehensive leverage configuration guide (v2.0.3)
- Document new configurable leverage feature in Risk Management section
- Add detailed leverage configuration section with examples
- Explain Binance subaccount restrictions (≤5x leverage)
- Provide recommended settings for different account types and risk levels
- Add leverage fields to configuration table
- Include warnings and best practices

Key documentation updates:
- Clear distinction between subaccount (≤5x) and main account limits
- Example configurations for safe, medium, high, and maximum risk levels
- Explanation of how AI uses leverage within configured limits
- Updated default values from fixed 20x/50x to configurable 5x

This documentation helps users safely configure leverage based on their account type.

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-29 20:30:30 +08:00
PorunC
93e331aa1b Fix: Improve frontend code quality and null safety
- Remove unused variables and imports
- Add null/undefined safety checks for account data display
- Use optional chaining and nullish coalescing for safer data access
- Remove unused "Input Prompt" display section (keeping CoT trace)
- Fix TypeScript warnings and improve type safety

Changes:
- App.tsx: Add null checks for account fields, remove unused stats prop and input prompt display
- ComparisonChart.tsx: Remove unused imports and variables

This improves code quality without affecting functionality.

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-29 20:30:17 +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
PorunC
b5a5760bc4 Feat: Add configurable leverage settings for BTC/ETH and altcoins (v2.0.3)
- Add LeverageConfig struct with btc_eth_leverage and altcoin_leverage fields
- Set default leverage to 5x (safe for Binance subaccounts)
- Add validation warnings for leverage >5x (subaccount restrictions)
- Update config.json.example with leverage configuration

Breaking changes:
- None (backward compatible with default 5x leverage)

Migration:
- Existing configs will auto-default to 5x leverage (safe)
- Main accounts can increase to 20x (altcoins) or 50x (BTC/ETH) in config.json
- Subaccounts must keep leverage ≤5x to avoid trade failures

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-29 20:29:51 +08:00
PorunC
4dcf00fd98 Feat: Upgrade Docker deployment with multi-stage build and Nginx integration
- Upgrade Dockerfile to Go 1.24 with multi-stage build (backend + frontend)
- Add TA-Lib installation for technical analysis support
- Integrate frontend build into main container image
- Add Nginx reverse proxy configuration for API routing
- Update docker-compose.yml to simplified single-container architecture
- Update .dockerignore to include web source for build
- Improve health checks and startup time handling

Benefits:
- One-click deployment with single Docker image
- Better resource utilization with multi-stage build
- Production-ready Nginx frontend serving
- Easier maintenance and deployment

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-29 20:29:34 +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
81475eb88e Docs: Add bounty templates for Hyperliquid and Aster exchange integration
Add comprehensive bounty documentation to recruit contributors for
exchange integrations:

**New Files:**
- `.github/ISSUE_TEMPLATE/feature_request.md` - GitHub Issue template
- `INTEGRATION_BOUNTY_HYPERLIQUID.md` - Complete Hyperliquid integration spec
- `INTEGRATION_BOUNTY_ASTER.md` - Complete Aster integration spec
- `HOW_TO_POST_BOUNTY.md` - Step-by-step guide for posting bounties

**Bounty Documentation Includes:**
- Clear task requirements and acceptance criteria
- Technical specifications and interface definitions
- File structure and implementation guidelines
- Testing and documentation requirements
- Contribution workflow
- Support resources and community links

**HOW_TO_POST_BOUNTY.md Guide:**
- Two methods to post GitHub Issues (Web UI + GitHub CLI)
- Bounty platform recommendations (Gitcoin, Bountysource, IssueHunt)
- Social media promotion templates (Twitter, Telegram, Reddit)
- Issue management best practices
- Legal and quality control considerations

**Benefits:**
- Standardized contribution process
- Clear technical requirements
- Professional bounty presentation
- Easy for maintainers to post and manage
- Attractive for potential contributors

Ready to recruit developers for multi-exchange support! 🚀

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-29 19:47:20 +08:00
tinkle
20ad60c12c Docs: Add Docker one-click deployment support for all languages
Complete Docker deployment solution with beginner-friendly documentation:

**New Docker Files:**
- `Dockerfile` - Multi-stage Go backend build with health checks
- `web/Dockerfile` - Frontend build with Nginx and API proxy
- `docker-compose.yml` - Full orchestration with service dependencies
- `.dockerignore` & `web/.dockerignore` - Build optimization
- `start.sh` - Convenient management script (start/stop/logs/status)

**Comprehensive Documentation:**
- `DOCKER_DEPLOY.md` (中文) - Complete Chinese deployment guide
- `DOCKER_DEPLOY.en.md` (English) - Complete English deployment guide
  - Prerequisites & Docker installation (macOS/Windows/Linux)
  - 3-step quick start (config → start → access)
  - Service management commands
  - Advanced configuration (ports, resources, env vars)
  - Data persistence & backups
  - Comprehensive troubleshooting
  - Security recommendations
  - Production deployment (Nginx, HTTPS, Docker Swarm)
  - Monitoring & logging setup

**README Updates (All 4 Languages):**
- README.md (English)
- README.zh-CN.md (中文)
- README.uk.md (Українська)
- README.ru.md (Русский)

Added prominent "Option A: Docker One-Click Deployment" section at the
beginning of Quick Start in all languages. Clearly marked as EASIEST
method for beginners. Shows 3 simple steps with command examples and
links to detailed DOCKER_DEPLOY docs.

**Key Features:**
- One-command deployment: `./start.sh start --build`
- Auto-handles all dependencies (Go, Node.js, TA-Lib)
- Health checks for both services
- Data persistence (logs, cache, config)
- Log rotation (10MB × 3 files)
- Easy service management
- Beginner-friendly for complete newcomers

**User Benefits:**
- No need to install Go, Node.js, or TA-Lib manually
- Works on macOS, Windows, Linux
- Perfect for non-developers
- Production-ready with best practices

This makes NOFX truly accessible to beginners as requested: "真就让小白都能一键开始"

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-29 18:29:49 +08:00
tinkle
1d356be402 Fix: Correct Sharpe Ratio calculation by using proper equity values
Critical bug fix in Sharpe Ratio calculation logic:

Problem:
- Previously calculated equity as TotalBalance + TotalUnrealizedProfit
- This was incorrect because TotalBalance already stores TotalEquity
- TotalUnrealizedProfit actually stores TotalPnL (not unrealized profit)
- This caused: equity = 2 * TotalEquity - InitialBalance (wrong!)

Root cause:
- Field naming mismatch between AccountSnapshot and actual stored values
- TotalBalance field actually contains TotalEquity (wallet + unrealized)
- TotalUnrealizedProfit field actually contains TotalPnL (equity - initial)

Solution:
- Use TotalBalance directly as it already represents complete account equity
- Added clear comments explaining the field name vs content mismatch
- Sharpe Ratio now correctly calculates risk-adjusted returns

Impact:
- Sharpe Ratio values are now mathematically accurate
- AI performance assessment is now reliable
- No changes needed to data storage or API layer

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-29 18:08:36 +08:00
tinkle
a0ce1e20a9 Fix: Correct Profit Factor calculation and display units in AI Learning
Backend changes (logger/decision_logger.go):
- Fixed Profit Factor to use standard formula (total profit / total loss)
- Previously used average values which was incorrect when win/loss counts differ
- Now saves total amounts before calculating averages for accurate ratio

Frontend changes (web/src/components/AILearning.tsx):
- Fixed display units: changed USDT amounts from "%" to "USDT"
- Updated avg_win and avg_loss to show "USDT Average" instead of "%"
- Updated best/worst performer displays to show "USDT" instead of "%"
- Added "(USDT)" labels to table headers for clarity
- Removed "%" from all table data cells showing monetary amounts

This ensures accurate performance metrics and eliminates user confusion
between percentage values and absolute USDT amounts.

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-29 17:59:19 +08:00
tinkle
6d822173fb Docs: Enhance README files with beginner-friendly guides (4 languages)
**Configuration Improvements:**
- Add comprehensive "Get AI API Keys" section (DeepSeek + Qwen)
- Split configuration into Beginner Mode and Expert Mode
- Add step-by-step setup guides with placeholder tables
- Add configuration checklist and field explanations
- Document smart default behavior for use_default_coins (v2.0.2)

**Startup/Monitoring Guides:**
- Add detailed 2-step system startup instructions
- Include expected output and error troubleshooting tables
- Add monitoring and graceful shutdown procedures
- Provide health check commands

**AI Decision Flow Updates:**
- Enhance flow diagram with emojis and wider boxes
- Add v2.0.2 improvement markers throughout
- Document position duration tracking
- Document accurate USDT PnL calculation with leverage
- Document enhanced AI freedom for raw data analysis
- Document improved position tracking (symbol_side keys)
- Add "Key Improvements in v2.0.2" summary section

**Code Changes:**
- Simplify config.json.example to beginner-friendly single trader
- Implement smart default: use_default_coins auto-enables when omitted
- Set default to true if false without coin_pool_api_url

**Files Updated:**
- README.md (English): +559 lines
- README.zh-CN.md (Chinese): +527 lines
- README.ru.md (Russian): +634 lines
- README.uk.md (Ukrainian): +521 lines
- config.json.example: Simplified configuration
- config/config.go: Smart default logic

Total: 2068+ additions across all documentation

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-29 17:16:27 +08:00
tinkle
a3f896d3b3 Fix: Correct PnL calculation in trade history analysis
Fixed critical issues in historical trade record and performance analysis:

1. PnL Calculation: Changed from percentage-only to actual USDT amount
   - Now correctly calculates: positionValue × priceChange% × leverage
   - Previously: 100U@5% and 1000U@5% both showed 5.0
   - Now: Properly reflects different position sizes and leverage

2. Position Tracking: Added quantity and leverage to open position records
   - Store complete trade data for accurate PnL calculation
   - Previously only stored: side, openPrice, openTime
   - Now includes: quantity, leverage for proper accounting

3. Position Key: Fixed to distinguish long/short positions
   - Changed from symbol to symbol_side (e.g., BTCUSDT_long)
   - Prevents conflicts when holding both long and short positions

4. Sharpe Ratio: Replaced custom Newton's method with math.Sqrt
   - Simplified standard deviation calculation
   - More reliable and maintainable

Impact: Win rate, profit factor, and Sharpe ratio now based on accurate USDT amounts

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-29 15:30:32 +08:00
tinkle
1d697c978f Refactor: Give AI full freedom to analyze raw sequence data
Remove prescriptive indicator combinations and let AI freely use all available data.

**Changes**:
- Emphasized AI has access to **raw sequence data** (MidPrices array, 4h candles)
- Listed all available sequences: price, technical (EMA/MACD/RSI), and capital flow (volume/OI)
- Removed hard-coded indicator combinations (e.g., "MACD + RSI + Volume")
- Changed from prescriptive examples to open-ended analysis freedom
- AI can now freely perform trend analysis, pattern recognition, support/resistance calculation
- Reduced minimum close-open interval from 30min to 15min for more flexibility

**Before**:
```
强信号示例:
- 趋势突破 + 多个指标确认(MACD + RSI + 成交量)
- 持仓量暴增 + 价格突破关键位
```

**After**:
```
你拥有的完整数据:
- 📊 原始序列:3分钟价格序列(MidPrices数组) + 4小时K线序列
- 📈 技术序列:EMA20序列、MACD序列、RSI7序列、RSI14序列
- 💰 资金序列:成交量序列、持仓量(OI)序列、资金费率

分析方法(完全由你自主决定):
- 自由运用序列数据,你可以做趋势分析、形态识别、支撑阻力计算
- 多维度交叉验证(价格+量+OI+指标+序列形态)
- 用你认为最有效的方法发现高确定性机会
```

**Philosophy**: Trust AI to discover effective patterns in raw data rather than constraining it to pre-defined indicator combinations.

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-29 14:33:54 +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-community
f07ad429a8 Merge pull request #9 from hrzisme/fix/empty-api-url-default-coins
fix: 当API URL为空时使用默认币种列表,避免循环请求失败
2025-10-29 13:06:19 +08:00
nobody
ccfa48688b feat: 添加use_default_coins开关,简化默认币种配置
- 新增use_default_coins配置项:true=使用默认8个主流币种,false=使用API币种池
- 更直观的配置方式,新手可直接设置true快速开始
- 优先级:use_default_coins > coin_pool_api_url > 缓存 > 默认列表
- 更新所有语言版本README(en/zh-CN/ru/uk)添加配置说明
- 更新config.json.example示例文件
2025-10-29 12:59:12 +08:00
tinkle
f3b7131ba8 Refactor: Enhance AI decision engine with Sharpe ratio optimization
Major improvements to the AI trading decision engine:

**Core Changes in decision/engine.go** (175 lines modified):

1. **Sharpe Ratio Optimization Focus**
   - Restructured system prompt to emphasize Sharpe ratio maximization
   - Added clear guidance: high-quality trades over frequent trading
   - Explained that 3-minute scan interval ≠ trade every cycle

2. **Trading Frequency Controls**
   - Defined optimal frequency: 2-4 trades/day (0.1-0.2 trades/hour)
   - Over-trading threshold: >2 trades/hour indicates issues
   - Minimum holding period: 30-60 minutes per position

3. **Long/Short Balance Incentives**
   - Emphasized equal profit potential for long and short positions
   - Removed long-bias with explicit short trading encouragement
   - Clear guidance: uptrend→long, downtrend→short, sideways→wait

4. **Stricter Entry Signal Standards**
   - Strong signals only: confidence ≥75, multi-indicator confirmation
   - Weak signals explicitly discouraged (single indicator, unclear trend)
   - Self-check mechanism to prevent premature re-entry (<30min)

5. **Enhanced Sharpe Ratio Feedback Loop**
   - Sharpe < -0.5: Stop trading for 6+ cycles (18min), deep reflection
   - Sharpe -0.5~0: Strict control, confidence >80 only
   - Sharpe 0~0.7: Maintain current strategy
   - Sharpe >0.7: Consider position size increase

6. **Risk-Reward Ratio Validation**
   - Added hard constraint: R:R must be ≥ 3.0:1
   - Automatic calculation and validation in `validateDecision()`
   - Rejects trades with insufficient risk-reward ratio

7. **Improved Prompt Structure**
   - More organized sections with clear headers
   - Actionable guidance instead of abstract principles
   - Better examples for JSON output format

**Impact**: These changes should significantly improve trading quality,
reduce over-trading, and increase Sharpe ratio through better risk management
and trade selection discipline.

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-29 12:49:34 +08:00
nobody
7a0612b2db fix: 当API URL为空时使用默认币种列表,避免循环请求失败
- 添加默认主流币种列表(BTC、ETH、SOL、BNB、XRP、DOGE、ADA、HYPE)
- 在GetCoinPool()中检查coin_pool_api_url,为空时直接返回默认列表
- 在GetOITopPositions()中检查oi_top_api_url,为空时跳过OI Top数据
- 更新README文档,说明API URL可选配置和默认币种列表
- 修复:避免空URL导致的循环请求和"unsupported protocol scheme"错误
2025-10-29 12:23:29 +08:00
awake 0x
deadd2e437 sync: Sync complete codebase from nofx internal version
Full code synchronization from nofx internal repository to open-nofx.
Updated all source files, documentation, and configuration.

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-29 12:00:09 +08:00
tinkle
321b3395e7 sync: Sync complete codebase from nofx internal version
Full synchronization of all files from nofx to open-nofx repository.
Updated documentation and source code to match internal version.

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-29 11:42:20 +08:00
tinkle
8f5ee23fa6 sync: Sync complete codebase from nofx internal version
Synchronize all source code, documentation, and configuration files
from the internal nofx repository to the open-nofx public repository.

This includes:
- Updated README files (EN/ZH/RU/UK) with Binance registration info
- Latest source code across all modules
- Current dependencies and configurations

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-29 11:37:33 +08:00
tinkle
6ef15e27d8 docs: Update README to reflect new codebase architecture
- Split market/ into mcp/, decision/, and market/ modules
- Update trader log directory names (trader1/2 -> qwen/deepseek_trader)
- Reflect modular architecture changes in documentation

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-29 11:26:49 +08:00