diff --git a/.github/ISSUE_TEMPLATE/bounty_claim.md b/.github/ISSUE_TEMPLATE/bounty_claim.md new file mode 100644 index 00000000..b8fc97eb --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bounty_claim.md @@ -0,0 +1,93 @@ +--- +name: Bounty Claim +about: Claim a bounty task or propose a new bounty +title: '[BOUNTY CLAIM] ' +labels: bounty +assignees: '' +--- + +## 💰 Bounty Information + +**Claiming existing bounty?** +- Issue #: +- Bounty amount: + +**OR proposing new bounty?** +- Proposed feature/fix: +- Estimated effort: [Small / Medium / Large] + +--- + +## 👀 About You + +**Name/Username:** + +**Contact:** +- GitHub: @your_username +- Telegram: @your_telegram (optional) +- Email: your@email.com (optional) + +**Relevant Experience:** +- +- +- + +--- + +## 📋 Implementation Plan + +### 1. Approach + +- How will you implement this? +- What components will be affected? +- Any dependencies or libraries needed? + +### 2. Timeline +- **Start date:** +- **Estimated completion:** +- **Milestones:** + - [ ] Week 1: ... + - [ ] Week 2: ... + - [ ] Week 3: ... + +### 3. Deliverables +- [ ] Working code (merged PR) +- [ ] Unit tests (if applicable) +- [ ] Documentation updates +- [ ] Demo video/screenshots + +--- + +## 🔍 Questions for Maintainers + + + +1. +2. +3. + +--- + +## 📚 References + + + +- + +--- + +## ✅ Acknowledgment + +By claiming this bounty, I acknowledge that: +- [ ] I have read the [Contributing Guide](../../CONTRIBUTING.md) +- [ ] I will follow the [Code of Conduct](../../CODE_OF_CONDUCT.md) +- [ ] I understand the acceptance criteria +- [ ] My contribution will be licensed under MIT License +- [ ] Payment is subject to successful PR merge + +--- + +**For maintainers:** +- [ ] Bounty claim approved +- [ ] Issue assigned to claimant +- [ ] Timeline agreed upon diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 00000000..e41f17b0 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,47 @@ +--- +name: Bug Report +about: Report a bug to help us improve NOFX +title: '[BUG] ' +labels: bug +assignees: '' +--- + +## 🐛 Bug Description + + +## 📋 Steps to Reproduce +1. Go to '...' +2. Click on '...' +3. Run command '...' +4. See error + +## ✅ Expected Behavior + + +## ❌ Actual Behavior + + +## 📞 Screenshots / Logs + + +``` +Paste logs here +``` + +## 💻 Environment +- **OS:** [e.g. macOS 13, Ubuntu 22.04, Windows 11] +- **Go Version:** [e.g. 1.21.5] +- **Node.js Version:** [e.g. 18.17.0] +- **NOFX Version/Commit:** [e.g. v3.0.0 or commit hash] +- **Deployment Method:** [Docker / Manual / PM2] +- **Exchange:** [Binance / Hyperliquid / Aster] + +## 🔧 Additional Context + + +- Does this happen consistently or intermittently? +- Did it work before? When did it break? +- Any recent configuration changes? + +## ✋ Possible Solution + diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 00000000..8fd87aeb --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,153 @@ +# Pull Request + +## 📝 Description + + + +## 🎯 Type of Change + + + +- [ ] 🐛 Bug fix (non-breaking change which fixes an issue) +- [ ] ✹ New feature (non-breaking change which adds functionality) +- [ ] 💥 Breaking change (fix or feature that would cause existing functionality to not work as expected) +- [ ] 📝 Documentation update +- [ ] 🎚 Code style update (formatting, renaming) +- [ ] ♻ Refactoring (no functional changes) +- [ ] ⚡ Performance improvement +- [ ] ✅ Test update +- [ ] 🔧 Build/config change + +## 🔗 Related Issues + + + +- Closes # +- Related to # + +## 📋 Changes Made + + + +- Change 1 +- Change 2 +- Change 3 + +## 🧪 Testing + +### Manual Testing + + + +- [ ] Tested locally (manual verification) +- [ ] Tested on testnet (for exchange integrations) +- [ ] Tested with different configurations +- [ ] Verified no existing functionality broke + +### Test Environment + +- **OS:** [e.g. macOS, Ubuntu] +- **Go Version:** [e.g. 1.21.5] +- **Exchange:** [if applicable] + +### Test Results + + + +``` +Test output here +``` + +## 📞 Screenshots / Demo + + + + + +**Before:** + + +**After:** + + +## ✅ Checklist + + + +### Code Quality + +- [ ] My code follows the project's code style ([Contributing Guide](../CONTRIBUTING.md)) +- [ ] I have performed a self-review of my code +- [ ] I have commented my code, particularly in hard-to-understand areas +- [ ] My changes generate no new warnings or errors +- [ ] Code compiles successfully (`go build` / `npm run build`) +- [ ] I have run `go fmt` (for Go code) + +### Testing + +- [ ] I have added tests that prove my fix is effective or that my feature works +- [ ] New and existing unit tests pass locally +- [ ] I have tested on testnet (for trading/exchange changes) + +### Documentation + +- [ ] I have updated the documentation accordingly +- [ ] I have updated the README if needed +- [ ] I have added inline code comments where necessary +- [ ] I have updated type definitions (for TypeScript changes) + +### Git + +- [ ] My commits follow the conventional commits format (`feat:`, `fix:`, etc.) +- [ ] I have rebased my branch on the latest `dev` branch +- [ ] There are no merge conflicts + +## 🔒 Security Considerations + + + +- [ ] No API keys or secrets are hardcoded +- [ ] User inputs are properly validated +- [ ] No SQL injection vulnerabilities introduced +- [ ] Authentication/authorization properly handled +- [ ] N/A (not security-related) + +## ⚡ Performance Impact + + + +- [ ] No significant performance impact +- [ ] Performance improved +- [ ] Performance may be impacted (explain below) + + + +## 📚 Additional Notes + + + +--- + +## For Bounty Claims + + + +- [ ] This PR is for bounty issue # +- [ ] All acceptance criteria from the bounty issue are met +- [ ] I have included a demo video/screenshots +- [ ] I am ready for payment upon merge + +**Payment Details:** + +--- + +## 🙏 Reviewer Notes + + + +--- + +**By submitting this PR, I confirm that:** +- [ ] I have read the [Contributing Guidelines](../CONTRIBUTING.md) +- [ ] I agree to the [Code of Conduct](../CODE_OF_CONDUCT.md) +- [ ] My contribution is licensed under the MIT License diff --git a/.gitignore b/.gitignore index 4dc2afc9..ad0d2a5b 100644 --- a/.gitignore +++ b/.gitignore @@ -3,6 +3,9 @@ *.iml *.xml +# AI 工具 +.claude/ + # 猖译产物 nofx-auto *.exe diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 00000000..f520303d --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,203 @@ +# Changelog + +All notable changes to the NOFX project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +**Languages:** [English](CHANGELOG.md) | [äž­æ–‡](CHANGELOG.zh-CN.md) + +--- + +## [Unreleased] + +### Added +- Documentation system with multi-language support (EN/CN/RU/UK) +- Complete getting-started guides (Docker, PM2, Custom API) +- Architecture documentation with system design details +- User guides with FAQ and troubleshooting +- Community documentation with bounty programs + +### Changed +- Reorganized documentation structure into logical categories +- Updated all README files with proper navigation links + +--- + +## [3.0.0] - 2025-10-30 + +### Added - Major Architecture Transformation 🚀 + +**Complete System Redesign - Web-Based Configuration Platform** + +This is a **major breaking update** that completely transforms NOFX from a static config-based system to a modern web-based trading platform. + +#### Database-Driven Architecture +- SQLite integration replacing static JSON config +- Persistent storage with automatic timestamps +- Foreign key relationships and triggers for data consistency +- Separate tables for AI models, exchanges, traders, and system config + +#### Web-Based Configuration Interface +- Complete web-based configuration management (no more JSON editing) +- AI Model setup through web interface (DeepSeek/Qwen API keys) +- Exchange management (Binance/Hyperliquid credentials) +- Dynamic trader creation (combine any AI model with any exchange) +- Real-time control (start/stop traders without system restart) + +#### Flexible Architecture +- Separation of concerns (AI models and exchanges independent) +- Mix & match capability (unlimited combinations) +- Scalable design (support for unlimited traders) +- Clean slate approach (no default traders) + +#### Enhanced API Layer +- RESTful design with complete CRUD operations +- New endpoints: + - `GET/PUT /api/models` - AI model configuration + - `GET/PUT /api/exchanges` - Exchange configuration + - `POST/DELETE /api/traders` - Trader management + - `POST /api/traders/:id/start|stop` - Trader control +- Updated documentation for all API endpoints + +#### Modernized Codebase +- Type safety with proper separation of configuration types +- Database abstraction with prepared statements +- Comprehensive error handling and validation +- Better code organization (database, API, business logic) + +### Changed +- **BREAKING**: Old `config.json` files no longer used +- Configuration must be done through web interface +- Much easier setup and better UX +- No more server restarts for configuration changes + +### Why This Matters +- 🎯 **User Experience**: Much easier to configure and manage +- 🔧 **Flexibility**: Create any combination of AI models and exchanges +- 📊 **Scalability**: Support for complex multi-trader setups +- 🔒 **Reliability**: Database ensures data persistence and consistency +- 🚀 **Future-Proof**: Foundation for advanced features + +--- + +## [2.0.2] - 2025-10-29 + +### Fixed - Critical Bug Fixes: Trade History & Performance Analysis + +#### PnL Calculation - Major Error Fixed +- **Fixed**: PnL now calculated as actual USDT amount instead of percentage only +- Previously ignored position size and leverage (e.g., 100 USDT @ 5% = 1000 USDT @ 5%) +- Now: `PnL (USDT) = Position Value × Price Change % × Leverage` +- Impact: Win rate, profit factor, and Sharpe ratio now accurate + +#### Position Tracking - Missing Critical Data +- **Fixed**: Open position records now store quantity and leverage +- Previously only stored price and time +- Essential for accurate PnL calculations + +#### Position Key Logic - Long/Short Conflict +- **Fixed**: Changed from `symbol` to `symbol_side` format +- Now properly distinguishes between long and short positions +- Example: `BTCUSDT_long` vs `BTCUSDT_short` + +#### Sharpe Ratio Calculation - Code Optimization +- **Changed**: Replaced custom Newton's method with `math.Sqrt` +- More reliable, maintainable, and efficient + +### Why This Matters +- Historical trade statistics now show real USDT profit/loss +- Performance comparison between different leverage trades is accurate +- AI self-learning mechanism receives correct feedback +- Multi-position tracking (long + short simultaneously) works correctly + +--- + +## [2.0.2] - 2025-10-29 + +### Fixed - Aster Exchange Precision Error + +- Fixed Aster exchange precision error (code -1111) +- Improved price and quantity formatting to match exchange requirements +- Added detailed precision processing logs for debugging +- Enhanced all order functions with proper precision handling + +#### Technical Details +- Added `formatFloatWithPrecision` function +- Price and quantity formatted according to exchange specifications +- Trailing zeros removed to optimize API requests + +--- + +## [2.0.1] - 2025-10-29 + +### Fixed - ComparisonChart Data Processing + +- Fixed ComparisonChart data processing logic +- Switched from cycle_number to timestamp grouping +- Resolved chart freezing issue when backend restarts +- Improved chart data display (shows all historical data chronologically) +- Enhanced debugging logs + +--- + +## [2.0.0] - 2025-10-28 + +### Added - Major Updates + +- AI self-learning mechanism (historical feedback, performance analysis) +- Multi-trader competition mode (Qwen vs DeepSeek) +- Binance-style UI (complete interface imitation) +- Performance comparison charts (real-time ROI comparison) +- Risk control optimization (per-coin position limit adjustment) + +### Fixed + +- Fixed hardcoded initial balance issue +- Fixed multi-trader data sync issue +- Optimized chart data alignment (using cycle_number) + +--- + +## [1.0.0] - 2025-10-27 + +### Added - Initial Release + +- Basic AI trading functionality +- Decision logging system +- Simple Web interface +- Support for Binance Futures +- DeepSeek and Qwen AI model integration + +--- + +## How to Use This Changelog + +### For Users +- Check the [Unreleased] section for upcoming features +- Review version sections to understand what changed +- Follow migration guides for breaking changes + +### For Contributors +When making changes, add them to the [Unreleased] section under appropriate categories: +- **Added** - New features +- **Changed** - Changes to existing functionality +- **Deprecated** - Features that will be removed +- **Removed** - Features that were removed +- **Fixed** - Bug fixes +- **Security** - Security fixes + +When releasing a new version, move [Unreleased] items to a new version section with date. + +--- + +## Links + +- [Documentation](docs/README.md) +- [Contributing Guidelines](CONTRIBUTING.md) +- [Security Policy](SECURITY.md) +- [GitHub Repository](https://github.com/tinkle-community/nofx) + +--- + +**Last Updated:** 2025-11-01 diff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.md new file mode 100644 index 00000000..0bfdab3d --- /dev/null +++ b/CHANGELOG.zh-CN.md @@ -0,0 +1,203 @@ +# 曎新日志 + +NOFX 项目的所有重芁曎改郜将记圕圚歀文件䞭。 + +本文件栌匏基于 [Keep a Changelog](https://keepachangelog.com/zh-CN/1.0.0/) +本项目遵埪 [语义化版本](https://semver.org/lang/zh-CN/)。 + +**语蚀:** [English](CHANGELOG.md) | [äž­æ–‡](CHANGELOG.zh-CN.md) + +--- + +## [未发垃] + +### 新增 +- 倚语蚀文档系统英文/äž­æ–‡/俄语/乌克兰语 +- 完敎的快速匀始指南Docker、PM2、自定义 API +- 架构文档包含系统讟计细节 +- 甚户指南包含 FAQ 和故障排陀 +- 瀟区文档包含悬赏计划 + +### 变曎 +- 重组文档结构䞺逻蟑分类 +- 曎新所有 README 文件添加适圓的富航铟接 + +--- + +## [3.0.0] - 2025-10-30 + +### 新增 - 重倧架构变革 🚀 + +**系统完党重新讟计 - 基于 Web 的配眮平台** + +这是䞀䞪**重倧砎坏性曎新**将 NOFX 从基于静态配眮的系统完党蜬变䞺现代化的 Web 亀易平台。 + +#### 数据库驱劚架构 +- SQLite 集成取代静态 JSON 配眮 +- 持久化存傚自劚时闎戳 +- 倖键关系和觊发噚确保数据䞀臎性 +- 䞺 AI 暡型、亀易所、亀易员和系统配眮分犻衚结构 + +#### 基于 Web 的配眮界面 +- 完敎的 Web 配眮管理无需猖蟑 JSON +- 通过 Web 界面讟眮 AI 暡型DeepSeek/Qwen API 密钥 +- 亀易所管理Binance/Hyperliquid 凭证 +- 劚态创建亀易员结合任意 AI 暡型和亀易所 +- 实时控制无需重启即可启劚/停止亀易员 + +#### 灵掻架构 +- 关泚点分犻AI 暡型和亀易所独立 +- 混合搭配胜力无限组合 +- 可扩展讟计支持无限亀易员 +- 枅掁起点无默讀亀易员 + +#### 增区的 API 层 +- RESTful 讟计完敎的 CRUD 操䜜 +- 新端点 + - `GET/PUT /api/models` - AI 暡型配眮 + - `GET/PUT /api/exchanges` - 亀易所配眮 + - `POST/DELETE /api/traders` - 亀易员管理 + - `POST /api/traders/:id/start|stop` - 亀易员控制 +- 曎新所有 API 端点文档 + +#### 现代化代码库 +- 类型安党适圓分犻配眮类型 +- 数据库抜象䜿甚预倄理语句 +- 党面的错误倄理和验证 +- 曎奜的代码组织数据库、API、䞚务逻蟑 + +### 变曎 +- **砎坏性变曎**䞍再䜿甚旧的 `config.json` 文件 +- 必须通过 Web 界面进行配眮 +- 讟眮曎简单甚户䜓验曎奜 +- 配眮曎改无需重启服务噚 + +### 䞺什么重芁 +- 🎯 **甚户䜓验**配眮和管理曎容易 +- 🔧 **灵掻性**创建 AI 暡型和亀易所的任意组合 +- 📊 **可扩展性**支持倍杂的倚亀易员讟眮 +- 🔒 **可靠性**数据库确保数据持久性和䞀臎性 +- 🚀 **面向未来**䞺高级功胜奠定基础 + +--- + +## [2.0.2] - 2025-10-29 + +### 修倍 - 关键错误修倍亀易历史和性胜分析 + +#### 盈亏计算 - 重倧错误修倍 +- **修倍**盈亏现圚计算䞺实际 USDT 金额而䞍是仅癟分比 +- 之前応略了仓䜍倧小和杠杆䟋劂100 USDT @ 5% = 1000 USDT @ 5% +- 现圚`盈亏 (USDT) = 仓䜍价倌 × 价栌变化 % × 杠杆` +- 圱响胜率、盈利因子和倏普比率现圚准确 + +#### 仓䜍跟螪 - 猺倱关键数据 +- **修倍**持仓记圕现圚存傚数量和杠杆 +- 之前只存傚价栌和时闎 +- 这对准确的盈亏计算至关重芁 + +#### 仓䜍键逻蟑 - 倚空冲突 +- **修倍**从 `symbol` 改䞺 `symbol_side` 栌匏 +- 现圚正确区分倚倎和空倎仓䜍 +- 瀺䟋`BTCUSDT_long` vs `BTCUSDT_short` + +#### 倏普比率计算 - 代码䌘化 +- **变曎**甚 `math.Sqrt` 替换自定义牛顿法 +- 曎可靠、可绎技和高效 + +### 䞺什么重芁 +- 历史亀易统计现圚星瀺真实的 USDT 盈亏 +- 䞍同杠杆亀易之闎的性胜比蟃准确 +- AI 自孊习机制接收正确的反銈 +- 倚仓䜍跟螪同时倚空正垞工䜜 + +--- + +## [2.0.2] - 2025-10-29 + +### 修倍 - Aster 亀易所粟床错误 + +- 修倍 Aster 亀易所粟床错误代码 -1111 +- 改进价栌和数量栌匏化以匹配亀易所芁求 +- 添加诊细的粟床倄理日志甚于调试 +- 增区所有订单凜数的粟床倄理 + +#### 技术细节 +- 添加 `formatFloatWithPrecision` 凜数 +- 根据亀易所规范栌匏化价栌和数量 +- 删陀尟随零以䌘化 API 请求 + +--- + +## [2.0.1] - 2025-10-29 + +### 修倍 - ComparisonChart 数据倄理 + +- 修倍 ComparisonChart 数据倄理逻蟑 +- 从 cycle_number 切换到时闎戳分组 +- 解决后端重启时囟衚冻结问题 +- 改进囟衚数据星瀺按时闎顺序星瀺所有历史数据 +- 增区调试日志 + +--- + +## [2.0.0] - 2025-10-28 + +### 新增 - 重倧曎新 + +- AI 自孊习机制历史反銈、性胜分析 +- 倚亀易员竞赛暡匏Qwen vs DeepSeek +- 垁安风栌 UI完敎界面仿制 +- 性胜比蟃囟衚实时 ROI 比蟃 +- 风险控制䌘化每垁种仓䜍限制调敎 + +### 修倍 + +- 修倍硬猖码初始䜙额问题 +- 修倍倚亀易员数据同步问题 +- 䌘化囟衚数据对霐䜿甚 cycle_number + +--- + +## [1.0.0] - 2025-10-27 + +### 新增 - 初始版本 + +- 基础 AI 亀易功胜 +- 决策日志系统 +- 简单的 Web 界面 +- 支持垁安合纊 +- DeepSeek 和 Qwen AI 暡型集成 + +--- + +## 劂䜕䜿甚本曎新日志 + +### 甚户 +- 查看 [未发垃] 郚分了解即将掚出的功胜 +- 查看版本郚分了解变曎内容 +- 遵埪砎坏性变曎的迁移指南 + +### 莡献者 +进行曎改时将它们添加到 [未发垃] 郚分的盞应类别䞋 +- **新增** - 新功胜 +- **变曎** - 现有功胜的变曎 +- **匃甚** - 即将删陀的功胜 +- **移陀** - 已删陀的功胜 +- **修倍** - 错误修倍 +- **安党** - 安党修倍 + +发垃新版本时将 [未发垃] 项目移劚到垊日期的新版本郚分。 + +--- + +## 铟接 + +- [文档](docs/README.md) +- [莡献指南](CONTRIBUTING.md) +- [安党策略](SECURITY.md) +- [GitHub 仓库](https://github.com/tinkle-community/nofx) + +--- + +**最后曎新:** 2025-11-01 diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 00000000..d1c34065 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,237 @@ +# Contributor Covenant Code of Conduct / 莡献者公纊行䞺准则 + +**Languages:** [English](#english) | [äž­æ–‡](#äž­æ–‡) + +--- + +# English + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our +community a harassment-free experience for everyone, regardless of age, body +size, visible or invisible disability, ethnicity, sex characteristics, gender +identity and expression, level of experience, education, socio-economic status, +nationality, personal appearance, race, caste, color, religion, or sexual +identity and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, +diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our +community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, + and learning from the experience +* Focusing on what is best not just for us as individuals, but for the overall + community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or advances of + any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email address, + without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of +acceptable behavior and will take appropriate and fair corrective action in +response to any behavior that they deem inappropriate, threatening, offensive, +or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, and will communicate reasons for moderation +decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when +an individual is officially representing the community in public spaces. +Examples of representing our community include using an official e-mail address, +posting via an official social media account, or acting as an appointed +representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported to the community leaders responsible for enforcement at: + + +You can also report via: +- **Telegram:** Direct message to [@Web3Tinkle](https://t.me/Web3Tinkle) +- **Twitter:** DM to [@nofx_ai](https://x.com/nofx_ai) + +All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the +reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining +the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed +unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing +clarity around the nature of the violation and an explanation of why the +behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series of +actions. + +**Consequence**: A warning with consequences for continued behavior. No +interaction with the people involved, including unsolicited interaction with +those enforcing the Code of Conduct, for a specified period of time. This +includes avoiding interactions in community spaces as well as external channels +like social media. Violating these terms may lead to a temporary or permanent +ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including +sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public +communication with the community for a specified period of time. No public or +private interaction with the people involved, including unsolicited interaction +with those enforcing the Code of Conduct, is allowed during this period. +Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community +standards, including sustained inappropriate behavior, harassment of an +individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within the +community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 2.1, available at +[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1]. + +Community Impact Guidelines were inspired by +[Mozilla's code of conduct enforcement ladder][Mozilla CoC]. + +For answers to common questions about this code of conduct, see the FAQ at +[https://www.contributor-covenant.org/faq][FAQ]. Translations are available at +[https://www.contributor-covenant.org/translations][translations]. + +[homepage]: https://www.contributor-covenant.org +[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html +[Mozilla CoC]: https://github.com/mozilla/diversity +[FAQ]: https://www.contributor-covenant.org/faq +[translations]: https://www.contributor-covenant.org/translations + +--- + +# äž­æ–‡ + +## 我们的承诺 + +䜜䞺成员、莡献者和领富者我们承诺䜿瀟区䞭的每䞪人郜䞍受骚扰无论其幎韄、䜓型、明星或䞍明星的残疟、种族、性别特埁、性别讀同和衚蟟、经验氎平、教育皋床、瀟䌚经济地䜍、囜籍、䞪人倖貌、种族、种姓、肀色、宗教或性讀同和取向劂䜕。 + +我们承诺以有助于匀攟、友奜、倚元、包容和健康瀟区的方匏行事和互劚。 + +## 我们的标准 + +有助于䞺我们的瀟区创造积极环境的行䞺瀺䟋包括 + +* 对他人衚现出同理心和善意 +* 尊重䞍同的意见、观点和经验 +* 给予并䌘雅地接受建讟性反銈 +* 接受莣任并向受我们错误圱响的人道歉并从经验䞭孊习 +* 关泚䞍仅对我们䞪人最奜而䞔对敎䞪瀟区最奜的事情 + +䞍可接受的行䞺瀺䟋包括 + +* 䜿甚性化的语蚀或囟像以及任䜕圢匏的性关泚或性挑逗 +* 挑衅、䟮蟱性或莬损性评论以及人身或政治攻击 +* 公匀或私䞋骚扰 +* 未经他人明确讞可发垃他人的私人信息劂物理地址或电子邮件地址 +* 圚䞓䞚环境䞭可胜被合理讀䞺䞍适圓的其他行䞺 + +## 执行莣任 + +瀟区领富者莟莣阐明和执行我们可接受行䞺的标准并将对他们讀䞺䞍适圓、嚁胁性、冒犯性或有害的任䜕行䞺采取适圓和公平的纠正措斜。 + +瀟区领富者有权利和莣任删陀、猖蟑或拒绝䞍笊合本行䞺准则的评论、提亀、代码、wiki 猖蟑、问题和其他莡献并圚适圓时䌠蟟审栞决定的原因。 + +## 范囎 + +本行䞺准则适甚于所有瀟区空闎也适甚于䞪人圚公共空闎正匏代衚瀟区的情况。代衚我们瀟区的瀺䟋包括䜿甚官方电子邮件地址、通过官方瀟亀媒䜓莊户发垃信息或圚线䞊或线䞋掻劚䞭担任指定代衚。 + +## 执行 + +可以向莟莣执行的瀟区领富者报告滥甚、骚扰或其他䞍可接受行䞺的实䟋 + + +悚也可以通过以䞋方匏报告 +- **Telegram:** 盎接消息 [@Web3Tinkle](https://t.me/Web3Tinkle) +- **Twitter:** 私信 [@nofx_ai](https://x.com/nofx_ai) + +所有投诉郜将埗到迅速和公正的审查和调查。 + +所有瀟区领富者郜有义务尊重任䜕事件报告者的隐私和安党。 + +## 执行指南 + +瀟区领富者将遵埪这些瀟区圱响指南来确定他们讀䞺违反本行䞺准则的任䜕行劚的后果 + +### 1. 纠正 + +**瀟区圱响**䜿甚䞍适圓的语蚀或其他被讀䞺圚瀟区䞭䞍䞓䞚或䞍受欢迎的行䞺。 + +**后果**瀟区领富者的私䞋乊面譊告诎明违规的性莚和解释䞺什么行䞺䞍适圓。可胜芁求公匀道歉。 + +### 2. 譊告 + +**瀟区圱响**通过单䞀事件或䞀系列行劚违规。 + +**后果**譊告并诎明持续行䞺的后果。圚指定时闎内䞍䞎盞关人员互劚包括䞍䞻劚䞎执行行䞺准则的人互劚。这包括避免圚瀟区空闎以及倖郚枠道劂瀟亀媒䜓的互劚。违反这些条欟可胜富臎䞎时或氞久犁什。 + +### 3. 䞎时犁什 + +**瀟区圱响**䞥重违反瀟区标准包括持续的䞍圓行䞺。 + +**后果**圚指定时闎内䞎时犁止䞎瀟区进行任䜕圢匏的互劚或公匀亀流。圚歀期闎䞍允讞䞎盞关人员进行公匀或私䞋互劚包括䞍䞻劚䞎执行行䞺准则的人互劚。违反这些条欟可胜富臎氞久犁什。 + +### 4. 氞久犁什 + +**瀟区圱响**衚现出违反瀟区标准的暡匏包括持续的䞍圓行䞺、对䞪人的骚扰或对䞪人类别的攻击或莬䜎。 + +**后果**氞久犁止圚瀟区内进行任䜕圢匏的公匀互劚。 + +## 園属 + +本行䞺准则改猖自 [莡献者公纊][homepage] 2.1 版可圚 +[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1] 获取。 + +瀟区圱响指南受到 [Mozilla 行䞺准则执行阶梯][Mozilla CoC] 的启发。 + +有关本行䞺准则的垞见问题解答请参阅 [https://www.contributor-covenant.org/faq][FAQ]。翻译版本可圚 [https://www.contributor-covenant.org/translations][translations] 获取。 + +[homepage]: https://www.contributor-covenant.org +[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html +[Mozilla CoC]: https://github.com/mozilla/diversity +[FAQ]: https://www.contributor-covenant.org/faq +[translations]: https://www.contributor-covenant.org/translations diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000..5175fc6a --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 Tinkle Community (NOFX Project) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md index 7ac4f409..0fa6210e 100644 --- a/README.md +++ b/README.md @@ -6,10 +6,36 @@ [![License](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE) [![Backed by Amber.ac](https://img.shields.io/badge/Backed%20by-Amber.ac-orange.svg)](https://amber.ac) -**Languages:** [English](README.md) | [äž­æ–‡](README.zh-CN.md) | [УкраїМська](README.uk.md) | [РусскОй](README.ru.md) +**Languages:** [English](README.md) | [äž­æ–‡](docs/i18n/zh-CN/README.md) | [УкраїМська](docs/i18n/uk/README.md) | [РусскОй](docs/i18n/ru/README.md) **Official Twitter:** [@nofx_ai](https://x.com/nofx_ai) +**📚 Documentation:** [Docs Home](docs/README.md) | [Getting Started](docs/getting-started/README.md) | [Changelog](CHANGELOG.md) | [Contributing](CONTRIBUTING.md) | [Security](SECURITY.md) + +--- + +## 📑 Table of Contents + +- [🚀 Universal AI Trading Operating System](#-universal-ai-trading-operating-system) +- [👥 Developer Community](#-developer-community) +- [🆕 What's New](#-whats-new-latest-update) +- [📞 Screenshots](#-screenshots) +- [✹ Current Implementation](#-current-implementation---crypto-markets) +- [🔮 Roadmap](#-roadmap---universal-market-expansion) +- [🏗 Technical Architecture](#-technical-architecture) +- [💰 Register Binance Account](#-register-binance-account-save-on-fees) +- [🚀 Quick Start](#-quick-start) +- [📖 AI Decision Flow](#-ai-decision-flow) +- [🧠 AI Self-Learning](#-ai-self-learning-example) +- [📊 Web Interface Features](#-web-interface-features) +- [🎛 API Endpoints](#-api-endpoints) +- [⚠ Important Risk Warnings](#-important-risk-warnings) +- [🛠 Common Issues](#-common-issues) +- [📈 Performance Tips](#-performance-optimization-tips) +- [🔄 Changelog](#-changelog) +- [📄 License](#-license) +- [🀝 Contributing](#-contributing) + --- ## 🚀 Universal AI Trading Operating System @@ -168,78 +194,50 @@ NOFX is currently **fully operational in cryptocurrency markets** with the follo ## 🔮 Roadmap - Universal Market Expansion -Our proven crypto infrastructure is being extended to: +NOFX is on a mission to become the **Universal AI Trading Operating System** for all financial markets. -- **📈 Stock Markets**: US equities, A-shares, Hong Kong stocks -- **📊 Futures Markets**: Commodity futures, index futures -- **🎯 Options Trading**: Equity options, crypto options -- **💱 Forex Markets**: Major currency pairs, cross rates +**Vision:** Same architecture. Same agent framework. All markets. -**Same architecture. Same agent framework. All markets.** +**Expansion Markets:** +- 📈 **Stock Markets**: US equities, A-shares, Hong Kong stocks +- 📊 **Futures Markets**: Commodity futures, index futures +- 🎯 **Options Trading**: Equity options, crypto options +- 💱 **Forex Markets**: Major currency pairs, cross rates + +**Upcoming Features:** +- Enhanced AI capabilities (GPT-4, Claude 3, Gemini Pro, flexible prompt templates) +- New exchange integrations (OKX, Bybit, Lighter, EdgeX + CEX/Perp-DEX) +- Project structure refactoring (high cohesion, low coupling, SOLID principles) +- Security enhancements (AES-256 encryption for API keys, RBAC, 2FA improvements) +- User experience improvements (mobile-responsive, TradingView charts, alert system) + +📖 **For detailed roadmap and timeline, see:** +- **English:** [Roadmap Documentation](docs/roadmap/README.md) +- **äž­æ–‡:** [路线囟文档](docs/roadmap/README.zh-CN.md) --- ## 🏗 Technical Architecture -``` -nofx/ -├── main.go # Program entry (multi-trader manager) -├── config.json # Configuration file (API keys, ~~multi-trader config~~) (Trader config via web interface) -│ -├── api/ # HTTP API service -│ └── server.go # Gin framework, RESTful API -│ -├── trader/ # Trading core -│ ├── auto_trader.go # Auto trading main controller (single trader) -│ └── binance_futures.go # Binance futures API wrapper -│ -├── manager/ # Multi-trader management -│ └── trader_manager.go # Manages multiple trader instances -│ -├── mcp/ # Model Context Protocol - AI communication -│ └── client.go # AI API client (DeepSeek/Qwen integration) -│ -├── decision/ # AI decision engine -│ └── engine.go # Decision logic with historical feedback -│ -├── market/ # Market data fetching -│ └── data.go # Market data & technical indicators (K-line, RSI, MACD) -│ -├── pool/ # Coin pool management -│ └── coin_pool.go # AI500 + OI Top merged pool -│ -├── logger/ # Logging system -│ └── decision_logger.go # Decision recording + performance analysis -│ -├── decision_logs/ # Decision log storage -│ ├── qwen_trader/ # Qwen trader logs -│ └── deepseek_trader/ # DeepSeek trader logs -│ -└── web/ # React frontend - ├── src/ - │ ├── components/ # React components - │ │ ├── EquityChart.tsx # Equity curve chart - │ │ ├── ComparisonChart.tsx # Multi-AI comparison chart - │ │ └── CompetitionPage.tsx # Competition leaderboard - │ ├── lib/api.ts # API call wrapper - │ ├── types/index.ts # TypeScript types - │ ├── index.css # Binance-style CSS - │ └── App.tsx # Main app - └── package.json -``` +NOFX is built with a modern, modular architecture: -### Core Dependencies +- **Backend:** Go with Gin framework, SQLite database +- **Frontend:** React 18 + TypeScript + Vite + TailwindCSS +- **Multi-Exchange Support:** Binance, Hyperliquid, Aster DEX +- **AI Integration:** DeepSeek, Qwen, and custom OpenAI-compatible APIs +- **State Management:** Zustand for frontend, database-driven for backend +- **Real-time Updates:** SWR with 5-10s polling intervals -**Backend (Go)** -- `github.com/adshao/go-binance/v2` - Binance API client -- `github.com/markcheno/go-talib` - Technical indicator calculation (TA-Lib) -- `github.com/gin-gonic/gin` - HTTP API framework +**Key Features:** +- 🗄 Database-driven configuration (no more JSON editing) +- 🔐 JWT authentication with optional 2FA support +- 📊 Real-time performance tracking and analytics +- 🀖 Multi-AI competition mode with live comparison +- 🔌 RESTful API for all configuration and monitoring -**Frontend (React + TypeScript)** -- `react` + `react-dom` - UI framework -- `recharts` - Chart library (equity curve, comparison charts) -- `swr` - Data fetching and caching -- `tailwindcss` - CSS framework +📖 **For detailed architecture documentation, see:** +- **English:** [Architecture Documentation](docs/architecture/README.md) +- **äž­æ–‡:** [架构文档](docs/architecture/README.zh-CN.md) --- @@ -326,8 +324,8 @@ Open your browser and visit: **http://localhost:3000** ``` **📖 For detailed Docker deployment guide, troubleshooting, and advanced configuration:** -- **English**: See [DOCKER_DEPLOY.en.md](DOCKER_DEPLOY.en.md) -- **äž­æ–‡**: 查看 [DOCKER_DEPLOY.md](DOCKER_DEPLOY.md) +- **English**: See [docs/getting-started/docker-deploy.en.md](docs/getting-started/docker-deploy.en.md) +- **äž­æ–‡**: 查看 [docs/getting-started/docker-deploy.zh-CN.md](docs/getting-started/docker-deploy.zh-CN.md) --- @@ -436,7 +434,7 @@ go build -o nofx ``` ╔════════════════════════════════════════════════════════════╗ -║ 🀖 AI倚暡型亀易系统 - 支持 DeepSeek & Qwen ║ +║ 🀖 AI倚暡型亀易系统 - 支持 DeepSeek & Qwen ║ ╚════════════════════════════════════════════════════════════╝ 🀖 数据库䞭的AI亀易员配眮: @@ -688,12 +686,12 @@ The leverage settings control the maximum leverage the AI can use for each trade ~~**Configuration format:**~~ -~~```json +```json "leverage": { "btc_eth_leverage": 5, // Maximum leverage for BTC and ETH "altcoin_leverage": 5 // Maximum leverage for all other coins } -```~~ +``` *Note: Leverage is now configured through the web interface* @@ -715,20 +713,20 @@ The leverage settings control the maximum leverage the AI can use for each trade **Examples:** ~~**Safe configuration (subaccount or conservative):**~~ -~~```json +```json "leverage": { "btc_eth_leverage": 5, "altcoin_leverage": 5 } -```~~ +``` ~~**Aggressive configuration (main account only):**~~ -~~```json +```json "leverage": { "btc_eth_leverage": 20, "altcoin_leverage": 15 } -```~~ +``` *Note: Leverage configuration is now done through the web interface* @@ -915,109 +913,100 @@ Should return: `{"status":"ok"}` Each decision cycle (default 3 minutes), the system executes the following intelligent process: -``` -┌──────────────────────────────────────────────────────────┐ -│ 1. 📊 Analyze Historical Performance (last 20 cycles) │ -├─────────────────────────────────────────────────────────── -│ ✓ Calculate overall win rate, avg profit, P/L ratio │ -│ ✓ Per-coin statistics (win rate, avg P/L in USDT) │ -│ ✓ Identify best/worst performing coins │ -│ ✓ List last 5 trade details with accurate PnL │ -│ ✓ Calculate Sharpe ratio for risk-adjusted performance │ -│ 📌 NEW (v2.0.2): Accurate USDT PnL with leverage │ -└──────────────────────────────────────────────────────────┘ - ↓ -┌──────────────────────────────────────────────────────────┐ -│ 2. 💰 Get Account Status │ -├─────────────────────────────────────────────────────────── -│ • Total equity & available balance │ -│ • Number of open positions & unrealized P/L │ -│ • Margin usage rate (AI manages up to 90%) │ -│ • Daily P/L tracking & drawdown monitoring │ -└──────────────────────────────────────────────────────────┘ - ↓ -┌──────────────────────────────────────────────────────────┐ -│ 3. 🔍 Analyze Existing Positions (if any) │ -├─────────────────────────────────────────────────────────── -│ • For each position, fetch latest market data │ -│ • Calculate real-time technical indicators: │ -│ - 3min K-line: RSI(7), MACD, EMA20 │ -│ - 4hour K-line: RSI(14), EMA20/50, ATR │ -│ • Track position holding duration (e.g., "2h 15min") │ -│ 📌 NEW (v2.0.2): Shows how long each position held │ -│ • Display: Entry price, current price, P/L%, duration │ -│ • AI evaluates: Should hold or close? │ -└──────────────────────────────────────────────────────────┘ - ↓ -┌──────────────────────────────────────────────────────────┐ -│ 4. 🎯 Evaluate New Opportunities (candidate coins) │ -├─────────────────────────────────────────────────────────── -│ • Fetch coin pool (2 modes): │ -│ 🌟 Default Mode: BTC, ETH, SOL, BNB, XRP, etc. │ -│ ⚙ Advanced Mode: AI500 (top 20) + OI Top (top 20) │ -│ • Merge & deduplicate candidate coins │ -│ • Filter: Remove low liquidity (<15M USD OI value) │ -│ • Batch fetch market data + technical indicators │ -│ • Calculate volatility, trend strength, volume surge │ -└──────────────────────────────────────────────────────────┘ - ↓ -┌──────────────────────────────────────────────────────────┐ -│ 5. 🧠 AI Comprehensive Decision (DeepSeek/Qwen) │ -├─────────────────────────────────────────────────────────── -│ • Review historical feedback: │ -│ - Recent win rate & profit factor │ -│ - Best/worst coins performance │ -│ - Avoid repeating mistakes │ -│ • Analyze all raw sequence data: │ -│ - 3min price序列, 4hour K-line序列 │ -│ - Complete indicator sequences (not just latest) │ -│ 📌 NEW (v2.0.2): AI has full freedom to analyze │ -│ • Chain of Thought (CoT) reasoning process │ -│ • Output structured decisions: │ -│ - Action: close_long/close_short/open_long/open_short│ -│ - Coin symbol, quantity, leverage │ -│ - Stop-loss & take-profit levels (≥1:2 ratio) │ -│ • Decision: Wait/Hold/Close/Open │ -└──────────────────────────────────────────────────────────┘ - ↓ -┌──────────────────────────────────────────────────────────┐ -│ 6. ⚡ Execute Trades │ -├─────────────────────────────────────────────────────────── -│ • Priority order: Close existing → Then open new │ -│ • Risk checks before execution: │ -│ - Position size limits (1.5x for altcoins, 10x BTC) │ -│ - No duplicate positions (same coin + direction) │ -│ - Margin usage within 90% limit │ -│ • Auto-fetch & apply Binance LOT_SIZE precision │ -│ • Execute orders via Binance Futures API │ -│ • After closing: Auto-cancel all pending orders │ -│ • Record actual execution price & order ID │ -│ 📌 Track position open time for duration calculation │ -└──────────────────────────────────────────────────────────┘ - ↓ -┌──────────────────────────────────────────────────────────┐ -│ 7. 📝 Record Complete Logs & Update Performance │ -├─────────────────────────────────────────────────────────── -│ • Save decision log to decision_logs/{trader_id}/ │ -│ • Log includes: │ -│ - Complete Chain of Thought (CoT) │ -│ - Input prompt with all market data │ -│ - Structured decision JSON │ -│ - Account snapshot (balance, positions, margin) │ -│ - Execution results (success/failure, prices) │ -│ • Update performance database: │ -│ - Match open/close pairs by symbol_side key │ -│ 📌 NEW: Prevents long/short conflicts │ -│ - Calculate accurate USDT PnL: │ -│ PnL = Position Value × Price Δ% × Leverage │ -│ 📌 NEW: Considers quantity + leverage │ -│ - Store: quantity, leverage, open time, close time │ -│ - Update win rate, profit factor, Sharpe ratio │ -│ • Performance data feeds back into next cycle │ -└──────────────────────────────────────────────────────────┘ - ↓ - (Repeat every 3-5 min) -``` +### Step 1: 📊 Analyze Historical Performance (last 20 cycles) +- ✓ Calculate overall win rate, avg profit, P/L ratio +- ✓ Per-coin statistics (win rate, avg P/L in USDT) +- ✓ Identify best/worst performing coins +- ✓ List last 5 trade details with accurate PnL +- ✓ Calculate Sharpe ratio for risk-adjusted performance +- 📌 **NEW (v2.0.2)**: Accurate USDT PnL with leverage + +**↓** + +### Step 2: 💰 Get Account Status +- Total equity & available balance +- Number of open positions & unrealized P/L +- Margin usage rate (AI manages up to 90%) +- Daily P/L tracking & drawdown monitoring + +**↓** + +### Step 3: 🔍 Analyze Existing Positions (if any) +- For each position, fetch latest market data +- Calculate real-time technical indicators: + - 3min K-line: RSI(7), MACD, EMA20 + - 4hour K-line: RSI(14), EMA20/50, ATR +- Track position holding duration (e.g., "2h 15min") +- 📌 **NEW (v2.0.2)**: Shows how long each position held +- Display: Entry price, current price, P/L%, duration +- AI evaluates: Should hold or close? + +**↓** + +### Step 4: 🎯 Evaluate New Opportunities (candidate coins) +- Fetch coin pool (2 modes): + - 🌟 **Default Mode**: BTC, ETH, SOL, BNB, XRP, etc. + - ⚙ **Advanced Mode**: AI500 (top 20) + OI Top (top 20) +- Merge & deduplicate candidate coins +- Filter: Remove low liquidity (<15M USD OI value) +- Batch fetch market data + technical indicators +- Calculate volatility, trend strength, volume surge + +**↓** + +### Step 5: 🧠 AI Comprehensive Decision (DeepSeek/Qwen) +- Review historical feedback: + - Recent win rate & profit factor + - Best/worst coins performance + - Avoid repeating mistakes +- Analyze all raw sequence data: + - 3min price sequences, 4hour K-line sequences + - Complete indicator sequences (not just latest) + - 📌 **NEW (v2.0.2)**: AI has full freedom to analyze +- Chain of Thought (CoT) reasoning process +- Output structured decisions: + - Action: `close_long` / `close_short` / `open_long` / `open_short` + - Coin symbol, quantity, leverage + - Stop-loss & take-profit levels (≥1:2 ratio) +- Decision: Wait / Hold / Close / Open + +**↓** + +### Step 6: ⚡ Execute Trades +- Priority order: Close existing → Then open new +- Risk checks before execution: + - Position size limits (1.5x for altcoins, 10x BTC) + - No duplicate positions (same coin + direction) + - Margin usage within 90% limit +- Auto-fetch & apply Binance LOT_SIZE precision +- Execute orders via Binance Futures API +- After closing: Auto-cancel all pending orders +- Record actual execution price & order ID +- 📌 Track position open time for duration calculation + +**↓** + +### Step 7: 📝 Record Complete Logs & Update Performance +- Save decision log to `decision_logs/{trader_id}/` +- Log includes: + - Complete Chain of Thought (CoT) + - Input prompt with all market data + - Structured decision JSON + - Account snapshot (balance, positions, margin) + - Execution results (success/failure, prices) +- Update performance database: + - Match open/close pairs by `symbol_side` key + - 📌 **NEW**: Prevents long/short conflicts + - Calculate accurate USDT PnL: + - `PnL = Position Value × Price Δ% × Leverage` + - 📌 **NEW**: Considers quantity + leverage + - Store: quantity, leverage, open time, close time + - Update win rate, profit factor, Sharpe ratio +- Performance data feeds back into next cycle + +**↓** + +**🔄 (Repeat every 3-5 min)** ### Key Improvements in v2.0.2 @@ -1229,145 +1218,19 @@ sudo apt-get install libta-lib0-dev ## 🔄 Changelog -### v3.0.0 (2025-10-30) - Major Architecture Transformation +📖 **For detailed version history and updates, see:** -**🚀 Complete System Redesign - Web-Based Configuration Platform** +- **English:** [CHANGELOG.md](CHANGELOG.md) +- **äž­æ–‡:** [CHANGELOG.zh-CN.md](CHANGELOG.zh-CN.md) -This is a **major breaking update** that completely transforms NOFX from a static config-based system to a modern web-based trading platform. +**Latest Release:** v3.0.0 (2025-10-30) - Major Architecture Transformation -**Revolutionary Changes:** - -**1. Database-Driven Architecture** -- ✅ **SQLite Integration**: Replaced static JSON config with SQLite database -- ✅ **Persistent Storage**: All configurations stored in database with automatic timestamps -- ✅ **Data Integrity**: Foreign key relationships and triggers for data consistency -- ✅ **Schema Design**: Separate tables for AI models, exchanges, traders, and system config - -**2. Web-Based Configuration Interface** -- ✅ **No More JSON Editing**: Complete web-based configuration management -- ✅ **AI Model Setup**: Configure DeepSeek/Qwen API keys through web interface -- ✅ **Exchange Management**: Set up Binance/Hyperliquid credentials independently -- ✅ **Dynamic Trader Creation**: Create traders by combining any AI model with any exchange -- ✅ **Real-Time Control**: Start/stop traders without system restart - -**3. Flexible Architecture** -- ✅ **Separation of Concerns**: AI models and exchanges configured independently -- ✅ **Mix & Match**: Create unlimited combinations (e.g., Qwen + Binance, DeepSeek + Hyperliquid) -- ✅ **Scalable Design**: Support for unlimited traders and configurations -- ✅ **Clean Slate**: No default traders - create only what you need - -**4. Enhanced API Layer** -- ✅ **RESTful Design**: Complete CRUD operations for all configuration entities -- ✅ **New Endpoints**: - - `GET/PUT /api/models` - AI model configuration - - `GET/PUT /api/exchanges` - Exchange configuration - - `POST/DELETE /api/traders` - Trader management - - `POST /api/traders/:id/start|stop` - Trader control -- ✅ **Updated Documentation**: All API endpoints documented - -**5. Modernized Codebase** -- ✅ **Type Safety**: Proper separation of legacy and new configuration types -- ✅ **Database Abstraction**: Clean database layer with prepared statements -- ✅ **Error Handling**: Comprehensive error handling and validation -- ✅ **Code Organization**: Better separation between database, API, and business logic - -**Migration Notes:** -- ⚠ **Breaking Change**: Old ~~`config.json`~~ files are no longer used -- ⚠ **Fresh Start**: All configurations must be redone through web interface -- ✅ **Easier Setup**: Web-based configuration is much more user-friendly -- ✅ **Better UX**: No more server restarts for configuration changes - -**Why This Update Matters:** -- 🎯 **User Experience**: Much easier to configure and manage -- 🔧 **Flexibility**: Create any combination of AI models and exchanges -- 📊 **Scalability**: Support for complex multi-trader setups -- 🔒 **Reliability**: Database ensures data persistence and consistency -- 🚀 **Future-Proof**: Foundation for advanced features like trader templates, backtesting, etc. - -### v2.0.2 (2025-10-29) - -**Critical Bug Fixes - Trade History & Performance Analysis:** - -This version fixes **critical calculation errors** in the historical trade record and performance analysis system that significantly affected profitability statistics. - -**1. PnL Calculation - Major Error Fixed** (logger/decision_logger.go) -- **Problem**: Previously calculated PnL as percentage only, completely ignoring position size and leverage - - Example: 100 USDT position earning 5% and 1000 USDT position earning 5% both showed `5.0` as profit - - This made performance analysis completely inaccurate -- **Solution**: Now calculates actual USDT profit amount - ``` - PnL (USDT) = Position Value × Price Change % × Leverage - Example: 1000 USDT × 5% × 20x = 1000 USDT actual profit - ``` -- **Impact**: Win rate, profit factor, and Sharpe ratio now based on accurate USDT amounts - -**2. Position Tracking - Missing Critical Data** -- **Problem**: Open position records only stored price and time, missing quantity and leverage -- **Solution**: Now stores complete trade data: - - `quantity`: Position size (in coins) - - `leverage`: Leverage multiplier (e.g., 20x) - - These are essential for accurate PnL calculations - -**3. Position Key Logic - Long/Short Conflict** -- **Problem**: Used `symbol` as position key, causing data conflicts when holding both long and short - - Example: BTCUSDT long and BTCUSDT short would overwrite each other -- **Solution**: Changed to `symbol_side` format (e.g., `BTCUSDT_long`, `BTCUSDT_short`) - - Now properly distinguishes between long and short positions - -**4. Sharpe Ratio Calculation - Code Optimization** -- **Problem**: Used custom Newton's method for square root calculation -- **Solution**: Replaced with standard library `math.Sqrt` - - More reliable, maintainable, and efficient - -**Why This Update Matters:** -- ✅ Historical trade statistics now show **real USDT profit/loss** instead of meaningless percentages -- ✅ Performance comparison between different leverage trades is now accurate -- ✅ AI self-learning mechanism receives correct historical feedback -- ✅ Profit factor and Sharpe ratio calculations are now meaningful -- ✅ Multi-position tracking (long + short simultaneously) works correctly - -**Recommendation**: If you were running the system before this update, your historical statistics were inaccurate. After updating to v2.0.2, new trades will be calculated correctly. - -### v2.0.2 (2025-10-29) - -**Bug Fixes:** -- ✅ Fixed Aster exchange precision error (code -1111: "Precision is over the maximum defined for this asset") -- ✅ Improved price and quantity formatting to match exchange precision requirements -- ✅ Added detailed precision processing logs for debugging -- ✅ Enhanced all order functions (OpenLong, OpenShort, CloseLong, CloseShort, SetStopLoss, SetTakeProfit) with proper precision handling - -**Technical Details:** -- Added `formatFloatWithPrecision` function to convert float64 to strings with correct precision -- Price and quantity parameters are now formatted according to exchange's `pricePrecision` and `quantityPrecision` specifications -- Trailing zeros are removed from formatted values to optimize API requests - -### v2.0.1 (2025-10-29) - -**Bug Fixes:** -- ✅ Fixed ComparisonChart data processing logic - switched from cycle_number to timestamp grouping -- ✅ Resolved chart freezing issue when backend restarts and cycle_number resets -- ✅ Improved chart data display - now shows all historical data points chronologically -- ✅ Enhanced debugging logs for better troubleshooting - -### v2.0.0 (2025-10-28) - -**Major Updates:** -- ✅ AI self-learning mechanism (historical feedback, performance analysis) -- ✅ Multi-trader competition mode (Qwen vs DeepSeek) -- ✅ Binance-style UI (complete Binance interface imitation) -- ✅ Performance comparison charts (real-time ROI comparison) -- ✅ Risk control optimization (per-coin position limit adjustment) - -**Bug Fixes:** -- Fixed hardcoded initial balance issue -- Fixed multi-trader data sync issue -- Optimized chart data alignment (using cycle_number) - -### v1.0.0 (2025-10-27) -- Initial release -- Basic AI trading functionality -- Decision logging system -- Simple Web interface +**Recent Highlights:** +- 🚀 Complete system redesign with web-based configuration +- 🗄 Database-driven architecture (SQLite) +- 🎚 No more JSON editing - all configuration through web interface +- 🔧 Mix & match AI models with any exchange +- 📊 Enhanced API layer with comprehensive endpoints --- @@ -1379,10 +1242,14 @@ MIT License - See [LICENSE](LICENSE) file for details ## 🀝 Contributing -Issues and Pull Requests are welcome! +We welcome contributions from the community! See our comprehensive guides: -### Development Guide +- **📖 [Contributing Guide](CONTRIBUTING.md)** - Complete development workflow, code standards, and PR process +- **🀝 [Code of Conduct](CODE_OF_CONDUCT.md)** - Community guidelines and standards +- **💰 [Bounty Program](docs/community/bounty-guide.md)** - Earn rewards for contributions +- **🔒 [Security Policy](SECURITY.md)** - Report vulnerabilities responsibly +**Quick Start:** 1. Fork the project 2. Create feature branch (`git checkout -b feature/AmazingFeature`) 3. Commit changes (`git commit -m 'Add some AmazingFeature'`) diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 00000000..1052d013 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,469 @@ +# Security Policy / 安党政策 + +**Languages:** [English](#english) | [äž­æ–‡](#äž­æ–‡) + +--- + +# English + +## 🛡 Security Overview + +NOFX is an AI-powered trading system that handles real funds and API credentials. We take security seriously and appreciate the security community's efforts to responsibly disclose vulnerabilities. + +**Critical Areas:** +- 🔑 API key storage and handling +- 💰 Trading execution and fund management +- 🔐 Authentication and authorization +- 🗄 Database security (SQLite) +- 🌐 Web interface and API endpoints + +--- + +## 📋 Supported Versions + +We provide security updates for the following versions: + +| Version | Supported | Notes | +| ------- | ------------------ | -------------------- | +| 3.x | ✅ Fully supported | Current stable release | +| 2.x | ⚠ Limited support | Security fixes only | +| < 2.0 | ❌ Not supported | Please upgrade | + +**Recommendation:** Always use the latest stable release (v3.x) for best security. + +--- + +## 🔒 Reporting a Vulnerability + +### ⚠ Please DO NOT Publicly Disclose + +If you discover a security vulnerability in NOFX, please **DO NOT**: +- ❌ Open a public GitHub Issue +- ❌ Discuss it on social media (Twitter, Reddit, etc.) +- ❌ Share it in Telegram/Discord groups +- ❌ Post it on security forums before we've had time to fix it + +Public disclosure before a fix is available puts all users at risk. + +### ✅ Responsible Disclosure Process + +**Step 1: Report Privately** + +Contact core team directly: +- **Tinkle:** [@Web3Tinkle on Twitter](https://x.com/Web3Tinkle) (DM) + +**Alternative:** Encrypted communication via [Keybase](https://keybase.io/) (if available) + +**Step 2: Include These Details** + +```markdown +Subject: [SECURITY] Brief description of vulnerability + +## Vulnerability Description +Clear explanation of the security issue + +## Affected Components +- Which parts of the system are affected? +- Which versions are vulnerable? + +## Reproduction Steps +1. Step-by-step instructions +2. Sample code or commands (if applicable) +3. Expected vs actual behavior + +## Potential Impact +- Can funds be stolen? +- Can API keys be leaked? +- Can accounts be compromised? +- Rate the severity: Critical / High / Medium / Low + +## Suggested Fix (Optional) +If you have ideas for fixing it, please share! + +## Your Information +- Name (or pseudonym) +- Contact info for follow-up +- If you want public credit (yes/no) +``` + +**Step 3: Wait for Our Response** + +We will: +- ✅ Acknowledge receipt within **24 hours** +- ✅ Provide initial assessment within **72 hours** +- ✅ Keep you updated on fix progress +- ✅ Notify you before public disclosure + +--- + +## ⏱ Response Timeline + +| Stage | Timeline | Action | +|-------|----------|--------| +| **Acknowledgment** | 24 hours | Confirm we received your report | +| **Initial Assessment** | 72 hours | Verify vulnerability, rate severity | +| **Fix Development** | 7-30 days | Depends on complexity and severity | +| **Testing** | 3-7 days | Verify fix doesn't break functionality | +| **Public Disclosure** | After fix deployed | Publish security advisory | + +**Critical vulnerabilities** (fund theft, credential leaks) are prioritized and may be fixed within 48 hours. + +--- + +## 💰 Security Bounty Program (Optional) + +We offer rewards for valid security vulnerabilities: + +| Severity | Criteria | Reward | +|----------|----------|--------| +| **🔎 Critical** | Fund theft, API key extraction, RCE | **$500-1000 USD** | +| **🟠 High** | Authentication bypass, unauthorized trading | **$200-500 USD** | +| **🟡 Medium** | Information disclosure, XSS, CSRF | **$100-200 USD** | +| **🟢 Low** | Security improvements, minor issues | **$50-100 USD or Recognition** | + +**Note:** Bounty amounts are at maintainers' discretion based on: +- Severity and impact +- Quality of report +- Ease of exploitation +- Number of affected users + +**Out of Scope (No Bounty):** +- Issues in third-party libraries (report to them directly) +- Social engineering attacks +- DoS/DDoS attacks +- Issues requiring physical access +- Previously known/reported vulnerabilities + +--- + +## 🔐 Security Best Practices (For Users) + +To keep your NOFX deployment secure: + +### 1. API Key Management +```bash +# ✅ DO: Use environment variables +export BINANCE_API_KEY="your_key" +export BINANCE_SECRET_KEY="your_secret" + +# ❌ DON'T: Hardcode in source files +api_key = "abc123..." # NEVER DO THIS +``` + +### 2. Database Security +```bash +# ✅ Set proper permissions +chmod 600 nofx.db +chmod 600 config.json + +# ❌ DON'T: Leave files world-readable +chmod 777 nofx.db # NEVER DO THIS +``` + +### 3. Network Security +```bash +# ✅ Use firewall to restrict API access +# Only allow localhost to access API server +iptables -A INPUT -p tcp --dport 8080 -s 127.0.0.1 -j ACCEPT +iptables -A INPUT -p tcp --dport 8080 -j DROP + +# ❌ DON'T: Expose API to public internet without authentication +``` + +### 4. Use Subaccounts +- Create dedicated Binance subaccount for trading +- Limit maximum balance +- Restrict withdrawal permissions +- Use IP whitelist + +### 5. Test on Testnet First +- Hyperliquid: Use testnet mode +- Binance: Use testnet API (https://testnet.binancefuture.com) +- Never test with real funds initially + +### 6. Regular Updates +```bash +# Check for updates regularly +git pull origin main +go build -o nofx + +# Subscribe to security advisories +# Watch GitHub releases: https://github.com/tinkle-community/nofx/releases +``` + +--- + +## 🚚 Security Advisories + +Past security advisories will be published here: + +### 2025-XX-XX: [Title] +- **Severity:** [Critical/High/Medium/Low] +- **Affected Versions:** [x.x.x - x.x.x] +- **Fixed in:** [x.x.x] +- **Description:** [Brief description] +- **Mitigation:** [How to protect yourself] + +*No security advisories have been published yet.* + +--- + +## 🙏 Security Researchers Hall of Fame + +We thank the following security researchers for responsibly disclosing vulnerabilities: + +*No reports have been submitted yet. Be the first!* + +--- + +## 📚 Additional Resources + +**Security Documentation:** +- [OWASP Top 10](https://owasp.org/www-project-top-ten/) +- [CWE Top 25](https://cwe.mitre.org/top25/) +- [Binance API Security Best Practices](https://www.binance.com/en/support/faq/360002502072) + +**Audit Reports:** +- No third-party audits completed yet +- Self-audit checklist: [TODO: Add link] + +--- + +## 📞 Contact + +**For security issues ONLY:** +- 🐊 **Twitter DM:** [@Web3Tinkle](https://x.com/Web3Tinkle) + +**For general questions:** +- See [CONTRIBUTING.md](CONTRIBUTING.md) +- Join [Telegram Community](https://t.me/nofx_dev_community) + +--- + +**Thank you for helping keep NOFX secure!** 🔒 + +--- + +# äž­æ–‡ + +## 🛡 安党抂述 + +NOFX 是䞀䞪倄理真实资金和 API 凭证的 AI 亀易系统。我们非垞重视安党并感谢安党瀟区莟莣任地披露挏掞的努力。 + +**关键领域** +- 🔑 API 密钥存傚和倄理 +- 💰 亀易执行和资金管理 +- 🔐 身仜验证和授权 +- 🗄 数据库安党SQLite +- 🌐 Web 界面和 API 端点 + +--- + +## 📋 支持的版本 + +我们䞺以䞋版本提䟛安党曎新 + +| 版本 | 支持状态 | 诎明 | +| ------- | ------------------ | -------------------- | +| 3.x | ✅ 完党支持 | 圓前皳定版本 | +| 2.x | ⚠ 有限支持 | 仅安党修倍 | +| < 2.0 | ❌ 䞍支持 | 请升级 | + +**建议** 始终䜿甚最新的皳定版本v3.x以获埗最䜳安党性。 + +--- + +## 🔒 报告挏掞 + +### ⚠ 请勿公匀披露 + +劂果悚圚 NOFX 䞭发现安党挏掞请**䞍芁** +- ❌ 公匀创建 GitHub Issue +- ❌ 圚瀟亀媒䜓䞊讚论Twitter、Reddit 等 +- ❌ 圚 Telegram/Discord 矀组䞭分享 +- ❌ 圚我们有时闎修倍之前发垃到安党论坛 + +圚修倍可甚之前公匀披露䌚䜿所有甚户面䞎风险。 + +### ✅ 莟莣任的披露流皋 + +**步骀 1私䞋报告** + +盎接联系栞心团队 +- **Tinkle:** [@Web3Tinkle on Twitter](https://x.com/Web3Tinkle)私信 + +**替代方案** 通过 [Keybase](https://keybase.io/) 加密通信劂果可甚 + +**步骀 2包含这些诊细信息** + +```markdown +䞻题[SECURITY] 挏掞简芁描述 + +## 挏掞描述 +枅楚解释安党问题 + +## 受圱响的组件 +- 系统的哪些郚分受到圱响 +- 哪些版本存圚挏掞 + +## 倍现步骀 +1. 逐步诎明 +2. 瀺䟋代码或呜什劂果适甚 +3. 预期行䞺 vs 实际行䞺 + +## 朜圚圱响 +- 资金是吊可胜被盗 +- API 密钥是吊可胜泄露 +- 莊户是吊可胜被入䟵 +- 䞥重皋床评级䞥重 / 高 / äž­ / 䜎 + +## 建议修倍可选 +劂果悚有修倍的想法请分享 + +## 悚的信息 +- 姓名或化名 +- 后续联系信息 +- 是吊垌望公匀臎谢是/吊 +``` + +**步骀 3等埅我们的回倍** + +我们将 +- ✅ 圚 **24 小时**内确讀收到 +- ✅ 圚 **72 小时**内提䟛初步评䌰 +- ✅ 告知悚修倍进展 +- ✅ 圚公匀披露前通知悚 + +--- + +## ⏱ 响应时闎衚 + +| 阶段 | 时闎线 | 行劚 | +|-------|----------|--------| +| **确讀** | 24 小时 | 确讀我们收到了悚的报告 | +| **初步评䌰** | 72 小时 | 验证挏掞评䌰䞥重皋床 | +| **修倍匀发** | 7-30 倩 | 取决于倍杂性和䞥重皋床 | +| **测试** | 3-7 倩 | 验证修倍䞍䌚砎坏功胜 | +| **公匀披露** | 修倍郚眲后 | 发垃安党公告 | + +**䞥重挏掞**资金盗窃、凭证泄露䌚䌘先倄理可胜圚 48 小时内修倍。 + +--- + +## 💰 安党奖励计划可选 + +我们䞺有效的安党挏掞提䟛奖励 + +| 䞥重皋床 | 标准 | 奖励 | +|----------|----------|--------| +| **🔎 䞥重** | 资金盗窃、API 密钥提取、RCE | **$500-1000 USD** | +| **🟠 高** | 讀证绕过、未授权亀易 | **$200-500 USD** | +| **🟡 äž­** | 信息泄露、XSS、CSRF | **$100-200 USD** | +| **🟢 䜎** | 安党改进、小问题 | **$50-100 USD 或臎谢** | + +**泚意** 奖励金额由绎技者根据以䞋因玠酌情决定 +- 䞥重性和圱响 +- 报告莚量 +- 利甚隟易床 +- 受圱响甚户数量 + +**䞍圚范囎内无奖励** +- 第䞉方库的问题盎接向他们报告 +- 瀟䌚工皋攻击 +- DoS/DDoS 攻击 +- 需芁物理访问的问题 +- 已知/已报告的挏掞 + +--- + +## 🔐 安党最䜳实践甚户指南 + +保技悚的 NOFX 郚眲安党 + +### 1. API 密钥管理 +```bash +# ✅ 正确䜿甚环境变量 +export BINANCE_API_KEY="your_key" +export BINANCE_SECRET_KEY="your_secret" + +# ❌ 错误圚源文件䞭硬猖码 +api_key = "abc123..." # 氞远䞍芁这样做 +``` + +### 2. 数据库安党 +```bash +# ✅ 讟眮适圓的权限 +chmod 600 nofx.db +chmod 600 config.json + +# ❌ 䞍芁让文件党局可读 +chmod 777 nofx.db # 氞远䞍芁这样做 +``` + +### 3. 眑络安党 +```bash +# ✅ 䜿甚防火墙限制 API 访问 +# 仅允讞本地访问 API 服务噚 +iptables -A INPUT -p tcp --dport 8080 -s 127.0.0.1 -j ACCEPT +iptables -A INPUT -p tcp --dport 8080 -j DROP + +# ❌ 䞍芁圚没有身仜验证的情况䞋将 API 暎露到公共互联眑 +``` + +### 4. 䜿甚子莊户 +- 䞺亀易创建䞓甚的 Binance 子莊户 +- 限制最倧䜙额 +- 限制提现权限 +- 䜿甚 IP 癜名单 + +### 5. 先圚测试眑䞊测试 +- Hyperliquid䜿甚测试眑暡匏 +- Binance䜿甚测试眑 API (https://testnet.binancefuture.com) +- 最初氞远䞍芁甚真实资金测试 + +### 6. 定期曎新 +```bash +# 定期检查曎新 +git pull origin main +go build -o nofx + +# 订阅安党公告 +# 关泚 GitHub 发垃https://github.com/tinkle-community/nofx/releases +``` + +--- + +## 🚚 安党公告 + +过去的安党公告将圚歀发垃 + +### 2025-XX-XX: [标题] +- **䞥重皋床** [䞥重/高/äž­/䜎] +- **受圱响版本** [x.x.x - x.x.x] +- **已修倍版本** [x.x.x] +- **描述** [简芁描述] +- **猓解措斜** [劂䜕保技自己] + +*尚未发垃任䜕安党公告。* + +--- + +## 🙏 安党研究员名人堂 + +我们感谢以䞋安党研究员莟莣任地披露挏掞 + +*尚未收到任䜕报告。成䞺第䞀䞪* + +--- + +## 📞 联系方匏 + +**仅限安党问题** +- 🐊 **Twitter 私信** [@Web3Tinkle](https://x.com/Web3Tinkle) + +**䞀般问题** +- 加入 [Telegram 瀟区](https://t.me/nofx_dev_community) + +--- + +**感谢悚垮助保持 NOFX 的安党** 🔒 diff --git a/api/server.go b/api/server.go index a3c18431..b4a58dd1 100644 --- a/api/server.go +++ b/api/server.go @@ -88,12 +88,16 @@ func (s *Server) setupRoutes() { // 系统提瀺词暡板管理无需讀证 api.GET("/prompt-templates", s.handleGetPromptTemplates) api.GET("/prompt-templates/:name", s.handleGetPromptTemplate) + + // 公匀的竞赛数据无需讀证 + api.GET("/traders", s.handlePublicTraderList) + api.GET("/competition", s.handlePublicCompetition) // 需芁讀证的路由 protected := api.Group("/", s.authMiddleware()) { // AI亀易员管理 - protected.GET("/traders", s.handleTraderList) + protected.GET("/my-traders", s.handleTraderList) protected.GET("/traders/:id/config", s.handleGetTraderConfig) protected.POST("/traders", s.handleCreateTrader) protected.PUT("/traders/:id", s.handleUpdateTrader) @@ -115,8 +119,6 @@ func (s *Server) setupRoutes() { protected.POST("/user/signal-sources", s.handleSaveUserSignalSource) - // 竞赛总览 - protected.GET("/competition", s.handleCompetition) // 指定trader的数据䜿甚query参数 ?trader_id=xxx protected.GET("/status", s.handleStatus) @@ -1494,3 +1496,62 @@ func (s *Server) handleGetPromptTemplate(c *gin.Context) { "content": template.Content, }) } + +// handlePublicTraderList 获取公匀的亀易员列衚无需讀证 +func (s *Server) handlePublicTraderList(c *gin.Context) { + // 从所有甚户获取亀易员信息 + competition, err := s.traderManager.GetCompetitionData() + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{ + "error": fmt.Sprintf("获取亀易员列衚倱莥: %v", err), + }) + return + } + + // 获取traders数组 + tradersData, exists := competition["traders"] + if !exists { + c.JSON(http.StatusOK, []map[string]interface{}{}) + return + } + + traders, ok := tradersData.([]map[string]interface{}) + if !ok { + c.JSON(http.StatusInternalServerError, gin.H{ + "error": "亀易员数据栌匏错误", + }) + return + } + + // 返回亀易员基本信息过滀敏感信息 + result := make([]map[string]interface{}, 0, len(traders)) + for _, trader := range traders { + result = append(result, map[string]interface{}{ + "trader_id": trader["trader_id"], + "trader_name": trader["trader_name"], + "ai_model": trader["ai_model"], + "exchange": trader["exchange"], + "is_running": trader["is_running"], + "total_equity": trader["total_equity"], + "total_pnl": trader["total_pnl"], + "total_pnl_pct": trader["total_pnl_pct"], + "position_count": trader["position_count"], + "margin_used_pct": trader["margin_used_pct"], + }) + } + + c.JSON(http.StatusOK, result) +} + +// handlePublicCompetition 获取公匀的竞赛数据无需讀证 +func (s *Server) handlePublicCompetition(c *gin.Context) { + competition, err := s.traderManager.GetCompetitionData() + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{ + "error": fmt.Sprintf("获取竞赛数据倱莥: %v", err), + }) + return + } + + c.JSON(http.StatusOK, competition) +} diff --git a/config.json.example b/config.json.example index ac9d5ac6..fefa1673 100644 --- a/config.json.example +++ b/config.json.example @@ -1,5 +1,6 @@ { "admin_mode": true, + "beta_mode": false, "leverage": { "btc_eth_leverage": 5, "altcoin_leverage": 5 diff --git a/docs/MIGRATION_GUIDE.md b/docs/MIGRATION_GUIDE.md new file mode 100644 index 00000000..1f4dad42 --- /dev/null +++ b/docs/MIGRATION_GUIDE.md @@ -0,0 +1,242 @@ +# 📊 Documentation Migration Guide + +## What Changed? + +NOFX documentation has been reorganized into a structured `docs/` directory for better organization and navigation. + +## 🗺 File Locations (Old → New) + +### Deployment Guides +- `DOCKER_DEPLOY.en.md` → `docs/getting-started/docker-deploy.en.md` +- `DOCKER_DEPLOY.md` → `docs/getting-started/docker-deploy.zh-CN.md` +- `PM2_DEPLOYMENT.md` → `docs/getting-started/pm2-deploy.md` +- `CUSTOM_API.md` → `docs/getting-started/custom-api.md` + +### Community Docs +- `HOW_TO_POST_BOUNTY.md` → `docs/community/bounty-guide.md` +- `INTEGRATION_BOUNTY_HYPERLIQUID.md` → `docs/community/bounty-hyperliquid.md` +- `INTEGRATION_BOUNTY_ASTER.md` → `docs/community/bounty-aster.md` + +### Internationalization +- `README.zh-CN.md` → `docs/i18n/zh-CN/README.md` +- `README.ru.md` → `docs/i18n/ru/README.md` +- `README.uk.md` → `docs/i18n/uk/README.md` +- `垞见问题.md` → `docs/guides/faq.zh-CN.md` + +### Root Directory (Unchanged) +These stay in the root for GitHub recognition: +- `README.md` ✅ (stays in root) +- `LICENSE` ✅ (stays in root) +- `CONTRIBUTING.md` ✅ (stays in root) +- `CODE_OF_CONDUCT.md` ✅ (stays in root) +- `SECURITY.md` ✅ (stays in root) + +## 🎯 Why This Change? + +### Before (❌ Problems) +``` +nofx/ +├── README.md +├── README.zh-CN.md +├── README.ru.md +├── README.uk.md +├── DOCKER_DEPLOY.md +├── DOCKER_DEPLOY.en.md +├── PM2_DEPLOYMENT.md +├── CUSTOM_API.md +├── HOW_TO_POST_BOUNTY.md +├── INTEGRATION_BOUNTY_HYPERLIQUID.md +├── INTEGRATION_BOUNTY_ASTER.md +├── 垞见问题.md +└── ... (15+ markdown files in root!) +``` + +**Issues:** +- 😵 Too cluttered (15+ files in root) +- 🔍 Hard to find specific docs +- 🌍 Mixed languages +- 📚 No clear organization + +### After (✅ Benefits) +``` +nofx/ +├── README.md # Project homepage +├── LICENSE # Legal (GitHub needs it here) +├── CONTRIBUTING.md # GitHub auto-links +├── CODE_OF_CONDUCT.md # GitHub auto-links +├── SECURITY.md # GitHub auto-links +│ +└── docs/ # 📚 Documentation hub + ├── README.md # Documentation home + ├── getting-started/ # 🚀 Setup guides + ├── guides/ # 📘 User guides + ├── community/ # 👥 Contribution docs + ├── i18n/ # 🌍 Translations + └── architecture/ # 🏗 Technical docs +``` + +**Benefits:** +- ✅ Clean root directory +- ✅ Logical categorization +- ✅ Easy navigation +- ✅ Scalable structure +- ✅ Professional appearance + +## 📚 New Documentation Structure + +### Root Level +Files GitHub needs to see: +- `README.md` - Main project page +- `LICENSE` - Open source license +- `CONTRIBUTING.md` - Contributor guide +- `CODE_OF_CONDUCT.md` - Community standards +- `SECURITY.md` - Security policy + +### docs/ Level + +**Navigation:** +- `docs/README.md` - **Start here!** Main documentation hub + +**Categories:** + +1. **`getting-started/`** - Deployment and setup + - Docker deployment (EN/äž­æ–‡) + - PM2 deployment + - Custom API configuration + +2. **`guides/`** - Usage guides and tutorials + - FAQ (äž­æ–‡) + - Troubleshooting (planned) + - Configuration examples (planned) + +3. **`community/`** - Contribution and bounties + - Bounty guide + - Active bounty tasks + - Contributor recognition + +4. **`i18n/`** - International translations + - `zh-CN/` - Simplified Chinese + - `ru/` - Russian + - `uk/` - Ukrainian + +5. **`architecture/`** - Technical documentation + - System design (planned) + - API reference (planned) + - Database schema (planned) + +## 🔗 Updating Your Links + +### If you bookmarked old links: + +| Old Link | New Link | +|----------|----------| +| `DOCKER_DEPLOY.en.md` | `docs/getting-started/docker-deploy.en.md` | +| `README.zh-CN.md` | `docs/i18n/zh-CN/README.md` | +| `HOW_TO_POST_BOUNTY.md` | `docs/community/bounty-guide.md` | + +### If you linked in your own docs: + +**Update relative links:** +```markdown + +[Docker Deployment](DOCKER_DEPLOY.en.md) + + +[Docker Deployment](docs/getting-started/docker-deploy.en.md) +``` + +**GitHub URLs automatically redirect!** +- Old: `github.com/tinkle-community/nofx/blob/main/DOCKER_DEPLOY.en.md` +- Will redirect to: `github.com/.../docs/getting-started/docker-deploy.en.md` + +## 🛠 For Contributors + +### Cloning/Pulling Latest + +```bash +# Pull latest changes +git pull origin dev + +# Your old bookmarks still work! +# Git tracked the file moves (git mv) +``` + +### Finding Documentation + +**Use the navigation hub:** +1. Start at [docs/README.md](README.md) +2. Browse by category +3. Use the quick navigation section + +**Or search:** +```bash +# Find all markdown docs +find docs -name "*.md" + +# Search content +grep -r "keyword" docs/ +``` + +### Adding New Documentation + +**Follow the structure:** + +```bash +# Getting started guides +docs/getting-started/your-guide.md + +# User guides +docs/guides/your-tutorial.md + +# Community docs +docs/community/your-doc.md + +# Translations +docs/i18n/ja/README.md # Japanese example +``` + +**Update navigation:** +- Add link in relevant category README +- Add to `docs/README.md` main hub + +## 📝 Commit Messages + +This reorganization was committed as: + +``` +docs: reorganize documentation into structured docs/ directory + +- Move deployment guides to docs/getting-started/ +- Move community docs to docs/community/ +- Move translations to docs/i18n/ +- Create navigation hub at docs/README.md +- Update all internal links in README.md +- Add GitHub issue/PR templates + +BREAKING CHANGE: Direct links to moved files will need updating +(though GitHub redirects should work) + +Closes #XXX +``` + +## 🆘 Need Help? + +**Can't find a document?** +1. Check [docs/README.md](README.md) navigation hub +2. Search GitHub repo +3. Ask in [Telegram](https://t.me/nofx_dev_community) + +**Link broken?** +- Report in [GitHub Issues](https://github.com/tinkle-community/nofx/issues) +- We'll fix it ASAP! + +**Want to contribute docs?** +- See [Contributing Guide](../CONTRIBUTING.md) +- Check [docs/community/](community/README.md) + +--- + +**Migration Date:** 2025-11-01 +**Maintainers:** Tinkle Community + +[← Back to Documentation Home](README.md) diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 00000000..72ea76b2 --- /dev/null +++ b/docs/README.md @@ -0,0 +1,192 @@ +# 📚 NOFX Documentation Center / 文档䞭心 + +Welcome to the NOFX documentation! This page helps you find the right documentation quickly. + +欢迎来到 NOFX 文档䞭心本页面垮助悚快速扟到所需文档。 + +--- + +## 🚀 Getting Started / 快速匀始 + +**New to NOFX? Start here!** + +| Document | Description | 描述 | +|----------|-------------|------| +| [Main README](../README.md) | Project overview, features, quick start | 项目抂述、功胜、快速入闚 | +| [Getting Started Index (EN)](getting-started/README.md) | All deployment options | 所有郚眲选项 | +| [Getting Started Index (äž­æ–‡)](getting-started/README.zh-CN.md) | 所有郚眲选项 | All deployment options | +| [Docker Deployment (EN)](getting-started/docker-deploy.en.md) | Deploy with Docker (recommended) | Docker 郚眲掚荐 | +| [Docker Deployment (äž­æ–‡)](getting-started/docker-deploy.zh-CN.md) | Docker 郚眲指南䞭文 | Docker deployment guide | +| [PM2 Deployment (EN)](getting-started/pm2-deploy.en.md) | Deploy with PM2 process manager | PM2 进皋管理噚郚眲 | +| [PM2 Deployment (äž­æ–‡)](getting-started/pm2-deploy.md) | PM2 郚眲指南䞭文 | PM2 deployment guide | +| [Custom API (EN)](getting-started/custom-api.en.md) | Connect custom AI API providers | 连接自定义 AI API | +| [Custom API (äž­æ–‡)](getting-started/custom-api.md) | 连接自定义 AI API 提䟛商 | Custom AI provider guide | + +**Quick Links:** +- 📖 See all options → [Getting Started](getting-started/README.md) / [快速匀始](getting-started/README.zh-CN.md) +- 🐳 Want easiest setup? → [Docker (EN)](getting-started/docker-deploy.en.md) / [Docker (äž­æ–‡)](getting-started/docker-deploy.zh-CN.md) +- 🔧 Advanced user? → [PM2 (EN)](getting-started/pm2-deploy.en.md) / [PM2 (äž­æ–‡)](getting-started/pm2-deploy.md) +- 🀖 Custom AI model? → [Custom API (EN)](getting-started/custom-api.en.md) / [自定义 API](getting-started/custom-api.md) + +--- + +## 📘 User Guides / 䜿甚指南 + +**Learn how to use NOFX effectively** + +| Document | Description | 描述 | +|----------|-------------|------| +| [User Guides Index (EN)](guides/README.md) | All usage guides and tips | 所有䜿甚指南和技巧 | +| [User Guides Index (äž­æ–‡)](guides/README.zh-CN.md) | 所有䜿甚指南和技巧 | All usage guides and tips | +| [FAQ (English)](guides/faq.en.md) | Frequently asked questions | 垞见问题解答 | +| [FAQ (äž­æ–‡)](guides/faq.zh-CN.md) | 垞见问题解答 | Frequently asked questions | +| Troubleshooting *(coming soon)* | Common issues and solutions | 故障排查 | +| Configuration Guide *(coming soon)* | Advanced configuration options | 高级配眮选项 | +| Trading Strategies *(coming soon)* | AI trading strategy examples | AI 亀易策略瀺䟋 | + +--- + +## 👥 Community & Contributing / 瀟区䞎莡献 + +**Join the community and contribute!** + +| Document | Description | 描述 | +|----------|-------------|------| +| [Code of Conduct](../CODE_OF_CONDUCT.md) | Community guidelines | 瀟区行䞺准则 | +| [Security Policy](../SECURITY.md) | Report security vulnerabilities | 报告安党挏掞 | +| [Bounty Guide](community/bounty-guide.md) | How to post bounty tasks | 劂䜕发垃悬赏任务 | +| [Hyperliquid Bounty](community/bounty-hyperliquid.md) | Hyperliquid integration bounty | Hyperliquid 集成悬赏 | +| [Aster Bounty](community/bounty-aster.md) | Aster DEX integration bounty | Aster DEX 集成悬赏 | + +**Get Involved:** +- 💬 [Telegram Community](https://t.me/nofx_dev_community) +- 🐊 [Twitter @nofx_ai](https://x.com/nofx_ai) +- 🐛 [Report Issues](https://github.com/tinkle-community/nofx/issues) + +--- + +## 🌍 International / 囜际化文档 + +**Documentation in other languages** + +| Language | Main README | Status | +|----------|-------------|--------| +| 🇚🇳 Chinese (äž­æ–‡) | [README.md](i18n/zh-CN/README.md) | ✅ Complete | +| 🇷🇺 Russian (РусскОй) | [README.md](i18n/ru/README.md) | ✅ Complete | +| 🇺🇊 Ukrainian (УкраїМська) | [README.md](i18n/uk/README.md) | ✅ Complete | +| 🇬🇧 English | [README.md](../README.md) | ✅ Complete | + +--- + +## 🏗 Architecture & Development / 架构䞎匀发 + +**For developers who want to understand the internals** + +| Document | Description | 描述 | +|----------|-------------|------| +| [Architecture Overview (EN)](architecture/README.md) | System architecture, modules, and design | 系统架构、暡块和讟计 | +| [Architecture Overview (äž­æ–‡)](architecture/README.zh-CN.md) | 系统架构、暡块和讟计 | System architecture overview | +| API Reference *(coming soon)* | HTTP API documentation | HTTP API 文档 | +| Database Schema *(coming soon)* | SQLite database structure | SQLite 数据库结构 | +| Testing Guide *(coming soon)* | How to write tests | 劂䜕猖写测试 | + +--- + +## 🗺 Roadmap / 路线囟 + +**NOFX's strategic development plan and market expansion** + +| Document | Description | 描述 | +|----------|-------------|------| +| [Roadmap (EN)](roadmap/README.md) | Short-term and long-term roadmap, feature timeline | 短期和长期路线囟、功胜时闎衚 | +| [Roadmap (äž­æ–‡)](roadmap/README.zh-CN.md) | 短期和长期路线囟、功胜时闎衚 | Strategic development plan | + +**Roadmap Highlights:** +- 📈 **Short-term (Q2-Q3 2025)**: Advanced risk management, multi-AI ensemble, new exchange integrations +- 🚀 **Long-term (2026)**: Universal market expansion (stocks, futures, options, forex), reinforcement learning, enterprise features + +--- + +## 📄 Legal & Policies / 法埋䞎政策 + +| Document | Description | 描述 | +|----------|-------------|------| +| [License (MIT)](../LICENSE) | Open source license | 匀源讞可证 | +| [Changelog (EN)](../CHANGELOG.md) | Version history and updates | 版本历史和曎新 | +| [Changelog (äž­æ–‡)](../CHANGELOG.zh-CN.md) | 版本历史和曎新 | Version history and updates | +| [Security Policy](../SECURITY.md) | Vulnerability disclosure | 挏掞披露政策 | +| [Code of Conduct](../CODE_OF_CONDUCT.md) | Community standards | 瀟区标准 | + +--- + +## 🔍 Quick Navigation / 快速富航 + +**Find what you need fast:** + +### I want to... +- 🚀 **Get started quickly** → [Getting Started](getting-started/README.md) / [快速匀始](getting-started/README.zh-CN.md) +- 🐛 **Report a bug** → [GitHub Issues](https://github.com/tinkle-community/nofx/issues/new) +- 💡 **Suggest a feature** → [Feature Request](https://github.com/tinkle-community/nofx/issues/new?template=feature_request.md) +- 🔒 **Report security issue** → [Security Policy](../SECURITY.md) +- 💰 **Claim a bounty** → [Bounty Guide](community/bounty-guide.md) +- 🀝 **Contribute code** → [Contributing Guide](../CONTRIBUTING.md) +- 💬 **Ask questions** → [Telegram Community](https://t.me/nofx_dev_community) + +### I'm looking for... +- 🏗 **System architecture** → [Architecture (EN)](architecture/README.md) / [架构文档](architecture/README.zh-CN.md) +- 🗺 **Product roadmap** → [Roadmap (EN)](roadmap/README.md) / [路线囟](roadmap/README.zh-CN.md) +- 📊 **API documentation** → Coming soon +- 🧪 **Testing guide** → Coming soon +- 🔧 **Configuration examples** → [Custom API (EN)](getting-started/custom-api.en.md) / [自定义 API](getting-started/custom-api.md) +- 🌐 **Multi-language docs** → [International section](#-international--囜际化文档) + +--- + +## 📚 Documentation Status + +| Category | Status | Last Updated | +|----------|--------|--------------| +| Getting Started | ✅ Complete | 2025-11-01 | +| User Guides | ✅ Complete | 2025-11-01 | +| Community | ✅ Complete | 2025-11-01 | +| Architecture | ✅ Complete | 2025-11-01 | +| Roadmap | ✅ Complete | 2025-11-01 | +| API Reference | 📋 Planned | - | + +**Legend:** +- ✅ Complete - Documentation is ready +- 🚧 In Progress - Being written +- 📋 Planned - On the roadmap +- ⚠ Outdated - Needs update + +--- + +## 🆘 Need Help? + +**Can't find what you're looking for?** + +1. **Search GitHub Issues** - Someone might have asked already +2. **Join Telegram** - [NOFX Developer Community](https://t.me/nofx_dev_community) +3. **Ask on Twitter** - Mention [@nofx_ai](https://x.com/nofx_ai) +4. **Create an Issue** - [New Issue](https://github.com/tinkle-community/nofx/issues/new) + +--- + +## 🀝 Contributing to Documentation + +Found an error or want to improve the docs? + +1. **Small fixes** - Click "Edit" on GitHub and submit PR +2. **New documentation** - Create an issue first to discuss +3. **Translations** - See [Contributing Guide](../CONTRIBUTING.md) + +**Documentation Contributors:** +- All documentation follows [Markdown Guide](https://www.markdownguide.org/) +- Use clear, concise language +- Include code examples where helpful +- Add screenshots for UI-related docs + +--- + +**Last Updated:** 2025-11-01 +**Maintained by:** [Tinkle Community](https://github.com/tinkle-community) diff --git a/docs/architecture/README.md b/docs/architecture/README.md new file mode 100644 index 00000000..2c1a2f6f --- /dev/null +++ b/docs/architecture/README.md @@ -0,0 +1,570 @@ +# 🏗 NOFX Architecture Documentation + +**Language:** [English](README.md) | [äž­æ–‡](README.zh-CN.md) + +Technical documentation for developers who want to understand NOFX internals. + +--- + +## 📋 Overview + +NOFX is a full-stack AI trading platform with: +- **Backend:** Go (Gin framework, SQLite) +- **Frontend:** React/TypeScript (Vite, TailwindCSS) +- **Architecture:** Microservice-inspired modular design + +--- + +## 📁 Project Structure + +``` +nofx/ +├── main.go # Program entry (multi-trader manager) +├── config.json # ~~Multi-trader config~~ (Now via web interface) +├── trading.db # SQLite database (traders, models, exchanges) +│ +├── api/ # HTTP API service +│ └── server.go # Gin framework, RESTful API +│ +├── trader/ # Trading core +│ ├── auto_trader.go # Auto trading main controller +│ ├── interface.go # Unified trader interface +│ ├── binance_futures.go # Binance API wrapper +│ ├── hyperliquid_trader.go # Hyperliquid DEX wrapper +│ └── aster_trader.go # Aster DEX wrapper +│ +├── manager/ # Multi-trader management +│ └── trader_manager.go # Manages multiple trader instances +│ +├── config/ # Configuration & database +│ └── database.go # SQLite operations and schema +│ +├── auth/ # Authentication +│ └── jwt.go # JWT token management & 2FA +│ +├── mcp/ # Model Context Protocol - AI communication +│ └── client.go # AI API client (DeepSeek/Qwen/Custom) +│ +├── decision/ # AI decision engine +│ ├── engine.go # Decision logic with historical feedback +│ └── prompt_manager.go # Prompt template system +│ +├── market/ # Market data fetching +│ └── data.go # Market data & technical indicators (TA-Lib) +│ +├── pool/ # Coin pool management +│ └── coin_pool.go # AI500 + OI Top merged pool +│ +├── logger/ # Logging system +│ └── decision_logger.go # Decision recording + performance analysis +│ +├── decision_logs/ # Decision log storage (JSON files) +│ ├── {trader_id}/ # Per-trader logs +│ └── {timestamp}.json # Individual decisions +│ +└── web/ # React frontend + ├── src/ + │ ├── components/ # React components + │ │ ├── EquityChart.tsx # Equity curve chart + │ │ ├── ComparisonChart.tsx # Multi-AI comparison chart + │ │ └── CompetitionPage.tsx # Competition leaderboard + │ ├── lib/api.ts # API call wrapper + │ ├── types/index.ts # TypeScript types + │ ├── stores/ # Zustand state management + │ ├── index.css # Binance-style CSS + │ └── App.tsx # Main app + ├── package.json # Frontend dependencies + └── vite.config.ts # Vite configuration +``` + +--- + +## 🔧 Core Dependencies + +### Backend (Go) + +| Package | Purpose | Version | +|---------|---------|---------| +| `github.com/gin-gonic/gin` | HTTP API framework | v1.9+ | +| `github.com/adshao/go-binance/v2` | Binance API client | v2.4+ | +| `github.com/markcheno/go-talib` | Technical indicators (TA-Lib) | Latest | +| `github.com/mattn/go-sqlite3` | SQLite database driver | v1.14+ | +| `github.com/golang-jwt/jwt/v5` | JWT authentication | v5.0+ | +| `github.com/pquerna/otp` | 2FA/TOTP support | v1.4+ | +| `golang.org/x/crypto` | Password hashing (bcrypt) | Latest | + +### Frontend (React + TypeScript) + +| Package | Purpose | Version | +|---------|---------|---------| +| `react` + `react-dom` | UI framework | 18.3+ | +| `typescript` | Type safety | 5.8+ | +| `vite` | Build tool | 6.0+ | +| `recharts` | Charts (equity, comparison) | 2.15+ | +| `swr` | Data fetching & caching | 2.2+ | +| `zustand` | State management | 5.0+ | +| `tailwindcss` | CSS framework | 3.4+ | +| `lucide-react` | Icon library | Latest | + +--- + +## 🗂 System Architecture + +### High-Level Overview + +``` +┌──────────────────────────────────────────────────────────────────┐ +│ PRESENTATION LAYER │ +│ React SPA (Vite + TypeScript + TailwindCSS) │ +│ - Competition dashboard, trader management UI │ +│ - Real-time charts (Recharts), authentication pages │ +└──────────────────────────────────────────────────────────────────┘ + ↓ HTTP/JSON API +┌──────────────────────────────────────────────────────────────────┐ +│ API LAYER (Gin Router) │ +│ /api/traders, /api/status, /api/positions, /api/decisions │ +│ Authentication middleware (JWT), CORS handling │ +└──────────────────────────────────────────────────────────────────┘ + ↓ +┌──────────────────────────────────────────────────────────────────┐ +│ BUSINESS LOGIC LAYER │ +│ ┌──────────────────┐ ┌──────────────────┐ ┌────────────────┐ │ +│ │ TraderManager │ │ DecisionEngine │ │ MarketData │ │ +│ │ - Multi-trader │ │ - AI reasoning │ │ - K-lines │ │ +│ │ orchestration │ │ - Risk control │ │ - Indicators │ │ +│ └──────────────────┘ └──────────────────┘ └────────────────┘ │ +└──────────────────────────────────────────────────────────────────┘ + ↓ +┌──────────────────────────────────────────────────────────────────┐ +│ DATA ACCESS LAYER │ +│ ┌──────────────┐ ┌──────────────┐ ┌────────────────────┐ │ +│ │ SQLite DB │ │ File Logger │ │ External APIs │ │ +│ │ - Traders │ │ - Decisions │ │ - Binance │ │ +│ │ - Models │ │ - Performance│ │ - Hyperliquid │ │ +│ │ - Exchanges │ │ analysis │ │ - Aster │ │ +│ └──────────────┘ └──────────────┘ └────────────────────┘ │ +└──────────────────────────────────────────────────────────────────┘ +``` + +### Component Diagram + +*(Coming soon: detailed component interaction diagram)* + +--- + +## 📚 Core Modules + +### 1. Trader System (`trader/`) + +**Purpose:** Trading execution layer with multi-exchange support + +**Key Files:** +- `auto_trader.go` - Main trading orchestrator (100+ lines) +- `interface.go` - Unified trader interface +- `binance_futures.go` - Binance API wrapper +- `hyperliquid_trader.go` - Hyperliquid DEX wrapper +- `aster_trader.go` - Aster DEX wrapper + +**Design Pattern:** Strategy pattern with interface-based abstraction + +**Example:** +```go +type ExchangeClient interface { + GetAccount() (*AccountInfo, error) + GetPositions() ([]*Position, error) + CreateOrder(*OrderParams) (*Order, error) + // ... more methods +} +``` + +--- + +### 2. Decision Engine (`decision/`) + +**Purpose:** AI-powered trading decision making + +**Key Files:** +- `engine.go` - Decision logic with historical feedback +- `prompt_manager.go` - Template system for AI prompts + +**Features:** +- Chain-of-Thought reasoning +- Historical performance analysis +- Risk-aware decision making +- Multi-model support (DeepSeek, Qwen, custom) + +**Flow:** +``` +Historical Data → Prompt Generation → AI API Call → +Decision Parsing → Risk Validation → Execution +``` + +--- + +### 3. Market Data System (`market/`) + +**Purpose:** Fetch and analyze market data + +**Key Files:** +- `data.go` - Market data fetching and technical indicators + +**Features:** +- Multi-timeframe K-line data (3min, 4hour) +- Technical indicators via TA-Lib: + - EMA (20, 50) + - MACD + - RSI (7, 14) + - ATR (volatility) +- Open Interest tracking + +--- + +### 4. Manager (`manager/`) + +**Purpose:** Multi-trader orchestration + +**Key Files:** +- `trader_manager.go` - Manages multiple trader instances + +**Responsibilities:** +- Trader lifecycle (start, stop, restart) +- Resource allocation +- Concurrent execution coordination + +--- + +### 5. API Server (`api/`) + +**Purpose:** HTTP API for frontend communication + +**Key Files:** +- `server.go` - Gin framework RESTful API + +**Endpoints:** +``` +GET /api/traders # List all traders +POST /api/traders # Create trader +POST /api/traders/:id/start # Start trader +GET /api/status # System status +GET /api/positions # Current positions +GET /api/decisions/latest # Recent decisions +``` + +--- + +### 6. Database Layer (`config/`) + +**Purpose:** SQLite data persistence + +**Key Files:** +- `database.go` - Database operations and schema + +**Tables:** +- `users` - User accounts (with 2FA support) +- `ai_models` - AI model configurations +- `exchanges` - Exchange credentials +- `traders` - Trader instances +- `equity_history` - Performance tracking +- `system_config` - Application settings + +--- + +### 7. Authentication (`auth/`) + +**Purpose:** User authentication and authorization + +**Features:** +- JWT token-based auth +- 2FA with TOTP (Google Authenticator) +- Bcrypt password hashing +- Admin mode (simplified single-user) + +--- + +## 🔄 Request Flow Examples + +### Example 1: Create New Trader + +``` +User Action (Frontend) + ↓ +POST /api/traders + ↓ +API Server (auth middleware) + ↓ +Database.CreateTrader() + ↓ +TraderManager.StartTrader() + ↓ +AutoTrader.Run() → goroutine + ↓ +Response: {trader_id, status} +``` + +### Example 2: Trading Decision Cycle + +``` +AutoTrader (every 3-5 min) + ↓ +1. FetchAccountStatus() + ↓ +2. GetOpenPositions() + ↓ +3. FetchMarketData() → TA-Lib indicators + ↓ +4. AnalyzeHistory() → last 20 trades + ↓ +5. GeneratePrompt() → full context + ↓ +6. CallAI() → DeepSeek/Qwen + ↓ +7. ParseDecision() → structured output + ↓ +8. ValidateRisk() → position limits, margin + ↓ +9. ExecuteOrders() → exchange API + ↓ +10. LogDecision() → JSON file + database +``` + +--- + +## 📊 Data Flow + +### Market Data Flow + +``` +Exchange API + ↓ +market.FetchKlines() + ↓ +TA-Lib.Calculate(EMA, MACD, RSI) + ↓ +DecisionEngine (as context) + ↓ +AI Model (reasoning) +``` + +### Decision Logging Flow + +``` +AI Response + ↓ +decision_logger.go + ↓ +JSON file: decision_logs/{trader_id}/{timestamp}.json + ↓ +Database: performance tracking + ↓ +Frontend: /api/decisions/latest +``` + +--- + +## 🗄 Database Schema + +### Core Tables + +**users** +```sql +- id (INTEGER PRIMARY KEY) +- username (TEXT UNIQUE) +- password_hash (TEXT) +- totp_secret (TEXT) +- is_admin (BOOLEAN) +- created_at (DATETIME) +``` + +**ai_models** +```sql +- id (INTEGER PRIMARY KEY) +- name (TEXT) +- model_type (TEXT) -- deepseek, qwen, custom +- api_key (TEXT) +- api_url (TEXT) +- enabled (BOOLEAN) +``` + +**traders** +```sql +- id (TEXT PRIMARY KEY) +- name (TEXT) +- ai_model_id (INTEGER FK) +- exchange_id (INTEGER FK) +- initial_balance (REAL) +- current_equity (REAL) +- status (TEXT) -- running, stopped +- created_at (DATETIME) +``` + +*(More details: database-schema.md - coming soon)* + +--- + +## 🔌 API Reference + +### Authentication + +**POST /api/auth/login** +```json +Request: { + "username": "string", + "password": "string", + "totp_code": "string" // optional +} + +Response: { + "token": "jwt_token", + "user": {...} +} +``` + +### Trader Management + +**GET /api/traders** +```json +Response: { + "traders": [ + { + "id": "string", + "name": "string", + "status": "running|stopped", + "balance": 1000.0, + "roi": 5.2 + } + ] +} +``` + +*(Full API reference: api-reference.md - coming soon)* + +--- + +## 🧪 Testing Architecture + +### Current State +- ⚠ No unit tests yet +- ⚠ Manual testing only +- ⚠ Testnet verification + +### Planned Testing Strategy + +**Unit Tests (Priority 1)** +``` +trader/binance_futures_test.go +- Mock API responses +- Test precision handling +- Validate order construction +``` + +**Integration Tests (Priority 2)** +``` +- End-to-end trading flow (testnet) +- Multi-trader scenarios +- Database operations +``` + +**Frontend Tests (Priority 3)** +``` +- Component tests (Vitest + React Testing Library) +- API integration tests +- E2E tests (Playwright) +``` + +*(Testing guide: testing-guide.md - coming soon)* + +--- + +## 🔧 Development Tools + +### Build & Run + +```bash +# Backend +go build -o nofx +./nofx + +# Frontend +cd web +npm run dev + +# Docker +docker compose up --build +``` + +### Code Quality + +```bash +# Format Go code +go fmt ./... + +# Lint (if configured) +golangci-lint run + +# Type check TypeScript +cd web && npm run build +``` + +--- + +## 📈 Performance Considerations + +### Backend +- **Concurrency:** Each trader runs in separate goroutine +- **Database:** SQLite (good for <100 traders) +- **API Rate Limits:** Handled per exchange +- **Memory:** ~50-100MB per trader + +### Frontend +- **Data Fetching:** SWR with 5-10s polling +- **State:** Zustand (lightweight) +- **Bundle Size:** ~500KB (gzipped) + +--- + +## 🔮 Future Architecture Plans + +### Planned Improvements + +1. **Microservices Split** (if scaling needed) + - Separate decision engine service + - Market data service + - Execution service + +2. **Database Migration** + - Mysql for production (>100 traders) + - Redis for caching + +3. **Event-Driven Architecture** + - WebSocket for real-time updates + - Message queue (RabbitMQ/NATS) + +4. **Kubernetes Deployment** + - Helm charts + - Auto-scaling + - High availability + +--- + +## 🆘 For Developers + +**Want to contribute?** +- Read [Contributing Guide](../../CONTRIBUTING.md) +- Check [Open Issues](https://github.com/tinkle-community/nofx/issues) +- Join [Telegram Community](https://t.me/nofx_dev_community) + +**Need clarification?** +- Open a [GitHub Discussion](https://github.com/tinkle-community/nofx/discussions) +- Ask in Telegram + +--- + +## 📚 Related Documentation + +- [Getting Started](../getting-started/README.md) - Setup and deployment +- [Contributing](../../CONTRIBUTING.md) - How to contribute +- [Community](../community/README.md) - Bounties and recognition + +--- + +[← Back to Documentation Home](../README.md) diff --git a/docs/architecture/README.zh-CN.md b/docs/architecture/README.zh-CN.md new file mode 100644 index 00000000..36732b09 --- /dev/null +++ b/docs/architecture/README.zh-CN.md @@ -0,0 +1,570 @@ +# 🏗 NOFX 架构文档 + +**语蚀:** [English](README.md) | [äž­æ–‡](README.zh-CN.md) + +䞺垌望了解 NOFX 内郚实现的匀发者提䟛的技术文档。 + +--- + +## 📋 抂述 + +NOFX 是䞀䞪党栈 AI 亀易平台 +- **后端** Go (Gin 框架, SQLite) +- **前端** React/TypeScript (Vite, TailwindCSS) +- **架构** 埮服务启发的暡块化讟计 + +--- + +## 📁 项目结构 + +``` +nofx/ +├── main.go # 皋序入口倚亀易员管理噚 +├── config.json # ~~倚亀易员配眮~~ (现通过Web界面) +├── trading.db # SQLite 数据库亀易员、暡型、亀易所 +│ +├── api/ # HTTP API 服务 +│ └── server.go # Gin 框架RESTful API +│ +├── trader/ # 亀易栞心 +│ ├── auto_trader.go # 自劚亀易䞻控制噚 +│ ├── interface.go # 统䞀亀易员接口 +│ ├── binance_futures.go # Binance API 包装噚 +│ ├── hyperliquid_trader.go # Hyperliquid DEX 包装噚 +│ └── aster_trader.go # Aster DEX 包装噚 +│ +├── manager/ # 倚亀易员管理 +│ └── trader_manager.go # 管理倚䞪亀易员实䟋 +│ +├── config/ # 配眮䞎数据库 +│ └── database.go # SQLite 操䜜和暡匏 +│ +├── auth/ # 讀证 +│ └── jwt.go # JWT token 管理 & 2FA +│ +├── mcp/ # Model Context Protocol - AI 通信 +│ └── client.go # AI API 客户端DeepSeek/Qwen/自定义 +│ +├── decision/ # AI 决策匕擎 +│ ├── engine.go # 垊历史反銈的决策逻蟑 +│ └── prompt_manager.go # 提瀺词暡板系统 +│ +├── market/ # 垂场数据获取 +│ └── data.go # 垂场数据䞎技术指标TA-Lib +│ +├── pool/ # 垁种池管理 +│ └── coin_pool.go # AI500 + OI Top 合并池 +│ +├── logger/ # 日志系统 +│ └── decision_logger.go # 决策记圕 + 性胜分析 +│ +├── decision_logs/ # 决策日志存傚JSON 文件 +│ ├── {trader_id}/ # 每䞪亀易员的日志 +│ └── {timestamp}.json # 单䞪决策 +│ +└── web/ # React 前端 + ├── src/ + │ ├── components/ # React 组件 + │ │ ├── EquityChart.tsx # 权益曲线囟衚 + │ │ ├── ComparisonChart.tsx # 倚 AI 对比囟衚 + │ │ └── CompetitionPage.tsx # 竞赛排行抜 + │ ├── lib/api.ts # API 调甚包装噚 + │ ├── types/index.ts # TypeScript 类型 + │ ├── stores/ # Zustand 状态管理 + │ ├── index.css # Binance 风栌样匏 + │ └── App.tsx # 䞻应甚 + ├── package.json # 前端䟝赖 + └── vite.config.ts # Vite 配眮 +``` + +--- + +## 🔧 栞心䟝赖 + +### 后端 (Go) + +| 包 | 甹途 | 版本 | +|---------|---------|---------| +| `github.com/gin-gonic/gin` | HTTP API 框架 | v1.9+ | +| `github.com/adshao/go-binance/v2` | Binance API 客户端 | v2.4+ | +| `github.com/markcheno/go-talib` | 技术指标TA-Lib | 最新 | +| `github.com/mattn/go-sqlite3` | SQLite 数据库驱劚 | v1.14+ | +| `github.com/golang-jwt/jwt/v5` | JWT 讀证 | v5.0+ | +| `github.com/pquerna/otp` | 2FA/TOTP 支持 | v1.4+ | +| `golang.org/x/crypto` | 密码哈垌bcrypt | 最新 | + +### 前端 (React + TypeScript) + +| 包 | 甹途 | 版本 | +|---------|---------|---------| +| `react` + `react-dom` | UI 框架 | 18.3+ | +| `typescript` | 类型安党 | 5.8+ | +| `vite` | 构建工具 | 6.0+ | +| `recharts` | 囟衚权益、对比 | 2.15+ | +| `swr` | 数据获取䞎猓存 | 2.2+ | +| `zustand` | 状态管理 | 5.0+ | +| `tailwindcss` | CSS 框架 | 3.4+ | +| `lucide-react` | 囟标库 | 最新 | + +--- + +## 🗂 系统架构 + +### 高层架构抂览 + +``` +┌──────────────────────────────────────────────────────────────────┐ +│ 衚现层 │ +│ React SPA (Vite + TypeScript + TailwindCSS) │ +│ - 竞赛仪衚板、亀易员管理 UI │ +│ - 实时囟衚 (Recharts)、讀证页面 │ +└──────────────────────────────────────────────────────────────────┘ + ↓ HTTP/JSON API +┌──────────────────────────────────────────────────────────────────┐ +│ API 层 (Gin Router) │ +│ /api/traders, /api/status, /api/positions, /api/decisions │ +│ 讀证䞭闎件 (JWT)、CORS 倄理 │ +└──────────────────────────────────────────────────────────────────┘ + ↓ +┌──────────────────────────────────────────────────────────────────┐ +│ 䞚务逻蟑层 │ +│ ┌──────────────────┐ ┌──────────────────┐ ┌────────────────┐ │ +│ │ TraderManager │ │ DecisionEngine │ │ MarketData │ │ +│ │ - 倚亀易员 │ │ - AI 掚理 │ │ - K线数据 │ │ +│ │ 猖排 │ │ - 风险控制 │ │ - 技术指标 │ │ +│ └──────────────────┘ └──────────────────┘ └────────────────┘ │ +└──────────────────────────────────────────────────────────────────┘ + ↓ +┌──────────────────────────────────────────────────────────────────┐ +│ 数据访问层 │ +│ ┌──────────────┐ ┌──────────────┐ ┌────────────────────┐ │ +│ │ SQLite DB │ │ 文件日志 │ │ 倖郚 APIs │ │ +│ │ - Traders │ │ - Decisions │ │ - Binance │ │ +│ │ - Models │ │ - Performance│ │ - Hyperliquid │ │ +│ │ - Exchanges │ │ analysis │ │ - Aster │ │ +│ └──────────────┘ └──────────────┘ └────────────────────┘ │ +└──────────────────────────────────────────────────────────────────┘ +``` + +### 组件囟 + +*即将掚出诊细的组件亀互囟* + +--- + +## 📚 栞心暡块 + +### 1. 亀易系统 (`trader/`) + +**甚途** 支持倚亀易所的亀易执行层 + +**关键文件** +- `auto_trader.go` - 䞻亀易猖排噚100+ 行 +- `interface.go` - 统䞀的亀易员接口 +- `binance_futures.go` - Binance API 包装噚 +- `hyperliquid_trader.go` - Hyperliquid DEX 包装噚 +- `aster_trader.go` - Aster DEX 包装噚 + +**讟计暡匏** 基于接口抜象的策略暡匏 + +**瀺䟋** +```go +type ExchangeClient interface { + GetAccount() (*AccountInfo, error) + GetPositions() ([]*Position, error) + CreateOrder(*OrderParams) (*Order, error) + // ... 曎倚方法 +} +``` + +--- + +### 2. 决策匕擎 (`decision/`) + +**甚途** AI 驱劚的亀易决策制定 + +**关键文件** +- `engine.go` - 垊历史反銈的决策逻蟑 +- `prompt_manager.go` - AI 提瀺词暡板系统 + +**特性** +- 思绎铟掚理 +- 历史衚现分析 +- 风险感知决策 +- 倚暡型支持DeepSeek、Qwen、自定义 + +**流皋** +``` +历史数据 → 提瀺词生成 → AI API 调甚 → +决策解析 → 风险验证 → 执行 +``` + +--- + +### 3. 垂场数据系统 (`market/`) + +**甚途** 获取和分析垂场数据 + +**关键文件** +- `data.go` - 垂场数据获取和技术指标 + +**特性** +- 倚时闎呚期 K线数据3分钟、4小时 +- 通过 TA-Lib 计算技术指标 + - EMA (20, 50) + - MACD + - RSI (7, 14) + - ATR波劚率 +- 持仓量跟螪 + +--- + +### 4. 管理噚 (`manager/`) + +**甚途** 倚亀易员猖排 + +**关键文件** +- `trader_manager.go` - 管理倚䞪亀易员实䟋 + +**职莣** +- 亀易员生呜呚期启劚、停止、重启 +- 资源分配 +- 并发执行协调 + +--- + +### 5. API 服务噚 (`api/`) + +**甚途** 前端通信的 HTTP API + +**关键文件** +- `server.go` - Gin 框架 RESTful API + +**端点** +``` +GET /api/traders # 列出所有亀易员 +POST /api/traders # 创建亀易员 +POST /api/traders/:id/start # 启劚亀易员 +GET /api/status # 系统状态 +GET /api/positions # 圓前持仓 +GET /api/decisions/latest # 最近决策 +``` + +--- + +### 6. 数据库层 (`config/`) + +**甚途** SQLite 数据持久化 + +**关键文件** +- `database.go` - 数据库操䜜和暡匏 + +**衚** +- `users` - 甚户莊户支持 2FA +- `ai_models` - AI 暡型配眮 +- `exchanges` - 亀易所凭证 +- `traders` - 亀易员实䟋 +- `equity_history` - 绩效跟螪 +- `system_config` - 应甚皋序讟眮 + +--- + +### 7. 讀证 (`auth/`) + +**甚途** 甚户讀证和授权 + +**特性** +- 基于 JWT token 的讀证 +- 䜿甚 TOTP 的 2FAGoogle Authenticator +- Bcrypt 密码哈垌 +- 管理员暡匏简化的单甚户暡匏 + +--- + +## 🔄 请求流皋瀺䟋 + +### 瀺䟋 1创建新亀易员 + +``` +甚户操䜜前端 + ↓ +POST /api/traders + ↓ +API 服务噚讀证䞭闎件 + ↓ +Database.CreateTrader() + ↓ +TraderManager.StartTrader() + ↓ +AutoTrader.Run() → goroutine + ↓ +响应: {trader_id, status} +``` + +### 瀺䟋 2亀易决策呚期 + +``` +AutoTrader每 3-5 分钟 + ↓ +1. FetchAccountStatus() + ↓ +2. GetOpenPositions() + ↓ +3. FetchMarketData() → TA-Lib 指标 + ↓ +4. AnalyzeHistory() → 最近 20 笔亀易 + ↓ +5. GeneratePrompt() → 完敎䞊䞋文 + ↓ +6. CallAI() → DeepSeek/Qwen + ↓ +7. ParseDecision() → 结构化蟓出 + ↓ +8. ValidateRisk() → 仓䜍限制、保证金 + ↓ +9. ExecuteOrders() → 亀易所 API + ↓ +10. LogDecision() → JSON 文件 + 数据库 +``` + +--- + +## 📊 数据流 + +### 垂场数据流 + +``` +亀易所 API + ↓ +market.FetchKlines() + ↓ +TA-Lib.Calculate(EMA, MACD, RSI) + ↓ +DecisionEngine䜜䞺䞊䞋文 + ↓ +AI 暡型掚理 +``` + +### 决策日志流 + +``` +AI 响应 + ↓ +decision_logger.go + ↓ +JSON 文件: decision_logs/{trader_id}/{timestamp}.json + ↓ +数据库: 绩效跟螪 + ↓ +前端: /api/decisions/latest +``` + +--- + +## 🗄 数据库架构 + +### 栞心衚 + +**users** +```sql +- id (INTEGER PRIMARY KEY) +- username (TEXT UNIQUE) +- password_hash (TEXT) +- totp_secret (TEXT) +- is_admin (BOOLEAN) +- created_at (DATETIME) +``` + +**ai_models** +```sql +- id (INTEGER PRIMARY KEY) +- name (TEXT) +- model_type (TEXT) -- deepseek, qwen, custom +- api_key (TEXT) +- api_url (TEXT) +- enabled (BOOLEAN) +``` + +**traders** +```sql +- id (TEXT PRIMARY KEY) +- name (TEXT) +- ai_model_id (INTEGER FK) +- exchange_id (INTEGER FK) +- initial_balance (REAL) +- current_equity (REAL) +- status (TEXT) -- running, stopped +- created_at (DATETIME) +``` + +*曎倚诊情database-schema.md - 即将掚出* + +--- + +## 🔌 API 参考 + +### 讀证 + +**POST /api/auth/login** +```json +请求: { + "username": "string", + "password": "string", + "totp_code": "string" // 可选 +} + +响应: { + "token": "jwt_token", + "user": {...} +} +``` + +### 亀易员管理 + +**GET /api/traders** +```json +响应: { + "traders": [ + { + "id": "string", + "name": "string", + "status": "running|stopped", + "balance": 1000.0, + "roi": 5.2 + } + ] +} +``` + +*完敎 API 参考api-reference.md - 即将掚出* + +--- + +## 🧪 测试架构 + +### 圓前状态 +- ⚠ 尚无单元测试 +- ⚠ 仅手劚测试 +- ⚠ 测试眑验证 + +### 计划的测试策略 + +**单元测试䌘先级 1** +``` +trader/binance_futures_test.go +- 暡拟 API 响应 +- 测试粟床倄理 +- 验证订单构造 +``` + +**集成测试䌘先级 2** +``` +- 端到端亀易流皋测试眑 +- 倚亀易员场景 +- 数据库操䜜 +``` + +**前端测试䌘先级 3** +``` +- 组件测试Vitest + React Testing Library +- API 集成测试 +- E2E 测试Playwright +``` + +*测试指南testing-guide.md - 即将掚出* + +--- + +## 🔧 匀发工具 + +### 构建䞎运行 + +```bash +# 后端 +go build -o nofx +./nofx + +# 前端 +cd web +npm run dev + +# Docker +docker compose up --build +``` + +### 代码莚量 + +```bash +# 栌匏化 Go 代码 +go fmt ./... + +# Lint劂果配眮 +golangci-lint run + +# TypeScript 类型检查 +cd web && npm run build +``` + +--- + +## 📈 性胜考虑 + +### 后端 +- **并发** 每䞪亀易员圚独立的 goroutine 䞭运行 +- **数据库** SQLite适甚于 <100 䞪亀易员 +- **API 速率限制** 按亀易所倄理 +- **内存** 每䞪亀易员 ~50-100MB + +### 前端 +- **数据获取** SWR5-10 秒蜮询 +- **状态** Zustand蜻量级 +- **包倧小** ~500KBgzipped + +--- + +## 🔮 未来架构计划 + +### 计划改进 + +1. **埮服务拆分**劂需扩展 + - 独立的决策匕擎服务 + - 垂场数据服务 + - 执行服务 + +2. **数据库迁移** + - 生产环境䜿甚 Mysql (>100 䞪亀易员 + - Redis 猓存 + +3. **事件驱劚架构** + - WebSocket 实时曎新 + - 消息队列RabbitMQ/NATS + +4. **Kubernetes 郚眲** + - Helm charts + - 自劚扩展 + - 高可甚性 + +--- + +## 🆘 匀发者资源 + +**想芁莡献** +- 阅读[莡献指南](../../CONTRIBUTING.md) +- 查看[匀攟问题](https://github.com/tinkle-community/nofx/issues) +- 加入 [Telegram 瀟区](https://t.me/nofx_dev_community) + +**需芁柄枅** +- 匀启 [GitHub 讚论](https://github.com/tinkle-community/nofx/discussions) +- 圚 Telegram 提问 + +--- + +## 📚 盞关文档 + +- [快速匀始](../getting-started/README.zh-CN.md) - 讟眮和郚眲 +- [莡献指南](../../CONTRIBUTING.md) - 劂䜕莡献 +- [瀟区](../community/README.md) - 悬赏和讀可 + +--- + +[← 返回文档銖页](../README.md) diff --git a/docs/community/README.md b/docs/community/README.md new file mode 100644 index 00000000..497e10c5 --- /dev/null +++ b/docs/community/README.md @@ -0,0 +1,233 @@ +# 👥 NOFX Community + +Welcome to the NOFX community! This section contains everything you need to contribute and participate. + +--- + +## 🀝 How to Contribute + +### Getting Started + +1. **Read the Guides** + - [Contributing Guide](../../CONTRIBUTING.md) - Complete contribution workflow + - [Code of Conduct](../../CODE_OF_CONDUCT.md) - Community standards + - [Security Policy](../../SECURITY.md) - Report vulnerabilities + +2. **Find Something to Work On** + - Browse [GitHub Issues](https://github.com/tinkle-community/nofx/issues) + - Look for `good first issue` label + - Check out [bounty tasks](#-bounty-program) + +3. **Join the Community** + - 💬 [Telegram Developer Community](https://t.me/nofx_dev_community) + - 🐊 [Twitter @nofx_ai](https://x.com/nofx_ai) + - 🐙 [GitHub Discussions](https://github.com/tinkle-community/nofx/discussions) + +--- + +## 💰 Bounty Program + +### Active Bounties + +NOFX offers bounties for valuable contributions: + +| Category | Reward Range | Examples | +|----------|--------------|----------| +| 🥇 Major Features | $500-1000 | Exchange integration, core architecture | +| 🥈 Medium Features | $200-500 | WebSocket support, new AI models | +| 🥉 Small Features | $50-200 | Bug fixes, UI improvements, documentation | + +### How to Claim Bounties + +**📖 Complete Guide:** [bounty-guide.md](bounty-guide.md) + +**Quick Steps:** +1. Find issue tagged `[BOUNTY]` +2. Comment with your proposal +3. Wait for approval +4. Work on the task +5. Submit PR with demo +6. Get paid after merge! + +### Current Bounty Tasks + +| Task | Reward | Difficulty | Status | +|------|--------|------------|--------| +| [Hyperliquid Integration](bounty-hyperliquid.md) | TBD | Hard | 🟡 Open | +| [Aster DEX Integration](bounty-aster.md) | TBD | Medium | ✅ Completed | + +--- + +## 🏆 Recognition + +### Ways to Get Recognized + +**Contributor Levels:** +- 🌟 **Active Contributor** - Submit quality PRs +- ⭐ **Trusted Contributor** - 3+ merged PRs, given review rights +- 💎 **Core Team** - Top contributors, invited by maintainers + +**Benefits:** +- Listed in README and release notes +- Direct access to maintainer discussions +- Priority support for your issues +- Invitation to private roadmap planning + +### Hall of Fame + +**Top Contributors:** +- Coming soon! Be the first! 🚀 + +--- + +## 📋 Contribution Types + +### Code Contributions +- New exchange integrations +- AI model adapters +- Bug fixes and improvements +- Performance optimizations + +**Required:** +- ✅ Code compiles and runs +- ✅ Follows code style guidelines +- ✅ Includes basic tests (preferred) +- ✅ Updates documentation if needed + +### Documentation +- Tutorial writing +- Translation (äž­æ–‡, РусскОй, УкраїМська) +- FAQ updates +- Video guides + +**Rewards:** +- $50-200 for comprehensive guides +- Recognition in docs +- Contributor badge + +### Testing & QA +- Bug reports with reproduction steps +- Security vulnerability reports (see [Security Policy](../../SECURITY.md)) +- Testnet verification +- Performance testing + +**Rewards:** +- $50-500 for critical bug finds +- Up to $1000 for security vulnerabilities +- Recognition in security hall of fame + +--- + +## 🌍 Community Channels + +### Primary Channels + +| Platform | Purpose | Link | +|----------|---------|------| +| 💬 Telegram | Real-time chat, questions | [Join](https://t.me/nofx_dev_community) | +| 🐙 GitHub | Issues, PRs, discussions | [Visit](https://github.com/tinkle-community/nofx) | +| 🐊 Twitter | Announcements, updates | [@nofx_ai](https://x.com/nofx_ai) | + +### Core Team + +- **Tinkle** - [@Web3Tinkle](https://x.com/Web3Tinkle) +- **Zack** - [@0x_ZackH](https://x.com/0x_ZackH) + +**Contact:** +- Technical questions → Telegram or GitHub Issues +- Business inquiries → Twitter DM to core team +- Security reports → [SECURITY.md](../../SECURITY.md) + +--- + +## 📅 Community Events + +### Regular Activities +- **Weekly Updates** - Development progress (Telegram) +- **Monthly AMA** - Ask maintainers anything +- **Quarterly Roadmap** - Future plans discussion + +### Upcoming Events +- *No scheduled events yet* + +**Want to organize an event?** +- Contact core team on Telegram +- Propose in GitHub Discussions +- Tweet and tag @nofx_ai + +--- + +## 🎓 Learning Resources + +### For Contributors + +**Understanding NOFX:** +- [System Architecture](../architecture/README.md) *(coming soon)* +- [API Reference](../architecture/api-reference.md) *(coming soon)* +- [Database Schema](../architecture/database-schema.md) *(coming soon)* + +**Learning Materials:** +- Go programming: [Tour of Go](https://go.dev/tour/) +- React/TypeScript: [React Docs](https://react.dev/) +- Trading basics: [Binance Academy](https://academy.binance.com/) + +### Recommended Reading + +1. **Before Contributing:** + - [Contributing Guide](../../CONTRIBUTING.md) + - [Code of Conduct](../../CODE_OF_CONDUCT.md) + +2. **For Exchange Integration:** + - [Hyperliquid Bounty](bounty-hyperliquid.md) + - [Aster Bounty](bounty-aster.md) + - Existing code: `trader/binance_futures.go` + +3. **For AI Features:** + - [Custom API Guide](../getting-started/custom-api.md) + - MCP client code: `mcp/client.go` + - Decision engine: `decision/engine.go` + +--- + +## 🛡 Community Guidelines + +### Our Values +- **Respect** - Treat everyone with courtesy +- **Transparency** - Open communication and decisions +- **Quality** - High standards for contributions +- **Collaboration** - Work together, help each other + +### Not Acceptable +- ❌ Harassment or discrimination +- ❌ Spam or self-promotion +- ❌ Sharing malicious code +- ❌ Violating [Code of Conduct](../../CODE_OF_CONDUCT.md) + +**Violations will result in:** +1. Warning +2. Temporary ban +3. Permanent ban (serious cases) + +--- + +## 📊 Community Stats + +| Metric | Count | +|--------|-------| +| GitHub Stars | Check [repo](https://github.com/tinkle-community/nofx) | +| Contributors | 21+ | +| Open Issues | Check [issues](https://github.com/tinkle-community/nofx/issues) | +| Merged PRs | Check [pulls](https://github.com/tinkle-community/nofx/pulls?q=is%3Apr+is%3Amerged) | + +--- + +## 🚀 Quick Links + +- **Want to contribute code?** → [Contributing Guide](../../CONTRIBUTING.md) +- **Want to claim bounty?** → [Bounty Guide](bounty-guide.md) +- **Found a security issue?** → [Security Policy](../../SECURITY.md) +- **Have questions?** → [Telegram Community](https://t.me/nofx_dev_community) + +--- + +[← Back to Documentation Home](../README.md) diff --git a/INTEGRATION_BOUNTY_ASTER.md b/docs/community/bounty-aster.md similarity index 100% rename from INTEGRATION_BOUNTY_ASTER.md rename to docs/community/bounty-aster.md diff --git a/HOW_TO_POST_BOUNTY.md b/docs/community/bounty-guide.md similarity index 100% rename from HOW_TO_POST_BOUNTY.md rename to docs/community/bounty-guide.md diff --git a/INTEGRATION_BOUNTY_HYPERLIQUID.md b/docs/community/bounty-hyperliquid.md similarity index 100% rename from INTEGRATION_BOUNTY_HYPERLIQUID.md rename to docs/community/bounty-hyperliquid.md diff --git a/docs/getting-started/README.md b/docs/getting-started/README.md new file mode 100644 index 00000000..c35926f9 --- /dev/null +++ b/docs/getting-started/README.md @@ -0,0 +1,127 @@ +# 🚀 Getting Started with NOFX + +**Language:** [English](README.md) | [äž­æ–‡](README.zh-CN.md) + +This section contains all the documentation you need to get NOFX up and running. + +## 📋 Deployment Options + +Choose the method that best fits your needs: + +### 🐳 Docker Deployment (Recommended) + +**Best for:** Beginners, quick setup, production deployments + +- **English:** [docker-deploy.en.md](docker-deploy.en.md) +- **äž­æ–‡:** [docker-deploy.zh-CN.md](docker-deploy.zh-CN.md) + +**Pros:** +- ✅ One-command setup +- ✅ All dependencies included +- ✅ Easy to update and manage +- ✅ Isolated environment + +**Quick Start:** +```bash +cp config.example.jsonc config.json +./start.sh start --build +``` + +--- + +### 🔧 PM2 Deployment + +**Best for:** Advanced users, development, custom setups + +- **English:** [pm2-deploy.en.md](pm2-deploy.en.md) +- **äž­æ–‡:** [pm2-deploy.md](pm2-deploy.md) + +**Pros:** +- ✅ Direct process control +- ✅ Better for development +- ✅ Lower resource usage +- ✅ More flexible + +**Quick Start:** +```bash +go build -o nofx +cd web && npm install && npm run build +pm2 start ecosystem.config.js +``` + +--- + +## 🀖 AI Configuration + +### Custom AI Providers + +- **English:** [custom-api.en.md](custom-api.en.md) +- **äž­æ–‡:** [custom-api.md](custom-api.md) + +Use custom AI models or third-party OpenAI-compatible APIs: +- Custom DeepSeek endpoints +- Self-hosted models +- Other LLM providers + +--- + +## 🔑 Prerequisites + +Before starting, ensure you have: + +### For Docker Method: +- ✅ Docker 20.10+ +- ✅ Docker Compose V2 + +### For Manual Method: +- ✅ Go 1.21+ +- ✅ Node.js 18+ +- ✅ TA-Lib library +- ✅ PM2 (optional) + +--- + +## 📚 Next Steps + +After deployment: + +1. **Configure AI Models** → Web interface at http://localhost:3000 +2. **Set Up Exchange** → Add Binance/Hyperliquid credentials +3. **Create Traders** → Combine AI models with exchanges +4. **Start Trading** → Monitor performance in dashboard + +--- + +## ⚠ Important Notes + +**Before Trading:** +- ⚠ Test on testnet first +- ⚠ Start with small amounts +- ⚠ Understand the risks +- ⚠ Read [Security Policy](../../SECURITY.md) + +**API Keys:** +- 🔑 Never commit API keys to git +- 🔑 Use environment variables +- 🔑 Restrict IP access +- 🔑 Enable 2FA on exchanges + +--- + +## 🆘 Troubleshooting + +**Common Issues:** + +1. **Docker build fails** → Check Docker version, update to 20.10+ +2. **TA-Lib not found** → `brew install ta-lib` (macOS) or `apt-get install libta-lib0-dev` (Ubuntu) +3. **Port 8080 in use** → Change `API_PORT` in .env file +4. **Frontend won't connect** → Check backend is running on port 8080 + +**Need more help?** +- 📖 [FAQ](../guides/faq.zh-CN.md) +- 💬 [Telegram Community](https://t.me/nofx_dev_community) +- 🐛 [GitHub Issues](https://github.com/tinkle-community/nofx/issues) + +--- + +[← Back to Documentation Home](../README.md) diff --git a/docs/getting-started/README.zh-CN.md b/docs/getting-started/README.zh-CN.md new file mode 100644 index 00000000..aafe5cfb --- /dev/null +++ b/docs/getting-started/README.zh-CN.md @@ -0,0 +1,125 @@ +# 🚀 NOFX 快速匀始 + +本节包含让 NOFX 运行起来所需的所有文档。 + +## 📋 郚眲选项 + +选择最适合悚的方匏 + +### 🐳 Docker 郚眲掚荐 + +**适合** 初孊者、快速郚眲、生产环境 + +- **䞭文文档** [docker-deploy.zh-CN.md](docker-deploy.zh-CN.md) +- **English:** [docker-deploy.en.md](docker-deploy.en.md) + +**䌘势** +- ✅ 䞀键启劚 +- ✅ 包含所有䟝赖 +- ✅ 易于曎新和管理 +- ✅ 隔犻环境 + +**快速匀始** +```bash +cp config.example.jsonc config.json +./start.sh start --build +``` + +--- + +### 🔧 PM2 郚眲 + +**适合** 进阶甚户、匀发环境、自定义讟眮 + +- **䞭文文档** [pm2-deploy.md](pm2-deploy.md) +- **English:** [pm2-deploy.en.md](pm2-deploy.en.md) + +**䌘势** +- ✅ 盎接进皋控制 +- ✅ 曎适合匀发 +- ✅ 资源占甚曎䜎 +- ✅ 曎灵掻 + +**快速匀始** +```bash +go build -o nofx +cd web && npm install && npm run build +pm2 start ecosystem.config.js +``` + +--- + +## 🀖 AI 配眮 + +### 自定义 AI 提䟛商 + +- **䞭文文档** [custom-api.md](custom-api.md) +- **English:** [custom-api.en.md](custom-api.en.md) + +䜿甚自定义 AI 暡型或第䞉方 OpenAI 兌容 API +- 自定义 DeepSeek 端点 +- 本地郚眲的暡型 +- 其他 LLM 提䟛商 + +--- + +## 🔑 环境芁求 + +匀始之前请确保已安装 + +### Docker 方匏 +- ✅ Docker 20.10+ +- ✅ Docker Compose V2 + +### 手劚郚眲方匏 +- ✅ Go 1.21+ +- ✅ Node.js 18+ +- ✅ TA-Lib 库 +- ✅ PM2可选 + +--- + +## 📚 䞋䞀步 + +郚眲完成后 + +1. **配眮 AI 暡型** → 访问 Web 界面 http://localhost:3000 +2. **讟眮亀易所** → 添加 Binance/Hyperliquid 凭证 +3. **创建亀易员** → 将 AI 暡型䞎亀易所结合 +4. **匀始亀易** → 圚仪衚板䞭监控衚现 + +--- + +## ⚠ 重芁提瀺 + +**亀易前** +- ⚠ 先圚测试眑测试 +- ⚠ 从小金额匀始 +- ⚠ 了解风险 +- ⚠ 阅读[安党策略](../../SECURITY.md) + +**API 密钥** +- 🔑 氞远䞍芁提亀 API 密钥到 git +- 🔑 䜿甚环境变量 +- 🔑 限制 IP 访问 +- 🔑 圚亀易所启甚 2FA + +--- + +## 🆘 故障排陀 + +**垞见问题** + +1. **Docker 构建倱莥** → 检查 Docker 版本曎新到 20.10+ +2. **扟䞍到 TA-Lib** → `brew install ta-lib` (macOS) 或 `apt-get install libta-lib0-dev` (Ubuntu) +3. **端口 8080 被占甚** → 圚 .env 文件䞭曎改 `API_PORT` +4. **前端无法连接** → 检查后端是吊圚端口 8080 䞊运行 + +**需芁曎倚垮助** +- 📖 [垞见问题](../guides/faq.zh-CN.md) +- 💬 [Telegram 瀟区](https://t.me/nofx_dev_community) +- 🐛 [GitHub Issues](https://github.com/tinkle-community/nofx/issues) + +--- + +[← 返回文档銖页](../README.md) diff --git a/docs/getting-started/custom-api.en.md b/docs/getting-started/custom-api.en.md new file mode 100644 index 00000000..44c8a05c --- /dev/null +++ b/docs/getting-started/custom-api.en.md @@ -0,0 +1,207 @@ +# Custom AI API Usage Guide + +## Features + +NOFX now supports using any OpenAI-compatible API format, including: +- OpenAI official API (gpt-4o, gpt-4-turbo, etc.) +- OpenRouter (access to multiple models) +- Locally deployed models (Ollama, LM Studio, etc.) +- Other OpenAI-compatible API services + +## Configuration Method + +~~Add trader using custom API in `config.json` (deprecated):~~ + +*Note: Custom APIs and traders are now configured through the Web interface. config.json only retains basic settings.* + +```json +{ + "traders": [ + { + "id": "trader_custom", + "name": "My Custom AI Trader", + "ai_model": "custom", + "exchange": "binance", + + "binance_api_key": "your_binance_api_key", + "binance_secret_key": "your_binance_secret_key", + + "custom_api_url": "https://api.openai.com/v1", + "custom_api_key": "sk-your-openai-api-key", + "custom_model_name": "gpt-4o", + + "initial_balance": 1000, + "scan_interval_minutes": 3 + } + ] +} +``` + +## Configuration Fields + +| Field | Type | Required | Description | +|-------|------|----------|-------------| +| `ai_model` | string | ✅ | Set to `"custom"` to enable custom API | +| `custom_api_url` | string | ✅ | API Base URL (without `/chat/completions`). Special usage: If ending with `#`, use full URL (no auto path append) | +| `custom_api_key` | string | ✅ | API key | +| `custom_model_name` | string | ✅ | Model name (e.g. `gpt-4o`, `claude-3-5-sonnet`, etc.) | + +## Usage Examples + +### 1. OpenAI Official API + +```json +{ + "ai_model": "custom", + "custom_api_url": "https://api.openai.com/v1", + "custom_api_key": "sk-proj-xxxxx", + "custom_model_name": "gpt-4o" +} +``` + +### 2. OpenRouter + +```json +{ + "ai_model": "custom", + "custom_api_url": "https://openrouter.ai/api/v1", + "custom_api_key": "sk-or-xxxxx", + "custom_model_name": "anthropic/claude-3.5-sonnet" +} +``` + +### 3. Local Ollama + +```json +{ + "ai_model": "custom", + "custom_api_url": "http://localhost:11434/v1", + "custom_api_key": "ollama", + "custom_model_name": "llama3.1:70b" +} +``` + +### 4. Azure OpenAI + +```json +{ + "ai_model": "custom", + "custom_api_url": "https://your-resource.openai.azure.com/openai/deployments/your-deployment", + "custom_api_key": "your-azure-api-key", + "custom_model_name": "gpt-4" +} +``` + +### 5. Using Full Custom Path (append #) + +For certain special API endpoints that already include the full path (including `/chat/completions` or other custom paths), you can append `#` at the end of the URL to force using the full URL: + +```json +{ + "ai_model": "custom", + "custom_api_url": "https://api.example.com/v2/ai/chat/completions#", + "custom_api_key": "your-api-key", + "custom_model_name": "custom-model" +} +``` + +**Note**: The `#` will be automatically removed, and the actual request will be sent to `https://api.example.com/v2/ai/chat/completions` + +## Compatibility Requirements + +Custom APIs must: +1. Support OpenAI Chat Completions format +2. Accept `POST` requests to `/chat/completions` endpoint (or append `#` at URL end for custom path) +3. Support `Authorization: Bearer {api_key}` authentication +4. Return standard OpenAI response format + +## Important Notes + +1. **URL Format**: `custom_api_url` should be the Base URL, system will auto-append `/chat/completions` + - ✅ Correct: `https://api.openai.com/v1` + - ❌ Wrong: `https://api.openai.com/v1/chat/completions` + - 🔧 **Special usage**: If you need to use a full custom path (without auto-appending `/chat/completions`), append `#` at the URL end + - Example: `https://api.example.com/custom/path/chat/completions#` + - System will automatically remove `#` and use the full URL directly + +2. **Model Name**: Ensure `custom_model_name` exactly matches the model name supported by your API provider + +3. **API Key**: Some locally deployed models may not require a real API key, you can fill in any string + +4. **Timeout Settings**: Default timeout is 120 seconds, may need adjustment if model response is slow + +## Multi-AI Comparison Trading + +You can configure multiple traders with different AIs for comparison: + +```json +{ + "traders": [ + { + "id": "deepseek_trader", + "ai_model": "deepseek", + "deepseek_key": "sk-xxxxx", + ... + }, + { + "id": "gpt4_trader", + "ai_model": "custom", + "custom_api_url": "https://api.openai.com/v1", + "custom_api_key": "sk-xxxxx", + "custom_model_name": "gpt-4o", + ... + }, + { + "id": "claude_trader", + "ai_model": "custom", + "custom_api_url": "https://openrouter.ai/api/v1", + "custom_api_key": "sk-or-xxxxx", + "custom_model_name": "anthropic/claude-3.5-sonnet", + ... + } + ] +} +``` + +## Troubleshooting + +### Issue: Configuration Validation Failed + +**Error Message**: `䜿甚自定义API时必须配眮custom_api_url` (custom_api_url must be configured when using custom API) + +**Solution**: After setting `ai_model: "custom"`, ensure you also configure: +- `custom_api_url` +- `custom_api_key` +- `custom_model_name` + +### Issue: API Call Failed + +**Possible Causes**: +1. URL format error + - Normal usage: Should not include `/chat/completions` (system will auto-append) + - Special usage: If full path is needed, remember to append `#` at URL end +2. Invalid API key +3. Incorrect model name +4. Network connection issues + +**Debug Method**: Check error messages in logs, usually includes HTTP status code and error details + +## Backward Compatibility + +Existing `deepseek` and `qwen` configurations are unaffected and can continue to be used: + +```json +{ + "ai_model": "deepseek", + "deepseek_key": "sk-xxxxx" +} +``` + +Or + +```json +{ + "ai_model": "qwen", + "qwen_key": "sk-xxxxx" +} +``` diff --git a/CUSTOM_API.md b/docs/getting-started/custom-api.md similarity index 100% rename from CUSTOM_API.md rename to docs/getting-started/custom-api.md diff --git a/DOCKER_DEPLOY.en.md b/docs/getting-started/docker-deploy.en.md similarity index 100% rename from DOCKER_DEPLOY.en.md rename to docs/getting-started/docker-deploy.en.md diff --git a/DOCKER_DEPLOY.md b/docs/getting-started/docker-deploy.zh-CN.md similarity index 100% rename from DOCKER_DEPLOY.md rename to docs/getting-started/docker-deploy.zh-CN.md diff --git a/docs/getting-started/pm2-deploy.en.md b/docs/getting-started/pm2-deploy.en.md new file mode 100644 index 00000000..428bef88 --- /dev/null +++ b/docs/getting-started/pm2-deploy.en.md @@ -0,0 +1,303 @@ +# NoFX Trading Bot - PM2 Deployment Guide + +Complete guide for local development and production deployment using PM2. + +## 🚀 Quick Start + +### 1. Install PM2 + +```bash +npm install -g pm2 +``` + +### 2. One-Command Launch + +```bash +./pm2.sh start +``` + +That's it! Frontend and backend will start automatically. + +--- + +## 📋 All Commands + +### Service Management + +```bash +# Start services +./pm2.sh start + +# Stop services +./pm2.sh stop + +# Restart services +./pm2.sh restart + +# View status +./pm2.sh status + +# Delete services +./pm2.sh delete +``` + +### Log Viewing + +```bash +# View all logs (live) +./pm2.sh logs + +# Backend logs only +./pm2.sh logs backend + +# Frontend logs only +./pm2.sh logs frontend +``` + +### Build & Compile + +```bash +# Compile backend +./pm2.sh build + +# Recompile backend and restart +./pm2.sh rebuild +``` + +### Monitoring + +```bash +# Open PM2 monitoring dashboard (real-time CPU/Memory) +./pm2.sh monitor +``` + +--- + +## 📊 Access URLs + +After successful startup: + +- **Frontend Web Interface**: http://localhost:3000 +- **Backend API**: http://localhost:8080 +- **Health Check**: http://localhost:8080/api/health + +--- + +## 🔧 Configuration Files + +### pm2.config.js + +PM2 configuration file, defines frontend and backend startup parameters: + +```javascript +const path = require('path'); + +module.exports = { + apps: [ + { + name: 'nofx-backend', + script: './nofx', // Go binary + cwd: __dirname, // Dynamically get current directory + autorestart: true, + max_memory_restart: '500M' + }, + { + name: 'nofx-frontend', + script: 'npm', + args: 'run dev', // Vite dev server + cwd: path.join(__dirname, 'web'), // Dynamically join path + autorestart: true, + max_memory_restart: '300M' + } + ] +}; +``` + +**After modifying configuration, restart is required:** +```bash +./pm2.sh restart +``` + +--- + +## 📝 Log File Locations + +- **Backend Logs**: `./logs/backend-error.log` and `./logs/backend-out.log` +- **Frontend Logs**: `./web/logs/frontend-error.log` and `./web/logs/frontend-out.log` + +--- + +## 🔄 Startup on Boot + +Set PM2 to start on boot: + +```bash +# 1. Start services +./pm2.sh start + +# 2. Save current process list +pm2 save + +# 3. Generate startup script +pm2 startup + +# 4. Follow the instructions to execute command (requires sudo) +``` + +**Disable startup on boot:** +```bash +pm2 unstartup +``` + +--- + +## 🛠 Common Operations + +### Restart After Code Changes + +**Backend changes:** +```bash +./pm2.sh rebuild # Auto compile and restart +``` + +**Frontend changes:** +```bash +./pm2.sh restart # Vite will auto hot-reload, no restart needed +``` + +### View Real-time Resource Usage + +```bash +./pm2.sh monitor +``` + +### View Detailed Information + +```bash +pm2 info nofx-backend # Backend details +pm2 info nofx-frontend # Frontend details +``` + +### Clear Logs + +```bash +pm2 flush +``` + +--- + +## 🐛 Troubleshooting + +### Service Startup Failed + +```bash +# 1. View detailed errors +./pm2.sh logs + +# 2. Check port usage +lsof -i :8080 # Backend port +lsof -i :3000 # Frontend port + +# 3. Manual compile test +go build -o nofx +./nofx +``` + +### Backend Won't Start + +```bash +# ~~Check if config.json exists~~ +# ~~ls -l config.json~~ + +# Check if database file exists +ls -l trading.db + +# Check permissions +chmod +x nofx + +# Run manually to see errors +./nofx +``` + +### Frontend Not Accessible + +```bash +# Check node_modules +cd web && npm install + +# Manual start test +npm run dev +``` + +--- + +## 🎯 Production Environment Recommendations + +### 1. Use Production Mode + +Modify `pm2.config.js`: + +```javascript +{ + name: 'nofx-frontend', + script: 'npm', + args: 'run preview', // Change to preview (requires npm run build first) + env: { + NODE_ENV: 'production' + } +} +``` + +### 2. Increase Instances (Load Balancing) + +```javascript +{ + name: 'nofx-backend', + script: './nofx', + instances: 2, // Start 2 instances + exec_mode: 'cluster' +} +``` + +### 3. Auto Restart Strategy + +```javascript +{ + autorestart: true, + max_restarts: 10, + min_uptime: '10s', + max_memory_restart: '500M' +} +``` + +--- + +## 📊 Comparison with Docker Deployment + +| Feature | PM2 Deployment | Docker Deployment | +|---------|---------------|-------------------| +| Startup Speed | ⚡ Fast | 🐌 Slower | +| Resource Usage | 💚 Low | 🟡 Medium | +| Isolation | 🟡 Medium | 💚 High | +| Use Case | Dev/Single-machine | Production/Cluster | +| Configuration Complexity | 💚 Simple | 🟡 Medium | + +**Recommendations:** +- **Development Environment**: Use `./pm2.sh` +- **Production Environment**: Use `./start.sh` (Docker) + +--- + +## 🆘 Getting Help + +```bash +./pm2.sh help +``` + +Or check PM2 official documentation: https://pm2.keymetrics.io/ + +--- + +## 📄 License + +MIT diff --git a/PM2_DEPLOYMENT.md b/docs/getting-started/pm2-deploy.md similarity index 100% rename from PM2_DEPLOYMENT.md rename to docs/getting-started/pm2-deploy.md diff --git a/docs/guides/README.md b/docs/guides/README.md new file mode 100644 index 00000000..9b5e72b1 --- /dev/null +++ b/docs/guides/README.md @@ -0,0 +1,138 @@ +# 📘 NOFX User Guides + +**Language:** [English](README.md) | [äž­æ–‡](README.zh-CN.md) + +Comprehensive guides to help you use NOFX effectively. + +--- + +## 📚 Available Guides + +### 🔧 Basic Usage + +| Guide | Description | Status | +|-------|-------------|--------| +| [FAQ (English)](faq.en.md) | Frequently asked questions | ✅ Available | +| [FAQ (äž­æ–‡)](faq.zh-CN.md) | 垞见问题解答 | ✅ Available | +| Configuration Guide | Advanced settings and options | 🚧 Coming Soon | +| Trading Strategies | AI trading strategy examples | 🚧 Coming Soon | + +--- + +## 🐛 Troubleshooting + +### Common Issues + +**Issue: TA-Lib not found** +```bash +# macOS +brew install ta-lib + +# Ubuntu/Debian +sudo apt-get install libta-lib0-dev +``` + +**Issue: Precision error** +- System auto-handles LOT_SIZE from exchange +- Check network connection +- Verify exchange API is accessible + +**Issue: AI API timeout** +- Check API key validity +- Verify network connection +- Check API balance/credits +- Timeout is set to 120 seconds + +**Issue: Frontend can't connect** +- Ensure backend is running (http://localhost:8080) +- Check if port 8080 is available +- Check browser console for errors + +--- + +## 📖 Usage Tips + +### Best Practices + +**1. Risk Management** +- Start with small amounts (100-500 USDT) +- Use subaccounts for additional safety +- Set reasonable leverage limits +- Monitor daily loss limits + +**2. Performance Monitoring** +- Check decision logs regularly +- Analyze win rate and profit factor +- Review AI reasoning (Chain of Thought) +- Track equity curve trends + +**3. Configuration** +- Test on testnet first +- Gradually increase trading amounts +- Adjust scan intervals (3-5 minutes recommended) +- Use default coin list for beginners + +--- + +## 🎯 Advanced Topics + +### Multi-Trader Competition +Run multiple AI models simultaneously: +- Qwen vs DeepSeek head-to-head +- Compare performance in real-time +- Identify best-performing strategies + +### Custom Coin Pools +- Use external API for coin selection +- Combine AI500 + OI Top data +- Filter by liquidity and volume + +### Exchange Integration +- Binance Futures (CEX) +- Hyperliquid (DEX) +- Aster DEX (Binance-compatible) + +--- + +## 📊 Understanding Metrics + +### Key Performance Indicators + +**Win Rate** +- Percentage of profitable trades +- Target: >50% for consistent profit + +**Profit Factor** +- Ratio of gross profit to gross loss +- Target: >1.5 (1.5:1 or better) + +**Sharpe Ratio** +- Risk-adjusted return measure +- Higher is better (>1.0 is good) + +**Maximum Drawdown** +- Largest peak-to-trough decline +- Keep under 20% for safety + +--- + +## 🔗 Related Documentation + +- [Getting Started (EN)](../getting-started/README.md) - Initial setup +- [Getting Started (äž­æ–‡)](../getting-started/README.zh-CN.md) - 初始讟眮 +- [Community](../community/README.md) - Contributing and bounties +- [FAQ (English)](faq.en.md) - Common questions +- [FAQ (äž­æ–‡)](faq.zh-CN.md) - 垞见问题 + +--- + +## 🆘 Need Help? + +**Can't find what you need?** +- 💬 [Telegram Community](https://t.me/nofx_dev_community) +- 🐛 [GitHub Issues](https://github.com/tinkle-community/nofx/issues) +- 🐊 [Twitter @nofx_ai](https://x.com/nofx_ai) + +--- + +[← Back to Documentation Home](../README.md) diff --git a/docs/guides/README.zh-CN.md b/docs/guides/README.zh-CN.md new file mode 100644 index 00000000..2e358f6b --- /dev/null +++ b/docs/guides/README.zh-CN.md @@ -0,0 +1,137 @@ +# 📘 NOFX 䜿甚指南 + +**语蚀:** [English](README.md) | [äž­æ–‡](README.zh-CN.md) + +垮助悚有效䜿甚 NOFX 的绌合指南。 + +--- + +## 📚 可甚指南 + +### 🔧 基础䜿甚 + +| 指南 | 描述 | 状态 | +|------|------|------| +| [FAQ (äž­æ–‡)](faq.zh-CN.md) | 垞见问题解答 | ✅ 可甚 | +| [FAQ (English)](faq.en.md) | Frequently asked questions | ✅ 可甚 | +| 配眮指南 | 高级讟眮和选项 | 🚧 即将掚出 | +| 亀易策略 | AI 亀易策略瀺䟋 | 🚧 即将掚出 | + +--- + +## 🐛 故障排陀 + +### 垞见问题 + +**问题扟䞍到 TA-Lib** +```bash +# macOS +brew install ta-lib + +# Ubuntu/Debian +sudo apt-get install libta-lib0-dev +``` + +**问题粟床错误** +- 系统自劚倄理亀易所的 LOT_SIZE +- 检查眑络连接 +- 验证亀易所 API 可访问 + +**问题AI API 超时** +- 检查 API 密钥有效性 +- 验证眑络连接 +- 检查 API 䜙额/额床 +- 超时讟眮䞺 120 秒 + +**问题前端无法连接** +- 确保后端正圚运行 (http://localhost:8080) +- 检查端口 8080 是吊可甚 +- 检查浏览噚控制台错误 + +--- + +## 📖 䜿甚技巧 + +### 最䜳实践 + +**1. 风险管理** +- 从小金额匀始100-500 USDT +- 䜿甚子莊户增加安党性 +- 讟眮合理的杠杆限制 +- 监控每日亏损限制 + +**2. 性胜监控** +- 定期检查决策日志 +- 分析胜率和盈利因子 +- 审查 AI 掚理思绎铟 +- 跟螪权益曲线趋势 + +**3. 配眮** +- 先圚测试眑测试 +- 逐步增加亀易金额 +- 调敎扫描闎隔掚荐 3-5 分钟 +- 初孊者䜿甚默讀垁种列衚 + +--- + +## 🎯 进阶䞻题 + +### 倚亀易员竞赛 +同时运行倚䞪 AI 暡型 +- Qwen vs DeepSeek 对决 +- 实时比蟃性胜 +- 识别衚现最䜳的策略 + +### 自定义垁种池 +- 䜿甚倖郚 API 进行垁种选择 +- 结合 AI500 + OI Top 数据 +- 按流劚性和亀易量过滀 + +### 亀易所集成 +- Binance Futures䞭心化亀易所 +- Hyperliquid去䞭心化亀易所 +- Aster DEX兌容 Binance + +--- + +## 📊 理解指标 + +### 关键性胜指标 + +**胜率Win Rate** +- 盈利亀易的癟分比 +- 目标>50% 以获埗皳定盈利 + +**盈利因子Profit Factor** +- 总盈利䞎总亏损的比率 +- 目标>1.51.5:1 或曎奜 + +**倏普比率Sharpe Ratio** +- 风险调敎后的收益衡量 +- 越高越奜>1.0 䞺良奜 + +**最倧回撀Maximum Drawdown** +- 从峰倌到谷倌的最倧跌幅 +- 䞺安党起见保持圚 20% 以䞋 + +--- + +## 🔗 盞关文档 + +- [快速匀始](../getting-started/README.zh-CN.md) - 初始讟眮 +- [瀟区](../community/README.md) - 莡献和悬赏 +- [FAQ äž­æ–‡](faq.zh-CN.md) - 垞见问题 +- [FAQ English](faq.en.md) - Common questions + +--- + +## 🆘 需芁垮助 + +**扟䞍到悚需芁的内容** +- 💬 [Telegram 瀟区](https://t.me/nofx_dev_community) +- 🐛 [GitHub Issues](https://github.com/tinkle-community/nofx/issues) +- 🐊 [Twitter @nofx_ai](https://x.com/nofx_ai) + +--- + +[← 返回文档銖页](../README.md) diff --git a/docs/guides/faq.en.md b/docs/guides/faq.en.md new file mode 100644 index 00000000..7b31142d --- /dev/null +++ b/docs/guides/faq.en.md @@ -0,0 +1,25 @@ +# Frequently Asked Questions + +## Binance Position Mode Error (code=-4061) + +**Error Message**: `Order's position side does not match user's setting` + +**Cause**: The system requires Hedge Mode (dual position), but your Binance account is set to One-way Mode. + +### Solution + +1. Login to [Binance Futures Trading Platform](https://www.binance.com/en/futures/BTCUSDT) + +2. Click **⚙ Preferences** in the top right corner + +3. Select **Position Mode** + +4. Switch to **Hedge Mode** (Dual Position) + +5. Confirm the change + +**Note**: You must close all open positions before switching modes. + +--- + +For more issues, check [GitHub Issues](https://github.com/tinkle-community/nofx/issues) diff --git a/垞见问题.md b/docs/guides/faq.zh-CN.md similarity index 100% rename from 垞见问题.md rename to docs/guides/faq.zh-CN.md diff --git a/docs/i18n/README.md b/docs/i18n/README.md new file mode 100644 index 00000000..7668cfb6 --- /dev/null +++ b/docs/i18n/README.md @@ -0,0 +1,231 @@ +# 🌍 International Documentation / 囜际化文档 + +NOFX documentation is available in multiple languages. + +NOFX 文档提䟛倚种语蚀版本。 + +--- + +## 📚 Available Languages / 可甚语蚀 + +| Language | Main README | Status | Maintainers | +|----------|-------------|--------|-------------| +| 🇬🇧 **English** | [README.md](../../README.md) | ✅ Complete | Core Team | +| 🇚🇳 **Chinese (äž­æ–‡)** | [README.md](zh-CN/README.md) | ✅ Complete | Community | +| 🇷🇺 **Russian (РусскОй)** | [README.md](ru/README.md) | ✅ Complete | Community | +| 🇺🇊 **Ukrainian (УкраїМська)** | [README.md](uk/README.md) | ✅ Complete | Community | + +--- + +## 🔗 Quick Access / 快速访问 + +### English 🇬🇧 +- **Main README:** [../../README.md](../../README.md) +- **Contributing:** [../../CONTRIBUTING.md](../../CONTRIBUTING.md) +- **Security:** [../../SECURITY.md](../../SECURITY.md) + +### äž­æ–‡ 🇚🇳 +- **äž» README:** [zh-CN/README.md](zh-CN/README.md) +- **莡献指南:** [../../CONTRIBUTING.md](../../CONTRIBUTING.md#äž­æ–‡) +- **安党政策:** [../../SECURITY.md](../../SECURITY.md#äž­æ–‡) +- **垞见问题:** [../guides/faq.zh-CN.md](../guides/faq.zh-CN.md) + +### РусскОй 🇷🇺 +- **ОсМПвМПй README:** [ru/README.md](ru/README.md) +- **РукПвПЎствП пП участОю:** [../../CONTRIBUTING.md](../../CONTRIBUTING.md) +- **ППлОтОка безПпасМПстО:** [../../SECURITY.md](../../SECURITY.md) + +### УкраїМська 🇺🇊 +- **ГПлПвМОй README:** [uk/README.md](uk/README.md) +- **ППсібМОк із вМесків:** [../../CONTRIBUTING.md](../../CONTRIBUTING.md) +- **ППлітОка безпекО:** [../../SECURITY.md](../../SECURITY.md) + +--- + +## 🀝 Help with Translations / 垮助翻译 + +### Want to Contribute Translations? / 想芁莡献翻译 + +We welcome translation contributions! / 我们欢迎翻译莡献 + +**What needs translation? / 需芁翻译什么** +- ✅ Main README (complete for 4 languages) +- 🚧 Deployment guides (partial) +- 📋 User guides (needed) +- 📋 Contributing guide (needed for RU/UK) + +**How to contribute translations? / 劂䜕莡献翻译** + +1. **Check existing translations / 检查现有翻译** + - Browse this directory + - See what's missing + +2. **Claim a translation task / 讀领翻译任务** + - Open a GitHub Issue + - Title: `[TRANSLATION] Document name to Language` + - Example: `[TRANSLATION] CONTRIBUTING.md to Chinese` + +3. **Submit translation / 提亀翻译** + - Follow [Contributing Guide](../../CONTRIBUTING.md) + - Place file in appropriate language folder + - Keep formatting and structure consistent + +4. **Get recognized / 获埗讀可** + - Listed as translator in credits + - Eligible for contributor badges + - Possible bounty rewards ($50-200) + +--- + +## 📝 Translation Guidelines / 翻译指南 + +### File Naming Convention / 文件呜名规范 + +**Pattern:** `document-name.{language-code}.md` + +**Examples:** +``` +README.md → en (default) +docker-deploy.zh-CN.md → Chinese +docker-deploy.ru.md → Russian +faq.zh-CN.md → Chinese FAQ +``` + +**Language Codes:** +- `en` - English (default, no suffix needed) +- `zh-CN` - Simplified Chinese +- `ru` - Russian +- `uk` - Ukrainian +- `ja` - Japanese *(future)* +- `ko` - Korean *(future)* + +### Quality Standards / 莚量标准 + +**Must have / 必须具倇:** +- ✅ Accurate technical terms +- ✅ Natural, fluent language +- ✅ Consistent terminology +- ✅ Preserved formatting (markdown) +- ✅ Working internal links + +**Avoid / 避免:** +- ❌ Machine translation without review +- ❌ Inconsistent terminology +- ❌ Broken links or formatting +- ❌ Cultural insensitivity + +### Technical Terms / 技术术语 + +**Keep in English (don't translate):** +- API, HTTP, REST, JSON +- Docker, Kubernetes +- GitHub, Git, Pull Request +- Specific tool names (Binance, Hyperliquid) + +**Example - Chinese:** +- ✅ "启劚 Docker 容噚" (start Docker container) +- ❌ "启劚 倚克 容噚" (transliterated Docker) + +--- + +## 🌐 Request a New Language / 请求新语蚀 + +### Want NOFX in your language? / 垌望 NOFX 支持䜠的语蚀 + +**Steps / 步骀:** + +1. **Check if it's planned / 检查是吊已计划** + - See list below + - Search GitHub Issues + +2. **Create a request / 创建请求** + - Open GitHub Issue + - Title: `[TRANSLATION REQUEST] Language name` + - Explain: Number of potential users, your willingness to help + +3. **Volunteer to help / 志愿垮助** + - Offer to translate + - Find other speakers to review + - Commit to maintaining updates + +### Planned Languages / 计划䞭的语蚀 + +| Language | Status | Need Volunteers? | +|----------|--------|------------------| +| 🇯🇵 Japanese | 📋 Planned | ✅ Yes | +| 🇰🇷 Korean | 📋 Planned | ✅ Yes | +| 🇪🇞 Spanish | 📋 Planned | ✅ Yes | +| 🇫🇷 French | 📋 Planned | ✅ Yes | +| 🇩🇪 German | 📋 Planned | ✅ Yes | + +--- + +## 👥 Translation Team / 翻译团队 + +### Current Translators / 圓前翻译者 + +| Language | Translators | Status | +|----------|-------------|--------| +| 🇚🇳 Chinese | Community | Active | +| 🇷🇺 Russian | Community | Active | +| 🇺🇊 Ukrainian | Community | Active | + +**Want to join the team? / 想加入团队** +- Contact on [Telegram](https://t.me/nofx_dev_community) +- Open an issue on GitHub +- DM [@nofx_ai](https://x.com/nofx_ai) on Twitter + +--- + +## 📊 Translation Progress / 翻译进床 + +### Document Coverage / 文档芆盖率 + +| Document | EN | äž­æ–‡ | РУ | УК | +|----------|----|----|----|----| +| Main README | ✅ | ✅ | ✅ | ✅ | +| CONTRIBUTING | ✅ | ✅ | 🚧 | 🚧 | +| CODE_OF_CONDUCT | ✅ | ✅ | 🚧 | 🚧 | +| SECURITY | ✅ | ✅ | 🚧 | 🚧 | +| Docker Deploy | ✅ | ✅ | ❌ | ❌ | +| FAQ | ✅ | ✅ | ❌ | ❌ | + +**Legend / 囟䟋:** +- ✅ Complete / 完成 +- 🚧 In Progress / 进行䞭 +- ❌ Not Started / 未匀始 + +--- + +## 🎯 Priority Translations / 䌘先翻译 + +**High Priority / 高䌘先级:** +1. CONTRIBUTING.md (all languages) +2. Docker deployment guides +3. FAQ sections + +**Medium Priority / 䞭䌘先级:** +1. User guides +2. Troubleshooting docs +3. API reference + +**Low Priority / 䜎䌘先级:** +1. Architecture docs (technical, less urgent) +2. Advanced configuration guides + +--- + +## 🆘 Translation Help / 翻译垮助 + +**Questions? / 有问题** +- 💬 Ask in [Telegram Community](https://t.me/nofx_dev_community) +- 🐙 Open a [GitHub Issue](https://github.com/tinkle-community/nofx/issues) +- 📧 Contact maintainers + +**Resources / 资源:** +- [Contributing Guide](../../CONTRIBUTING.md) - How to submit +- [Markdown Guide](https://www.markdownguide.org/) - Formatting reference + +--- + +[← Back to Documentation Home](../README.md) diff --git a/README.ru.md b/docs/i18n/ru/README.md similarity index 66% rename from README.ru.md rename to docs/i18n/ru/README.md index 2d2e6ff3..2feaa824 100644 --- a/README.ru.md +++ b/docs/i18n/ru/README.md @@ -6,10 +6,29 @@ [![License](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE) [![Backed by Amber.ac](https://img.shields.io/badge/Backed%20by-Amber.ac-orange.svg)](https://amber.ac) -**ЯзыкО / Languages:** [English](README.md) | [äž­æ–‡](README.zh-CN.md) | [УкраїМська](README.uk.md) | [РусскОй](README.ru.md) +**ЯзыкО / Languages:** [English](../../../README.md) | [äž­æ–‡](../zh-CN/README.md) | [УкраїМська](../uk/README.md) | [РусскОй](../ru/README.md) **ОфОцОальМый Twitter:** [@nofx_ai](https://x.com/nofx_ai) +**📚 ДПкуЌеМтацОя:** [ГлавМая](../../README.md) | [НачалП рабПты](../../getting-started/README.md) | [ЖурМал ОзЌеМеМОй](../../../CHANGELOG.zh-CN.md) | [СППбществП](../../community/README.md) + +--- + +## 📑 СПЎержаМОе + +- [🚀 УМОверсальМая AI ТПргПвая ОперацОПММая СОстеЌа](#-уМОверсальМая-ai-тПргПвая-ПперацОПММая-сОстеЌа) +- [👥 СППбществП РазрабПтчОкПв](#-сППбществП-разрабПтчОкПв) +- [🆕 ЧтП НПвПгП](#-чтП-МПвПгП) +- [📞 СкрОМшПты](#-скрОМшПты) +- [✹ Текущая РеалОзацОя - КрОптПвалютМые РыМкО](#-текущая-реалОзацОя---крОптПвалютМые-рыМкО) +- [🔮 ДПрПжМая Карта](#-ЎПрПжМая-карта---расшОреМОе-Ма-уМОверсальМые-рыМкО) +- [🏗 ТехМОческая АрхОтектура](#-техМОческая-архОтектура) +- [🚀 Быстрый Старт](#-быстрый-старт) +- [📊 ЀуМкцОО Web-ОМтерфейса](#-фуМкцОО-web-ОМтерфейса) +- [⚠ ВажМые ПреЎупрежЎеМОя П РОсках](#-важМые-преЎупрежЎеМОя-П-рОсках) +- [🛠 ОбщОе ПрПблеЌы](#-ПбщОе-прПблеЌы) +- [🔄 ЖурМал ИзЌеМеМОй](#-журМал-ОзЌеМеМОй) + --- ## 🚀 УМОверсальМая AI ТПргПвая ОперацОПММая СОстеЌа @@ -74,7 +93,7 @@ NOFX теперь пПЎЎержОвает **трО ПсМПвМые бОржО* **Быстрый старт:** 1. ППлучОте прОватМый ключ MetaMask (уЎалОте префОкс `0x`) -2. УстаМПвОте `"exchange": "hyperliquid"` в config.json +2. ~~УстаМПвОте `"exchange": "hyperliquid"` в config.json~~ *НастрПйте через веб-ОМтерфейс* 3. ДПбавьте `"hyperliquid_private_key": "your_key"` 4. НачМОте тПргПвать! @@ -109,15 +128,19 @@ NOFX теперь пПЎЎержОвает **трО ПсМПвМые бОржО* ## 📞 СкрОМшПты ### 🏆 РежОЌ кПМкуреМцОО - БОтва AI в реальМПЌ вреЌеМО -![СтраМОца кПМкуреМцОО](screenshots/competition-page.png) +![СтраМОца кПМкуреМцОО](../../../screenshots/competition-page.png) *ЛОЎербПрЎ с МескПлькОЌО AI О графОкО сравМеМОя прПОзвПЎОтельМПстО в реальМПЌ вреЌеМО пПказывают бОтву Qwen прПтОв DeepSeek* ### 📊 ДеталО трейЎера - ППлМая тПргПвая паМель -![СтраМОца Ўеталей](screenshots/details-page.png) +![СтраМОца Ўеталей](../../../screenshots/details-page.png) *ПрПфессОПМальМый тПргПвый ОМтерфейс с крОвыЌО капОтала, жОвыЌО пПзОцОяЌО О лПгаЌО решеМОй AI с раскрываеЌыЌО вхПЎМыЌО прПЌптаЌО О цепПчкПй рассужЎеМОй* --- +> 📘 **ПрОЌечаМОе**: ЭтП упрПщеММая русская версОя README. Для пПлучеМОя пПлМПй техМОческПй ЎПкуЌеМтацОО, включая архОтектуру сОстеЌы, API-ОМтерфейсы О расшОреММые кПМфОгурацОО, сЌ. [АМглОйскую версОю](../../../README.md) ОлО [КОтайскую версОю](../zh-CN/README.md). + +--- + ## ✹ ОсМПвМые вПзЌПжМПстО ### 🏆 РежОЌ кПМкуреМцОО МескПлькОх AI @@ -173,6 +196,55 @@ NOFX теперь пПЎЎержОвает **трО ПсМПвМые бОржО* --- +## 🔮 ДПрПжМая Карта - РасшОреМОе Ма УМОверсальМые РыМкО + +МОссОя NOFX - стать **УМОверсальМПй AI ТПргПвПй ОперацОПММПй СОстеЌПй** Ўля всех фОМаМсПвых рыМкПв. + +**ВОЎеМОе:** Та же архОтектура. Та же агеМтМая структура. Все рыМкО. + +**РасшОреМОе Ма РыМкО:** +- 📈 **ЀПМЎПвые РыМкО**: АкцОО СКА, A-акцОО, ГПМкПМгская бОржа +- 📊 **РыМкО ЀьючерсПв**: ТПварМые фьючерсы, ОМЎексМые фьючерсы +- 🎯 **ОпцОПММая ТПргПвля**: ОпцОПМы Ма акцОО, крОптП ПпцОПМы +- 💱 **РыМкО ЀПрекс**: ОсМПвМые валютМые пары, крПсс-курсы + +**ПреЎстПящОе ЀуМкцОО:** +- РасшОреММые AI вПзЌПжМПстО (GPT-4, Claude 3, Gemini Pro, гОбкОе шаблПМы прПЌптПв) +- НПвые ОМтеграцОО бОрж (OKX, Bybit, Lighter, EdgeX + CEX/Perp-DEX) +- РефактПрОМг структуры прПекта (высПкая связМПсть, МОзкая связаММПсть, прОМцОпы SOLID) +- УлучшеМОя безПпасМПстО (AES-256 шОфрПваМОе API ключей, RBAC, улучшеМОя 2FA) +- УлучшеМОя пПльзПвательскПгП Ппыта (ЌПбОльМый ОМтерфейс, графОкО TradingView, сОстеЌа ПпПвещеМОй) + +📖 **Для пПЎрПбМПй ЎПрПжМПй карты О срПкПв сЌ.:** +- **English:** [Roadmap Documentation](../../roadmap/README.md) +- **äž­æ–‡:** [路线囟文档](../../roadmap/README.zh-CN.md) + +--- + +## 🏗 ТехМОческая АрхОтектура + +NOFX пПстрПеМ Ма сПвреЌеММПй ЌПЎульМПй архОтектуре: + +- **Backend:** Go с фрейЌвПркПЌ Gin, база ЎаММых SQLite +- **Frontend:** React 18 + TypeScript + Vite + TailwindCSS +- **ППЎЎержка БОрж:** Binance, Hyperliquid, Aster DEX +- **ИМтеграцОя AI:** DeepSeek, Qwen О пПльзПвательскОе OpenAI-сПвЌестОЌые API +- **УправлеМОе СПстПяМОеЌ:** Zustand Ўля фрПМтеМЎа, Ма ПсМПве базы ЎаММых Ўля бэкеМЎа +- **ОбМПвлеМОя в РеальМПЌ ВреЌеМО:** SWR с ОМтервалаЌО ПпрПса 5-10 секуМЎ + +**Ключевые ОсПбеММПстО:** +- 🗄 КПМфОгурацОя Ма ПсМПве базы ЎаММых (бПльше МОкакПгП реЎактОрПваМОя JSON) +- 🔐 JWT аутеМтОфОкацОя с ПпцОПМальМПй пПЎЎержкПй 2FA +- 📊 ОтслежОваМОе прПОзвПЎОтельМПстО О аМалОтОка в реальМПЌ вреЌеМО +- 🀖 РежОЌ кПМкуреМцОО Multi-AI с жОвыЌ сравМеМОеЌ +- 🔌 RESTful API Ўля всех МастрПек О ЌПМОтПрОМга + +📖 **Для пПЎрПбМПй ЎПкуЌеМтацОО пП архОтектуре сЌ.:** +- **РусскОй:** [ДПкуЌеМтацОя пП АрхОтектуре](../../architecture/README.md) +- **äž­æ–‡:** [架构文档](../../architecture/README.zh-CN.md) + +--- + ## 💰 РегОстрацОя аккауМта Binance (ЭкПМПЌьте Ма кПЌОссОях!) ПереЎ ОспПльзПваМОеЌ этПй сОстеЌы ваЌ МужеМ аккауМт Binance Futures. **ИспПльзуйте Машу реферальМую ссылку Ўля пПлучеМОя скОЎкО Ма кПЌОссОО:** @@ -824,103 +896,73 @@ curl http://localhost:8080/api/health КажЎый цОкл прОМятОя решеМОй (пП уЌПлчаМОю 3 ЌОМуты), сОстеЌа рабПтает пП слеЎующеЌу прПцессу: -``` -┌──────────────────────────────────────────────────────────┐ -│ 1. 📊 АМалОз ОстПрОческПй прПОзвПЎОтельМПстО │ -│ (пПслеЎМОе 20 цОклПв) │ -├─────────────────────────────────────────────────────────── -│ ✓ Расчет ПбщегП прПцеМта выОгрышей, среЎМей прОбылО, │ -│ сППтМПшеМОя прОбылО/убытка │ -│ ✓ СтатОстОка пП кажЎПй ЌПМете (прПцеМт выОгрышей, │ -│ среЎМОй P/L в USDT) │ -│ ✓ ОпреЎелеМОе лучшОх/хуЎшОх ЌПМет пП прПОзвПЎОтельМПстО │ -│ ✓ СпОсПк Ўеталей пПслеЎМОх 5 сЎелПк с тПчМыЌ P/L │ -│ ✓ Расчет кПэффОцОеМта Карпа Ўля ПцеМкО рОска │ -│ 📌 НОВОЕ (v2.0.2): ТПчМый P/L в USDT с учетПЌ плеча │ -└──────────────────────────────────────────────────────────┘ - ↓ -┌──────────────────────────────────────────────────────────┐ -│ 2. 💰 ППлучеМОе сПстПяМОя аккауМта │ -├─────────────────────────────────────────────────────────── -│ • КапОтал аккауМта, ЎПступМый балаМс, МереалОзПваММый │ -│ P/L │ -│ • КПлОчествП пПзОцОй, ПбщОй P/L (реалОзПваММый + │ -│ МереалОзПваММый) │ -│ • ИспПльзПваМОе ЌаржО (текущее/ЌаксОЌальМПе) │ -│ • ИМЎОкатПры ПцеМкО рОска │ -└──────────────────────────────────────────────────────────┘ - ↓ -┌──────────────────────────────────────────────────────────┐ -│ 3. 🔍 АМалОз существующОх пПзОцОй (еслО есть) │ -├─────────────────────────────────────────────────────────── -│ • ППлучеМОе рыМПчМых ЎаММых Ўля кажЎПй пПзОцОО │ -│ (3-ЌОМутМые + 4-часПвые свечО) │ -│ • Расчет техМОческОх ОМЎОкатПрПв (RSI, MACD, EMA) │ -│ • ОтПбражеМОе ЎлОтельМПстО уЎержаМОя пПзОцОО │ -│ (МапрОЌер, "уЎержОвается 2 часа 15 ЌОМут") │ -│ • AI ПпреЎеляет, МужМП лО закрыть (тейк-прПфОт, │ -│ стПп-лПсс ОлО кПрректОрПвка) │ -│ 📌 НОВОЕ (v2.0.2): ОтслежОваМОе ЎлОтельМПстО пПзОцОО │ -│ пПЌПгает AI решать │ -└──────────────────────────────────────────────────────────┘ - ↓ -┌──────────────────────────────────────────────────────────┐ -│ 4. 🎯 ОцеМка МПвых вПзЌПжМПстей (пул каМЎОЎатПв ЌПМет) │ -├─────────────────────────────────────────────────────────── -│ • ППлучеМОе тПп-20 ЌПМет с высПкОЌ рейтОМгПЌ AI500 │ -│ • ППлучеМОе тПп-20 ЌПМет с саЌыЌ быстрыЌ рПстПЌ OI │ -│ • ОбъеЎОМеМОе, уЎалеМОе ЎублОкатПв, фОльтрацОя ЌПМет с │ -│ МОзкПй лОквОЎМПстью (OI < 15M USD) │ -│ • МассПвПе пПлучеМОе рыМПчМых ЎаММых О техМОческОх │ -│ ОМЎОкатПрПв │ -│ • ППЎгПтПвка пПлМых пПслеЎПвательМПстей сырых ЎаММых │ -│ Ўля кажЎПй ЌПМеты-каМЎОЎата │ -└──────────────────────────────────────────────────────────┘ - ↓ -┌──────────────────────────────────────────────────────────┐ -│ 5. 🧠 КПЌплексМПе решеМОе AI │ -├─────────────────────────────────────────────────────────── -│ • ПрПсЌПтр ОстПрОческПй ПбратМПй связО (прПцеМт │ -│ выОгрышей, кПэффОцОеМт P/L, лучшОе/хуЎшОе ЌПМеты) │ -│ • ППлучеМОе всех ЎаММых пПслеЎПвательМПстей (свечО, │ -│ ОМЎОкатПры, Пткрытый ОМтерес) │ -│ • АМалОз Chain of Thought │ -│ • ВывПЎ решеМОя: закрыть/Пткрыть/уЎержОвать/МаблюЎать │ -│ • Включает параЌетры плеча, разЌера, стПп-лПсса, │ -│ тейк-прПфОта │ -│ 📌 НОВОЕ (v2.0.2): AI ЌПжет свПбПЎМП аМалОзОрПвать │ -│ сырые пПслеЎПвательМПстО, Ме ПграМОчеМ зараМее │ -│ ПпреЎелеММыЌО ОМЎОкатПраЌО │ -└──────────────────────────────────────────────────────────┘ - ↓ -┌──────────────────────────────────────────────────────────┐ -│ 6. ⚡ ИспПлМеМОе сЎелПк │ -├─────────────────────────────────────────────────────────── -│ • ПрОПрОтОзацОя: сМачала закрытОе, затеЌ ПткрытОе │ -│ • АвтПЌатОческая аЎаптацОя тПчМПстО (правОла LOT_SIZE) │ -│ • ПреЎПтвращеМОе МакПплеМОя пПзОцОй (ПтклПМеМОе │ -│ ЎублОрПваМОя ЌПМета/МаправлеМОе) │ -│ • АвтПЌатОческая ПтЌеМа всех ПрЎерПв пПсле закрытОя │ -│ • ЗапОсь вреЌеМО ПткрытОя Ўля ПтслежОваМОя │ -│ ЎлОтельМПстО пПзОцОО │ -│ 📌 НОВОЕ (v2.0.2): ОтслежОваМОе вреЌеМО ПткрытОя │ -│ пПзОцОО │ -└──────────────────────────────────────────────────────────┘ - ↓ -┌──────────────────────────────────────────────────────────┐ -│ 7. 📝 ЗапОсь лПгПв │ -├─────────────────────────────────────────────────────────── -│ • СПхраМеМОе пПлМПй запОсО решеМОя в decision_logs/ │ -│ • Включает цепПчку рассужЎеМОй, JSON решеМОя, сМОЌПк │ -│ аккауМта, результаты ОспПлМеМОя │ -│ • ХраМеМОе пПлМых ЎаММых пПзОцОО (кПлОчествП, плечП, │ -│ вреЌя ПткрытОя/закрытОя) │ -│ • ИспПльзПваМОе ключей symbol_side Ўля преЎПтвращеМОя │ -│ кПМфлОктПв лПМг/шПрт │ -│ 📌 НОВОЕ (v2.0.2): ПреЎПтвращеМОе кПМфлОктПв прО │ -│ уЎержаМОО лПМг + шПрт, учет кПлОчества + плеча │ -└──────────────────────────────────────────────────────────┘ -``` +### Каг 1: 📊 АМалОз ОстПрОческПй прПОзвПЎОтельМПстО (пПслеЎМОе 20 цОклПв) +- ✓ Расчет ПбщегП прПцеМта выОгрышей, среЎМей прОбылО, сППтМПшеМОя прОбылО/убытка +- ✓ СтатОстОка пП кажЎПй ЌПМете (прПцеМт выОгрышей, среЎМОй P/L в USDT) +- ✓ ОпреЎелеМОе лучшОх/хуЎшОх ЌПМет пП прПОзвПЎОтельМПстО +- ✓ СпОсПк Ўеталей пПслеЎМОх 5 сЎелПк с тПчМыЌ P/L +- ✓ Расчет кПэффОцОеМта Карпа Ўля ПцеМкО рОска +- 📌 **НОВОЕ (v2.0.2)**: ТПчМый P/L в USDT с учетПЌ плеча + +**↓** + +### Каг 2: 💰 ППлучеМОе сПстПяМОя аккауМта +- КапОтал аккауМта, ЎПступМый балаМс, МереалОзПваММый P/L +- КПлОчествП пПзОцОй, ПбщОй P/L (реалОзПваММый + МереалОзПваММый) +- ИспПльзПваМОе ЌаржО (текущее/ЌаксОЌальМПе) +- ИМЎОкатПры ПцеМкО рОска + +**↓** + +### Каг 3: 🔍 АМалОз существующОх пПзОцОй (еслО есть) +- ППлучеМОе рыМПчМых ЎаММых Ўля кажЎПй пПзОцОО (3-ЌОМутМые + 4-часПвые свечО) +- Расчет техМОческОх ОМЎОкатПрПв (RSI, MACD, EMA) +- ОтПбражеМОе ЎлОтельМПстО уЎержаМОя пПзОцОО (МапрОЌер, "уЎержОвается 2 часа 15 ЌОМут") +- AI ПпреЎеляет, МужМП лО закрыть (тейк-прПфОт, стПп-лПсс ОлО кПрректОрПвка) +- 📌 **НОВОЕ (v2.0.2)**: ОтслежОваМОе ЎлОтельМПстО пПзОцОО пПЌПгает AI решать + +**↓** + +### Каг 4: 🎯 ОцеМка МПвых вПзЌПжМПстей (пул каМЎОЎатПв ЌПМет) +- ППлучеМОе пула ЌПМет (2 режОЌа): + - 🌟 **РежОЌ пП уЌПлчаМОю**: BTC, ETH, SOL, BNB, XRP О т.ÐŽ. + - ⚙ **РасшОреММый режОЌ**: AI500 (тПп-20) + OI Top (тПп-20) +- ОбъеЎОМеМОе, уЎалеМОе ЎублОкатПв, фОльтрацОя ЌПМет с МОзкПй лОквОЎМПстью (OI < 15M USD) +- МассПвПе пПлучеМОе рыМПчМых ЎаММых О техМОческОх ОМЎОкатПрПв +- ППЎгПтПвка пПлМых пПслеЎПвательМПстей сырых ЎаММых Ўля кажЎПй ЌПМеты-каМЎОЎата + +**↓** + +### Каг 5: 🧠 КПЌплексМПе решеМОе AI +- ПрПсЌПтр ОстПрОческПй ПбратМПй связО (прПцеМт выОгрышей, кПэффОцОеМт P/L, лучшОе/хуЎшОе ЌПМеты) +- ППлучеМОе всех ЎаММых пПслеЎПвательМПстей (свечО, ОМЎОкатПры, Пткрытый ОМтерес) +- АМалОз Chain of Thought +- ВывПЎ решеМОя: закрыть/Пткрыть/уЎержОвать/МаблюЎать +- Включает параЌетры плеча, разЌера, стПп-лПсса, тейк-прПфОта +- 📌 **НОВОЕ (v2.0.2)**: AI ЌПжет свПбПЎМП аМалОзОрПвать сырые пПслеЎПвательМПстО, Ме ПграМОчеМ зараМее ПпреЎелеММыЌО ОМЎОкатПраЌО + +**↓** + +### Каг 6: ⚡ ИспПлМеМОе сЎелПк +- ПрОПрОтОзацОя: сМачала закрытОе, затеЌ ПткрытОе +- АвтПЌатОческая аЎаптацОя тПчМПстО (правОла LOT_SIZE) +- ПреЎПтвращеМОе МакПплеМОя пПзОцОй (ПтклПМеМОе ЎублОрПваМОя ЌПМета/МаправлеМОе) +- АвтПЌатОческая ПтЌеМа всех ПрЎерПв пПсле закрытОя +- ЗапОсь вреЌеМО ПткрытОя Ўля ПтслежОваМОя ЎлОтельМПстО пПзОцОО +- 📌 ОтслежОваМОе вреЌеМО ПткрытОя пПзОцОО + +**↓** + +### Каг 7: 📝 ЗапОсь лПгПв +- СПхраМеМОе пПлМПй запОсО решеМОя в `decision_logs/` +- Включает цепПчку рассужЎеМОй, JSON решеМОя, сМОЌПк аккауМта, результаты ОспПлМеМОя +- ХраМеМОе пПлМых ЎаММых пПзОцОО (кПлОчествП, плечП, вреЌя ПткрытОя/закрытОя) +- ИспПльзПваМОе ключей `symbol_side` Ўля преЎПтвращеМОя кПМфлОктПв лПМг/шПрт +- 📌 **НОВОЕ (v2.0.2)**: ПреЎПтвращеМОе кПМфлОктПв прО уЎержаМОО лПМг + шПрт, учет кПлОчества + плеча + +**↓** + +**🔄 (ППвтПр кажЎые 3-5 ЌОМут)** ### Ключевые улучшеМОя в v2.0.2 @@ -1058,263 +1100,24 @@ sudo apt-get install libta-lib0-dev --- -## 🔄 ИстПрОя ОзЌеМеМОй +## 🔄 ЖурМал ИзЌеМеМОй -```json -{ - "traders": [ - { - "id": "qwen_trader", - "name": "Qwen AI Trader", - "ai_model": "qwen", - "binance_api_key": "ВАК_BINANCE_API_KEY", - "binance_secret_key": "ВАК_BINANCE_SECRET_KEY", - "use_qwen": true, - "qwen_key": "sk-xxxxx", - "scan_interval_minutes": 3, - "initial_balance": 1000.0 - }, - { - "id": "deepseek_trader", - "name": "DeepSeek AI Trader", - "ai_model": "deepseek", - "binance_api_key": "ВАК_BINANCE_API_KEY_2", - "binance_secret_key": "ВАК_BINANCE_SECRET_KEY_2", - "use_qwen": false, - "deepseek_key": "sk-xxxxx", - "scan_interval_minutes": 3, - "initial_balance": 1000.0 - } - ], - "use_default_coins": false, - "coin_pool_api_url": "http://x.x.x.x:xxx/api/ai500/list?auth=ВАК_AUTH", - "oi_top_api_url": "http://x.x.x.x:xxx/api/oi/top?auth=ВАК_AUTH", - "api_server_port": 8080 -} -``` +📖 **Для пПЎрПбМПй ОстПрОО версОй О ПбМПвлеМОй сЌ.:** -**ПрОЌечаМОя к кПМфОгурацОО:** -- `traders`: НастрПйте 1-N трейЎерПв (ПЎОМ AI ОлО сПревМПваМОе МескПлькОх AI) -- `id`: УМОкальМый ОЎеМтОфОкатПр трейЎера (ОспПльзуется Ўля ЎОректПрОО лПгПв) -- `ai_model`: "qwen" ОлО "deepseek" -- `binance_api_key/secret_key`: КажЎый трейЎер ОспПльзует МезавОсОЌый аккауМт Binance -- `initial_balance`: НачальМый балаМс (Ўля расчета P/L%) -- `scan_interval_minutes`: ЊОкл прОМятОя решеМОй (рекПЌеМЎуется 3-5 ЌОМут) -- `use_default_coins`: **true** = ИспПльзПвать 8 ПсМПвМых ЌПМет пП уЌПлчаМОю | **false** = ИспПльзПвать API пул ЌПМет (рекПЌеМЎуется Ўля МПвОчкПв: true) -- `coin_pool_api_url`: API пула ЌПМет AI500 (ПпцОПМальМП, ОгМПрОруется прО use_default_coins=true) -- `oi_top_api_url`: API ПткрытПгП ОМтереса OI Top (ПпцОПМальМП, еслО пустП, ЎаММые OI Top прПпускаются) +- **РусскОй:** [CHANGELOG.zh-CN.md](../../../CHANGELOG.zh-CN.md) +- **English:** [CHANGELOG.md](../../../CHANGELOG.md) -**СпОсПк ЌПМет пП уЌПлчаМОю** (кПгЎа `use_default_coins: true`): -- BTC, ETH, SOL, BNB, XRP, DOGE, ADA, HYPE +**ППслеЎМяя ВерсОя:** v3.0.0 (2025-10-30) - МасштабМая ТраМсфПрЌацОя АрхОтектуры -### 5. Запуск сОстеЌы - -**Запуск backend (сОстеЌа AI тПргПвлО + API сервер):** - -```bash -go build -o nofx -./nofx -``` - -**Запуск frontend (веб-паМель):** - -ОткрПйте МПвый терЌОМал: - -```bash -cd web -npm run dev -``` - -**ДПступ к ОМтерфейсу:** -``` -Веб-паМель: http://localhost:3000 -API сервер: http://localhost:8080 -``` - -### 6. ОстаМПвка сОстеЌы - -НажЌОте `Ctrl+C` в ПбПОх терЌОМалах - ---- - -## ⚠ ВажМые преЎупрежЎеМОя П рОсках - -### ТПргПвые рОскО - -1. **РыМкО крОптПвалют чрезвычайМП вПлатОльМы**, решеМОя AI Ме гараМтОруют прОбыль -2. **ТПргПвля фьючерсаЌО ОспПльзует плечП**, убыткО ЌПгут превысОть ПсМПвМую суЌЌу -3. **ЭкстреЌальМые рыМПчМые услПвОя** ЌПгут прОвестО к лОквОЎацОО -4. **КПЌОссОО за фОМаМсОрПваМОе** ЌПгут пПвлОять Ма стПОЌПсть уЎержаМОя -5. **РОск лОквОЎМПстО**: НекПтПрые ЌПМеты ЌПгут Оспытывать прПскальзываМОе - -### ТехМОческОе рОскО - -1. **ЗаЎержка сетО** ЌПжет вызвать прПскальзываМОе цеМы -2. **ЛОЌОты API** ЌПгут пПвлОять Ма ОспПлМеМОе сЎелПк -3. **ТайЌ-ауты AI API** ЌПгут вызвать сбПО решеМОй -4. **СОстеЌМые ПшОбкО** ЌПгут вызвать МеПжОЎаММПе пПвеЎеМОе - -### РекПЌеМЎацОО пП ОспПльзПваМОю - -✅ **РекПЌеМЎуется** -- ИспПльзуйте тПлькП среЎства, пПтерю кПтПрых вы ЌПжете пПзвПлОть Ўля тестОрПваМОя -- НачМОте с МебПльшОх суЌЌ (рекПЌеМЎуется 100-500 USDT) -- РегулярМП прПверяйте сПстПяМОе рабПты сОстеЌы -- ОтслежОвайте ОзЌеМеМОя балаМса счета -- АМалОзОруйте лПгО решеМОй AI Ўля пПМОЌаМОя стратегОО - -❌ **Не рекПЌеМЎуется** -- ИМвестОрПвать все среЎства ОлО заеЌМые ЎеМьгО -- Запускать без прОсЌПтра Ма ЎлОтельМые перОПЎы -- СлепП ЎПверять решеМОяЌ AI -- ИспПльзПвать без пПМОЌаМОя сОстеЌы -- Запускать вП вреЌя экстреЌальМПй вПлатОльМПстО рыМка - ---- - -## 🛠 Частые прПблеЌы - -### 1. ОшОбка кПЌпОляцОО: TA-Lib Ме МайЎеМа - -**РешеМОе**: УстаМПвОте бОблОПтеку TA-Lib -```bash -# macOS -brew install ta-lib - -# Ubuntu -sudo apt-get install libta-lib0-dev -``` - -### 2. ОшОбка тПчМПстО: ТПчМПсть превышает ЌаксОЌуЌ - -**РешеМОе**: СОстеЌа автПЌатОческО Пбрабатывает тПчМПсть Оз Binance LOT_SIZE. ЕслО ПшОбка сПхраМяется, прПверьте сетевПе пПЎключеМОе. - -### 3. ТайЌ-аут AI API - -**РешеМОе**: -- ПрПверьте правОльМПсть API ключа -- ПрПверьте сетевПе пПЎключеМОе (ЌПжет пПтребПваться прПксО) -- ТайЌ-аут сОстеЌы устаМПвлеМ Ма 120 секуМЎ - -### 4. Frontend Ме ЌПжет пПЎключОться к backend - -**РешеМОе**: -- УбеЎОтесь, чтП backend запущеМ (http://localhost:8080) -- ПрПверьте, Ме заМят лО пПрт 8080 -- ПрПверьте ПшОбкО в кПМсПлО браузера - -### 5. СбПй API пула ЌПМет - -**РешеМОе**: -- API пула ЌПМет ПпцОПМалеМ -- ЕслО API Ме рабПтает, сОстеЌа ОспПльзует ПсМПвМые ЌПМеты пП уЌПлчаМОю (BTC, ETH О т.ÐŽ.) -- ПрПверьте URL API О параЌетр auth в config.json - ---- - -## 📄 ЛОцеМзОя - -ЛОцеМзОя MIT - СЌ. файл [LICENSE](LICENSE) Ўля Ўеталей - ---- - -## 🀝 ВклаЎ в прПект - -ПрОветствуются Issues О Pull Requests! - -### РукПвПЎствП пП разрабПтке - -1. СЎелайте Fork прПекта -2. СПзЎайте ветку фуМкцОО (`git checkout -b feature/AmazingFeature`) -3. ЗафОксОруйте ОзЌеМеМОя (`git commit -m 'Add some AmazingFeature'`) -4. Отправьте в ветку (`git push origin feature/AmazingFeature`) -5. ОткрПйте Pull Request - ---- - -## 📬 КПМтакты - -- **Twitter/X**: [@Web3Tinkle](https://x.com/Web3Tinkle) -- **GitHub Issues**: [СПзЎать Issue](https://github.com/tinkle-community/nofx/issues) - ---- - -## 🙏 БлагПЎарМПстО - -- [Binance API](https://binance-docs.github.io/apidocs/futures/en/) - Binance Futures API -- [DeepSeek](https://platform.deepseek.com/) - DeepSeek AI API -- [Qwen](https://dashscope.aliyuncs.com/) - Alibaba Cloud Qwen -- [TA-Lib](https://ta-lib.org/) - БОблОПтека техМОческОх ОМЎОкатПрПв -- [Recharts](https://recharts.org/) - БОблОПтека графОкПв React - ---- - -## 🔄 ИстПрОя ОзЌеМеМОй - -### v2.0.2 (2025-10-29) - -**КрОтОческОе ОсправлеМОя ПшОбПк - ИстПрОя сЎелПк О аМалОз прПОзвПЎОтельМПстО:** - -Эта версОя Осправляет **крОтОческОе ПшОбкО расчета** в сОстеЌе ОстПрОческОх запОсей сЎелПк О аМалОза прПОзвПЎОтельМПстО, кПтПрые зМачОтельМП влОялО Ма статОстОку прОбыльМПстО. - -**1. Расчет P/L - ИсправлеМОе крупМПй ПшОбкО** (logger/decision_logger.go) -- **ПрПблеЌа**: РаМее P/L рассчОтывался тПлькП как прПцеМт, пПлМПстью ОгМПрОруя разЌер пПзОцОО О плечП - - ПрОЌер: ППзОцОя 100 USDT с ЎПхПЎПЌ 5% О пПзОцОя 1000 USDT с ЎПхПЎПЌ 5% Пбе пПказывалО `5.0` как прОбыль - - ЭтП ЎелалП аМалОз прПОзвПЎОтельМПстО пПлМПстью МетПчМыЌ -- **РешеМОе**: Теперь рассчОтывается фактОческая прОбыль в USDT - ``` - P/L (USDT) = СтПОЌПсть пПзОцОО × ИзЌеМеМОе цеМы % × ПлечП - ПрОЌер: 1000 USDT × 5% × 20x = 1000 USDT фактОческПй прОбылО - ``` -- **ВлОяМОе**: ПрПцеМт выОгрышей, кПэффОцОеМт прОбылО О кПэффОцОеМт Карпа теперь ПсМПваМы Ма тПчМых суЌЌах USDT - -**2. ОтслежОваМОе пПзОцОй - ОтсутствОе крОтОческОх ЎаММых** -- **ПрПблеЌа**: ЗапОсО Пткрытых пПзОцОй храМОлО тПлькП цеМу О вреЌя, прПпуская кПлОчествП О плечП -- **РешеМОе**: Теперь храМОт пПлМые тПргПвые ЎаММые: - - `quantity`: РазЌер пПзОцОО (в ЌПМетах) - - `leverage`: ММПжОтель плеча (МапрОЌер, 20x) - - ЭтО ЎаММые МеПбхПЎОЌы Ўля тПчМПгП расчета P/L - -**3. ЛПгОка ключа пПзОцОО - КПМфлОкт Long/Short** -- **ПрПблеЌа**: ИспПльзПвался `symbol` как ключ пПзОцОО, чтП вызывалП кПМфлОкты ЎаММых прО ПЎМПвреЌеММПЌ уЎержаМОО лПМгПв О шПртПв - - ПрОЌер: BTCUSDT лПМг О BTCUSDT шПрт перезапОсывалО Ўруг Ўруга -- **РешеМОе**: ИзЌеМеМП Ма фПрЌат `symbol_side` (МапрОЌер, `BTCUSDT_long`, `BTCUSDT_short`) - - Теперь правОльМП разлОчает лПМг О шПрт пПзОцОО - -**4. Расчет кПэффОцОеМта Карпа - ОптОЌОзацОя кПЎа** -- **ПрПблеЌа**: ИспПльзПвался пПльзПвательскОй ЌетПЎ НьютПМа Ўля расчета кваЎратМПгП кПрМя -- **РешеМОе**: ЗаЌеМеМ Ма стаМЎартМую бОблОПтеку `math.Sqrt` - - БПлее МаЎежМый, пПЎЎержОваеЌый О эффектОвМый - -**ППчеЌу этП ПбМПвлеМОе важМП:** -- ✅ ИстПрОческая статОстОка сЎелПк теперь пПказывает **реальМую прОбыль/убытПк в USDT** вЌестП бессЌыслеММых прПцеМтПв -- ✅ СравМеМОе прПОзвПЎОтельМПстО ЌежЎу сЎелкаЌО с разМыЌ плечПЌ теперь тПчМП -- ✅ МехаМОзЌ саЌППбучеМОя AI пПлучает правОльМую ОстПрОческую ПбратМую связь -- ✅ Расчеты кПэффОцОеМта прОбылО О кПэффОцОеМта Карпа теперь ОЌеют сЌысл -- ✅ ОтслежОваМОе МескПлькОх пПзОцОй (лПМг + шПрт ПЎМПвреЌеММП) теперь рабПтает правОльМП - -**РекПЌеМЎацОя**: ЕслО вы запускалО сОстеЌу ЎП этПгП ПбМПвлеМОя, ваша ОстПрОческая статОстОка была МетПчМПй. ППсле ПбМПвлеМОя ЎП v2.0.2, МПвые сЎелкО буЎут рассчОтываться правОльМП. - -### v2.0.1 (2025-10-29) - -**ИсправлеМОя ПшОбПк:** -- ✅ ИсправлеМа лПгОка ПбрабПткО ЎаММых ComparisonChart - перехПЎ Пт группОрПвкО пП cycle_number к timestamp -- ✅ РешеМа прПблеЌа заЌПражОваМОя графОка прО перезапуске backend О сбрПсе cycle_number -- ✅ УлучшеМП ПтПбражеМОе ЎаММых графОка - теперь пПказывает все ОстПрОческОе тПчкО в хрПМПлПгОческПЌ пПряЎке -- ✅ УлучшеММые ПтлаЎПчМые лПгО Ўля лучшей ЎОагМПстОкО - -### v2.0.0 (2025-10-28) - -**ОсМПвМые ПбМПвлеМОя:** -- ✅ МехаМОзЌ саЌППбучеМОя AI (ОстПрОческОй аМалОз, аМалОз прПОзвПЎОтельМПстО) -- ✅ РежОЌ кПМкуреМцОО МескПлькОх трейЎерПв (Qwen vs DeepSeek) -- ✅ UI в стОле Binance (пПлМая ОЌОтацОя ОМтерфейса Binance) -- ✅ ГрафОкО сравМеМОя прПОзвПЎОтельМПстО (сравМеМОе ROI в реальМПЌ вреЌеМО) -- ✅ ОптОЌОзацОя кПМтрПля рОскПв (кПрректОрПвка лОЌОта пПзОцОО пП ЌПМетаЌ) - ---- - -**ППслеЎМее ПбМПвлеМОе**: 2025-10-29 (v2.0.2) +**НеЎавМОе ОсМПвМые МПЌеМты:** +- 🚀 ППлМая перерабПтка сОстеЌы с веб-кПМфОгурацОей +- 🗄 АрхОтектура Ма ПсМПве базы ЎаММых (SQLite) +- 🎚 НОкакПгП реЎактОрПваМОя JSON - вся кПМфОгурацОя через веб-ОМтерфейс +- 🔧 КПЌбОМОруйте AI ЌПЎелО с любПй бОржей +- 📊 РасшОреММый API слПй с кПЌплексМыЌО эМЎпПОМтаЌО +- 🔐 АутеМтОфОкацОя JWT + пПЎЎержка 2FA +- 🌐 ППЎЎержка кастПЌМых API (сПвЌестОЌых с OpenAI) +- 📈 СОстеЌа шаблПМПв прПЌптПв с уЎалеММПй аутеМтОфОкацОей **⚡ ИсслеЎуйте вПзЌПжМПстО кПлОчествеММПй тПргПвлО с сОлПй AI!** diff --git a/README.uk.md b/docs/i18n/uk/README.md similarity index 68% rename from README.uk.md rename to docs/i18n/uk/README.md index 0ec6d5df..19d506ef 100644 --- a/README.uk.md +++ b/docs/i18n/uk/README.md @@ -6,10 +6,30 @@ [![License](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE) [![Backed by Amber.ac](https://img.shields.io/badge/Backed%20by-Amber.ac-orange.svg)](https://amber.ac) -**МПвО / Languages:** [English](README.md) | [äž­æ–‡](README.zh-CN.md) | [УкраїМська](README.uk.md) | [РусскОй](README.ru.md) +**МПвО / Languages:** [English](../../../README.md) | [äž­æ–‡](../zh-CN/README.md) | [УкраїМська](../uk/README.md) | [РусскОй](../ru/README.md) **ОфіційМОй Twitter:** [@nofx_ai](https://x.com/nofx_ai) +**📚 ДПкуЌеМтація:** [ГПлПвМа](../../README.md) | [ППчатПк рПбПтО](../../getting-started/README.md) | [СпільМПта](../../community/README.md) | [ЖурМал ЗЌіМ](../../../CHANGELOG.md) + +--- + +## 📑 ЗЌіст + +- [🚀 УМіверсальМа AI ТПргПва ОпераційМа СОстеЌа](#-уМіверсальМа-ai-тПргПва-ПпераційМа-сОстеЌа) +- [👥 СпільМПта рПзрПбМОків](#-спільМПта-рПзрПбМОків) +- [🆕 ОстаММі ПМПвлеММя](#-ПстаММі-ПМПвлеММя) +- [🏗 ТехМічМа Архітектура](#-техМічМа-архітектура) +- [📞 СОстеЌМі СкріМшПтО](#-сОстеЌМі-скріМшПтО) +- [🎮 КвОЎкОй Старт](#-швОЎкОй-старт) +- [📊 AI МПЎель](#-ai-ЌПЎель) +- [📈 ОгляЎ ПрПЎуктОвМПсті](#-ПгляЎ-прПЎуктОвМПсті) +- [📄 ЛіцеМзія](#-ліцеМзія) +- [🀝 ВМесПк у прПєкт](#-вМесПк-у-прПєкт) +- [📬 КПМтактО](#-кПМтактО) +- [🙏 ППЎякО](#-пПЎякО) +- [🔄 ЖурМал ЗЌіМ](#-журМал-зЌіМ) + --- ## 🚀 УМіверсальМа AI ТПргПва ОпераційМа СОстеЌа @@ -74,7 +94,7 @@ NOFX тепер піЎтрОЌує **трО ПсМПвМі біржі**: Binance **КвОЎкОй старт:** 1. ОтрОЌайте прОватМОй ключ MetaMask (вОЎаліть префікс `0x`) -2. ВстаМПвіть `"exchange": "hyperliquid"` в config.json +2. ~~ВстаМПвіть `"exchange": "hyperliquid"` в config.json~~ *Налаштуйте через веб-іМтерфейс* 3. ДПЎайте `"hyperliquid_private_key": "your_key"` 4. ППчМіть тПргуватО! @@ -109,15 +129,19 @@ NOFX тепер піЎтрОЌує **трО ПсМПвМі біржі**: Binance ## 📞 СкрОМшПтО ### 🏆 РежОЌ зЌагаММя - БОтва AI в реальМПЌу часі -![СтПріМка зЌагаММя](screenshots/competition-page.png) +![СтПріМка зЌагаММя](../../../screenshots/competition-page.png) *ЛіЎербПрЎ з кількПЌа AI та графікО пПрівМяММя прПЎуктОвМПсті в реальМПЌу часі пПказують бОтву Qwen прПтО DeepSeek* ### 📊 Деталі трейЎера - ППвМа тПргПва паМель -![СтПріМка Ўеталей](screenshots/details-page.png) +![СтПріМка Ўеталей](../../../screenshots/details-page.png) *ПрПфесійМОй тПргПвОй іМтерфейс з крОвОЌО капіталу, жОвОЌО пПзОціяЌО та лПгаЌО рішеМь AI з рПзкрОваєЌОЌО вхіЎМОЌО прПЌптаЌО та лаМцюгПЌ ЌіркуваМь* --- +> 📘 **ПрОЌітка**: Ње спрПщеМа україМська версія README. Для ПтрОЌаММя пПвМПї техМічМПї ЎПкуЌеМтації, включаючО архітектуру сОстеЌО, API-іМтерфейсО та рПзшОреМі кПМфігурації, ЎОв. [АМглійську версію](../../../README.md) абП [КОтайську версію](../zh-CN/README.md). + +--- + ## ✹ ОсМПвМі ЌПжлОвПсті ### 🏆 РежОЌ зЌагаММя кількПх AI @@ -173,6 +197,57 @@ NOFX тепер піЎтрОЌує **трО ПсМПвМі біржі**: Binance --- +## 🔮 ДПрПжМя Карта - РПзшОреММя Ма УМіверсальМі РОМкО + +Місія NOFX - статО **УМіверсальМПю AI ТПргПвПю ОпераційМПю СОстеЌПю** Ўля всіх фіМаМсПвОх рОМків. + +**БачеММя:** Та саЌа архітектура. Та саЌа агеМтМа структура. Всі рОМкО. + +**РПзшОреММя Ма РОМкО:** +- 📈 **ЀПМЎПві РОМкО**: Акції СКА, A-акції, ГПМкПМгська біржа +- 📊 **РОМкО Ѐ'ючерсів**: ТПварМі ф'ючерсО, іМЎексМі ф'ючерсО +- 🎯 **ОпціПММа ТПргівля**: ОпціПМО Ма акції, крОптП ПпціПМО +- 💱 **РОМкО ЀПрекс**: ОсМПвМі валютМі парО, крПс-курсО + +**МайбутМі ЀуМкції:** +- РПзшОреМі AI ЌПжлОвПсті (GPT-4, Claude 3, Gemini Pro, гМучкі шаблПМО прПЌптів) +- НПві іМтеграції бірж (OKX, Bybit, Lighter, EdgeX + CEX/Perp-DEX) +- РефактПрОМг структурО прПєкту (вОсПка зв'язМість, МОзька зчеплеМість, прОМцОпО SOLID) +- ППкращеММя безпекО (AES-256 шОфруваММя API ключів, RBAC, пПкращеММя 2FA) +- ППкращеММя кПрОстувацькПгП ЎПсвіЎу (ЌПбільМОй іМтерфейс, графікО TradingView, сОстеЌа спПвіщеМь) + +📖 **Для ЎетальМПї ЎПрПжМьПї картО та терЌіМів ЎОв.:** +- **English:** [Roadmap Documentation](../../roadmap/README.md) +- **äž­æ–‡:** [路线囟文档](../../roadmap/README.zh-CN.md) + +--- + +## 🏗 ТехМічМа Архітектура + +NOFX пПбуЎПваМП Ма сучасМій ЌПЎульМій архітектурі: + +- **Backend:** Go з фрейЌвПркПЌ Gin, база ЎаМОх SQLite +- **Frontend:** React 18 + TypeScript + Vite + TailwindCSS +- **AI іМтеграція:** DeepSeek, Qwen, кастПЌМі API (суЌісМі з OpenAI) +- **ПіЎтрОЌка бірж:** Binance Futures, Hyperliquid DEX, Aster DEX +- **АутеМтОфікація:** JWT тПкеМО + піЎтрОЌка 2FA +- **УправліММя стаМПЌ:** Zustand (легкПвагПве) +- **ОтрОЌаММя ЎаМОх:** SWR з ПпОтуваММяЌ 5-10с +- **ГрафікО:** Recharts Ўля крОвОх капіталу та пПрівМяМь + +**КлючПві ПсПблОвПсті:** +- 🔧 Архітектура Ма ПсМПві базО ЎаМОх (кПМфігурація через веб-іМтерфейс, без JSON) +- 🎯 КПЌбіМуйте буЎь-яку AI ЌПЎель з буЎь-якПю біржею +- 📊 RESTful API з кПЌплексМОЌО еМЎпПіМтаЌО +- 🔐 БезпечМе управліММя ПблікПвОх ЎаМОх +- 📈 СОстеЌа шаблПМів прПЌптів з віЎЎалеМПю аутеМтОфікацією + +📖 **ДетальМа ЎПкуЌеМтація пП архітектурі:** +- **English:** [Architecture Documentation](../../architecture/README.md) +- **äž­æ–‡:** [架构文档](../../architecture/README.zh-CN.md) + +--- + ## 💰 Реєстрація акауМта Binance (ЗаПщаЎжуйте Ма кПЌісіях!) ПереЎ вОкПрОстаММяЌ цієї сОстеЌО ваЌ пПтрібеМ акауМт Binance Futures. **ВОкПрОстПвуйте Маше реферальМе пПсОлаММя Ўля ПтрОЌаММя зМОжкО Ма кПЌісії:** @@ -824,104 +899,73 @@ curl http://localhost:8080/api/health КПжеМ цОкл прОйМяття рішеМь (за заЌПвчуваММяЌ 3 хвОлОМО), сОстеЌа працює за МаступМОЌ прПцесПЌ: -``` -┌──────────────────────────────────────────────────────────┐ -│ 1. 📊 АМаліз істПрОчМПї прПЎуктОвМПсті │ -│ (ПстаММі 20 цОклів) │ -├─────────────────────────────────────────────────────────── -│ ✓ РПзрахуМПк загальМПгП віЎсПтка вОграшів, сереЎМьПгП │ -│ прОбутку, співвіЎМПшеММя прОбутку/збОтку │ -│ ✓ СтатОстОка пП кПжМій ЌПМеті (віЎсПтПк вОграшів, │ -│ сереЎМій P/L в USDT) │ -│ ✓ ВОзМачеММя МайкращОх/МайгіршОх ЌПМет за │ -│ прПЎуктОвМістю │ -│ ✓ СпОсПк Ўеталей ПстаММіх 5 угПЎ з тПчМОЌ P/L │ -│ ✓ РПзрахуМПк кПефіцієМта Карпа Ўля ПціМкО рОзОку │ -│ 📌 НОВЕ (v2.0.2): ТПчМОй P/L в USDT з врахуваММяЌ │ -│ плеча │ -└──────────────────────────────────────────────────────────┘ - ↓ -┌──────────────────────────────────────────────────────────┐ -│ 2. 💰 ОтрОЌаММя стаМу акауМта │ -├─────────────────────────────────────────────────────────── -│ • Капітал акауМта, ЎПступМОй балаМс, МереалізПваМОй │ -│ P/L │ -│ • Кількість пПзОцій, загальМОй P/L (реалізПваМОй + │ -│ МереалізПваМОй) │ -│ • ВОкПрОстаММя Ќаржі (пПтПчМе/ЌаксОЌальМе) │ -│ • ІМЎОкатПрО ПціМкО рОзОку │ -└──────────────────────────────────────────────────────────┘ - ↓ -┌──────────────────────────────────────────────────────────┐ -│ 3. 🔍 АМаліз ісМуючОх пПзОцій (якщП є) │ -├─────────────────────────────────────────────────────────── -│ • ОтрОЌаММя рОМкПвОх ЎаМОх Ўля кПжМПї пПзОції │ -│ (3-хвОлОММі + 4-гПЎОММі свічкО) │ -│ • РПзрахуМПк техМічМОх іМЎОкатПрів (RSI, MACD, EMA) │ -│ • ВіЎПбражеММя трОвалПсті утрОЌаММя пПзОції │ -│ (МапрОклаЎ, "утрОЌується 2 гПЎОМО 15 хвОлОМ") │ -│ • AI вОзМачає, чО пПтрібМП закрОтО (тейк-прПфіт, │ -│ стПп-лПсс абП кПрОгуваММя) │ -│ 📌 НОВЕ (v2.0.2): ВіЎстежеММя трОвалПсті пПзОції │ -│ ЎПпПЌагає AI вОрішуватО │ -└──────────────────────────────────────────────────────────┘ - ↓ -┌──────────────────────────────────────────────────────────┐ -│ 4. 🎯 ОціМка МПвОх ЌПжлОвПстей (пул каМЎОЎатів ЌПМет) │ -├─────────────────────────────────────────────────────────── -│ • ОтрОЌаММя тПп-20 ЌПМет з вОсПкОЌ рейтОМгПЌ AI500 │ -│ • ОтрОЌаММя тПп-20 ЌПМет з МайшвОЎшОЌ зрПстаММяЌ OI │ -│ • Об'єЎМаММя, вОЎалеММя Ўублікатів, фільтрація ЌПМет з │ -│ МОзькПю ліквіЎМістю (OI < 15M USD) │ -│ • МасПве ПтрОЌаММя рОМкПвОх ЎаМОх та техМічМОх │ -│ іМЎОкатПрів │ -│ • ПіЎгПтПвка пПвМОх пПсліЎПвМПстей сОрОх ЎаМОх Ўля │ -│ кПжМПї ЌПМетО-каМЎОЎата │ -└──────────────────────────────────────────────────────────┘ - ↓ -┌──────────────────────────────────────────────────────────┐ -│ 5. 🧠 КПЌплексМе рішеММя AI │ -├─────────────────────────────────────────────────────────── -│ • ПерегляЎ істПрОчМПгП звПрПтМПгП зв'язку (віЎсПтПк │ -│ вОграшів, кПефіцієМт P/L, Майкращі/Майгірші ЌПМетО) │ -│ • ОтрОЌаММя всіх ЎаМОх пПсліЎПвМПстей (свічкО, │ -│ іМЎОкатПрО, віЎкрОтОй іМтерес) │ -│ • АМаліз Chain of Thought │ -│ • ВОвіЎ рішеММя: закрОтО/віЎкрОтО/утрОЌуватО/спПстерігатО │ -│ • Включає параЌетрО плеча, рПзЌіру, стПп-лПсса, │ -│ тейк-прПфіта │ -│ 📌 НОВЕ (v2.0.2): AI ЌПже вільМП аМалізуватО сОрі │ -│ пПсліЎПвМПсті, Ме ПбЌежеМОй зазЎалегіЎь вОзМачеМОЌО │ -│ іМЎОкатПраЌО │ -└──────────────────────────────────────────────────────────┘ - ↓ -┌──────────────────────────────────────────────────────────┐ -│ 6. ⚡ ВОкПМаММя угПЎ │ -├─────────────────────────────────────────────────────────── -│ • ПріПрОтОзація: спПчатку закрОття, пПтіЌ віЎкрОття │ -│ • АвтПЌатОчМа аЎаптація тПчМПсті (правОла LOT_SIZE) │ -│ • ЗапПбігаММя МакПпОчеММю пПзОцій (віЎхОлеММя │ -│ ЎублюваММя ЌПМета/МапряЌПк) │ -│ • АвтПЌатОчМа віЎЌіМа всіх ПрЎерів після закрОття │ -│ • ЗапОс часу віЎкрОття Ўля віЎстежеММя трОвалПсті │ -│ пПзОції │ -│ 📌 НОВЕ (v2.0.2): ВіЎстежеММя часу віЎкрОття пПзОції │ -└──────────────────────────────────────────────────────────┘ - ↓ -┌──────────────────────────────────────────────────────────┐ -│ 7. 📝 ЗапОс лПгів │ -├─────────────────────────────────────────────────────────── -│ • ЗбережеММя пПвМПгП запОсу рішеММя в decision_logs/ │ -│ • Включає лаМцюг ЌіркуваМь, JSON рішеММя, зМіЌПк │ -│ акауМта, результатО вОкПМаММя │ -│ • ЗберігаММя пПвМОх ЎаМОх пПзОції (кількість, плече, │ -│ час віЎкрОття/закрОття) │ -│ • ВОкПрОстаММя ключів symbol_side Ўля запПбігаММя │ -│ кПМфліктів лПМг/шПрт │ -│ 📌 НОВЕ (v2.0.2): ЗапПбігаММя кПМфліктів прО утрОЌаММі │ -│ лПМг + шПрт, врахуваММя кількПсті + плеча │ -└──────────────────────────────────────────────────────────┘ -``` +### КрПк 1: 📊 АМаліз істПрОчМПї прПЎуктОвМПсті (ПстаММі 20 цОклів) +- ✓ РПзрахуМПк загальМПгП віЎсПтка вОграшів, сереЎМьПгП прОбутку, співвіЎМПшеММя прОбутку/збОтку +- ✓ СтатОстОка пП кПжМій ЌПМеті (віЎсПтПк вОграшів, сереЎМій P/L в USDT) +- ✓ ВОзМачеММя МайкращОх/МайгіршОх ЌПМет за прПЎуктОвМістю +- ✓ СпОсПк Ўеталей ПстаММіх 5 угПЎ з тПчМОЌ P/L +- ✓ РПзрахуМПк кПефіцієМта Карпа Ўля ПціМкО рОзОку +- 📌 **НОВЕ (v2.0.2)**: ТПчМОй P/L в USDT з врахуваММяЌ плеча + +**↓** + +### КрПк 2: 💰 ОтрОЌаММя стаМу акауМта +- Капітал акауМта, ЎПступМОй балаМс, МереалізПваМОй P/L +- Кількість пПзОцій, загальМОй P/L (реалізПваМОй + МереалізПваМОй) +- ВОкПрОстаММя Ќаржі (пПтПчМе/ЌаксОЌальМе) +- ІМЎОкатПрО ПціМкО рОзОку + +**↓** + +### КрПк 3: 🔍 АМаліз ісМуючОх пПзОцій (якщП є) +- ОтрОЌаММя рОМкПвОх ЎаМОх Ўля кПжМПї пПзОції (3-хвОлОММі + 4-гПЎОММі свічкО) +- РПзрахуМПк техМічМОх іМЎОкатПрів (RSI, MACD, EMA) +- ВіЎПбражеММя трОвалПсті утрОЌаММя пПзОції (МапрОклаЎ, "утрОЌується 2 гПЎОМО 15 хвОлОМ") +- AI вОзМачає, чО пПтрібМП закрОтО (тейк-прПфіт, стПп-лПсс абП кПрОгуваММя) +- 📌 **НОВЕ (v2.0.2)**: ВіЎстежеММя трОвалПсті пПзОції ЎПпПЌагає AI вОрішуватО + +**↓** + +### КрПк 4: 🎯 ОціМка МПвОх ЌПжлОвПстей (пул каМЎОЎатів ЌПМет) +- ОтрОЌаММя пулу ЌПМет (2 режОЌО): + - 🌟 **РежОЌ за заЌПвчуваММяЌ**: BTC, ETH, SOL, BNB, XRP тПщП + - ⚙ **РПзшОреМОй режОЌ**: AI500 (тПп-20) + OI Top (тПп-20) +- Об'єЎМаММя, вОЎалеММя Ўублікатів, фільтрація ЌПМет з МОзькПю ліквіЎМістю (OI < 15M USD) +- МасПве ПтрОЌаММя рОМкПвОх ЎаМОх та техМічМОх іМЎОкатПрів +- ПіЎгПтПвка пПвМОх пПсліЎПвМПстей сОрОх ЎаМОх Ўля кПжМПї ЌПМетО-каМЎОЎата + +**↓** + +### КрПк 5: 🧠 КПЌплексМе рішеММя AI +- ПерегляЎ істПрОчМПгП звПрПтМПгП зв'язку (віЎсПтПк вОграшів, кПефіцієМт P/L, Майкращі/Майгірші ЌПМетО) +- ОтрОЌаММя всіх ЎаМОх пПсліЎПвМПстей (свічкО, іМЎОкатПрО, віЎкрОтОй іМтерес) +- АМаліз Chain of Thought +- ВОвіЎ рішеММя: закрОтО/віЎкрОтО/утрОЌуватО/спПстерігатО +- Включає параЌетрО плеча, рПзЌіру, стПп-лПсса, тейк-прПфіта +- 📌 **НОВЕ (v2.0.2)**: AI ЌПже вільМП аМалізуватО сОрі пПсліЎПвМПсті, Ме ПбЌежеМОй зазЎалегіЎь вОзМачеМОЌО іМЎОкатПраЌО + +**↓** + +### КрПк 6: ⚡ ВОкПМаММя угПЎ +- ПріПрОтОзація: спПчатку закрОття, пПтіЌ віЎкрОття +- АвтПЌатОчМа аЎаптація тПчМПсті (правОла LOT_SIZE) +- ЗапПбігаММя МакПпОчеММю пПзОцій (віЎхОлеММя ЎублюваММя ЌПМета/МапряЌПк) +- АвтПЌатОчМа віЎЌіМа всіх ПрЎерів після закрОття +- ЗапОс часу віЎкрОття Ўля віЎстежеММя трОвалПсті пПзОції +- 📌 ВіЎстежеММя часу віЎкрОття пПзОції + +**↓** + +### КрПк 7: 📝 ЗапОс лПгів +- ЗбережеММя пПвМПгП запОсу рішеММя в `decision_logs/` +- Включає лаМцюг ЌіркуваМь, JSON рішеММя, зМіЌПк акауМта, результатО вОкПМаММя +- ЗберігаММя пПвМОх ЎаМОх пПзОції (кількість, плече, час віЎкрОття/закрОття) +- ВОкПрОстаММя ключів `symbol_side` Ўля запПбігаММя кПМфліктів лПМг/шПрт +- 📌 **НОВЕ (v2.0.2)**: ЗапПбігаММя кПМфліктів прО утрОЌаММі лПМг + шПрт, врахуваММя кількПсті + плеча + +**↓** + +**🔄 (ППвтПр кПжМі 3-5 хвОлОМ)** ### КлючПві пПкращеММя в v2.0.2 @@ -950,6 +994,7 @@ curl http://localhost:8080/api/health ## ⚠ ВажлОві пПпереЎжеММя прП рОзОкО ### ТПргПвельМі рОзОкО +``` { "id": "qwen_trader", "name": "Qwen AI Trader", @@ -1013,6 +1058,7 @@ npm run dev ``` **ДПступ ЎП іМтерфейсу:** + ``` Веб-паМель: http://localhost:3000 API сервер: http://localhost:8080 @@ -1024,184 +1070,26 @@ API сервер: http://localhost:8080 --- -## ⚠ ВажлОві пПпереЎжеММя прП рОзОкО - -### ТПргПвельМі рОзОкО - -1. **РОМкО крОптПвалют МаЎзвОчайМП вПлатОльМі**, рішеММя AI Ме гараМтують прОбутПк -2. **ТПргівля ф'ючерсаЌО вОкПрОстПвує плече**, збОткО ЌПжуть перевОщОтО ПсМПвМу суЌу -3. **ЕкстреЌальМі рОМкПві уЌПвО** ЌПжуть прОзвестО ЎП ліквіЎації -4. **КПЌісії за фіМаМсуваММя** ЌПжуть вплОМутО Ма вартість утрОЌаММя -5. **РОзОк ліквіЎМПсті**: Деякі ЌПМетО ЌПжуть віЎчуватО прПкПвзуваММя - -### ТехМічМі рОзОкО - -1. **ЗатрОЌка Ќережі** ЌПже вОклОкатО прПкПвзуваММя ціМО -2. **ЛіЌітО API** ЌПжуть вплОМутО Ма вОкПМаММя угПЎ -3. **ТайЌ-аутО AI API** ЌПжуть вОклОкатО збПї рішеМь -4. **СОстеЌМі пПЌОлкО** ЌПжуть вОклОкатО МеПчікуваМу пПвеЎіМку - -### РекПЌеМЎації щПЎП вОкПрОстаММя - -✅ **РекПЌеМЎується** -- ВОкПрОстПвуйте лОше кПштО, втрату якОх вО ЌПжете ЎПзвПлОтО Ўля тестуваММя -- ППчМіть з МевелОкОх суЌ (рекПЌеМЎується 100-500 USDT) -- РегулярМП перевіряйте стаМ рПбПтО сОстеЌО -- ВіЎстежуйте зЌіМО балаМсу рахуМку -- АМалізуйте лПгО рішеМь AI Ўля рПзуЌіММя стратегії - -❌ **Не рекПЌеМЎується** -- ІМвестуватО всі кПштО абП пПзОчеМі грПші -- ЗапускатО без МагляЎу Ма трОвалі періПЎО -- СліпП ЎПвірятО рішеММяЌ AI -- ВОкПрОстПвуватО без рПзуЌіММя сОстеЌО -- ЗапускатО піЎ час екстреЌальМПї вПлатОльМПсті рОМку - --- -## 🛠 Часті прПблеЌО +## 🔄 ЖурМал ЗЌіМ -### 1. ППЌОлка кПЌпіляції: TA-Lib Ме зМайЎеМа +📖 **Для ЎетальМПї істПрії версій та ПМПвлеМь ЎОв.:** -**РішеММя**: ВстаМПвіть бібліПтеку TA-Lib -```bash -# macOS -brew install ta-lib +- **УкраїМська:** [CHANGELOG.zh-CN.md](../../../CHANGELOG.zh-CN.md) +- **English:** [CHANGELOG.md](../../../CHANGELOG.md) -# Ubuntu -sudo apt-get install libta-lib0-dev -``` +**ОстаММя Версія:** v3.0.0 (2025-10-30) - МасштабМа ТраМсфПрЌація АрхітектурО -### 2. ППЌОлка тПчМПсті: ТПчМість перевОщує ЌаксОЌуЌ - -**РішеММя**: СОстеЌа автПЌатОчМП ПбрПбляє тПчМість з Binance LOT_SIZE. ЯкщП пПЌОлка зберігається, перевірте Ќережеве піЎключеММя. - -### 3. ТайЌ-аут AI API - -**РішеММя**: -- Перевірте правОльМість API ключа -- Перевірте Ќережеве піЎключеММя (ЌПже зМаЎПбОтОся прПксі) -- ТайЌ-аут сОстеЌО встаМПвлеМП Ма 120 секуМЎ - -### 4. Frontend Ме ЌПже піЎключОтОся ЎП backend - -**РішеММя**: -- ПерекПМайтеся, щП backend запущеМП (http://localhost:8080) -- Перевірте, чО Ме зайМятОй пПрт 8080 -- Перевірте пПЌОлкО в кПМсПлі браузера - -### 5. Збій API пулу ЌПМет - -**РішеММя**: -- API пулу ЌПМет ПпціПМалеМ -- ЯкщП API Ме працює, сОстеЌа вОкПрОстПвує ПсМПвМі ЌПМетО за заЌПвчуваММяЌ (BTC, ETH тПщП) -- Перевірте URL API та параЌетр auth в config.json - ---- - -## 📄 ЛіцеМзія - -ЛіцеМзія MIT - ДОв. файл [LICENSE](LICENSE) Ўля Ўеталей - ---- - -## 🀝 ВМесПк у прПєкт - -Вітаються Issues та Pull Requests! - -### КерівМОцтвП з рПзрПбкО - -1. ЗрПбіть Fork прПєкту -2. СтвПріть гілку фуМкції (`git checkout -b feature/AmazingFeature`) -3. Зафіксуйте зЌіМО (`git commit -m 'Add some AmazingFeature'`) -4. НаЎішліть ЎП гілкО (`git push origin feature/AmazingFeature`) -5. ВіЎкрОйте Pull Request - ---- - -## 📬 КПМтактО - -- **Twitter/X**: [@Web3Tinkle](https://x.com/Web3Tinkle) -- **GitHub Issues**: [СтвПрОтО Issue](https://github.com/tinkle-community/nofx/issues) - ---- - -## 🙏 ППЎякО - -- [Binance API](https://binance-docs.github.io/apidocs/futures/en/) - Binance Futures API -- [DeepSeek](https://platform.deepseek.com/) - DeepSeek AI API -- [Qwen](https://dashscope.aliyuncs.com/) - Alibaba Cloud Qwen -- [TA-Lib](https://ta-lib.org/) - БібліПтека техМічМОх іМЎОкатПрів -- [Recharts](https://recharts.org/) - БібліПтека графіків React - ---- - -## 🔄 ІстПрія зЌіМ - -### v2.0.2 (2025-10-29) - -**КрОтОчМі вОправлеММя пПЌОлПк - ІстПрія угПЎ та аМаліз прПЎуктОвМПсті:** - -Њя версія вОправляє **крОтОчМі пПЌОлкО рПзрахуМку** в сОстеЌі істПрОчМОх запОсів угПЎ та аМалізу прПЎуктОвМПсті, які зМачМП вплОвалО Ма статОстОку прОбуткПвПсті. - -**1. РПзрахуМПк P/L - ВОправлеММя велОкПї пПЌОлкО** (logger/decision_logger.go) -- **ПрПблеЌа**: РаМіше P/L рПзрахПвувався лОше як віЎсПтПк, пПвМістю ігМПруючО рПзЌір пПзОції та плече - - ПрОклаЎ: ППзОція 100 USDT з ЎПхПЎПЌ 5% та пПзОція 1000 USDT з ЎПхПЎПЌ 5% ПбОЎві пПказувалО `5.0` як прОбутПк - - Ње рПбОлП аМаліз прПЎуктОвМПсті пПвМістю МетПчМОЌ -- **РішеММя**: Тепер рПзрахПвується фактОчМОй прОбутПк в USDT - ``` - P/L (USDT) = Вартість пПзОції × ЗЌіМа ціМО % × Плече - ПрОклаЎ: 1000 USDT × 5% × 20x = 1000 USDT фактОчМПгП прОбутку - ``` -- **ВплОв**: ВіЎсПтПк вОграшів, кПефіцієМт прОбутку та кПефіцієМт Карпа тепер засМПваМі Ма тПчМОх суЌах USDT - -**2. ВіЎстежеММя пПзОцій - ВіЎсутМість крОтОчМОх ЎаМОх** -- **ПрПблеЌа**: ЗапОсО віЎкрОтОх пПзОцій зберігалО лОше ціМу та час, прПпускаючО кількість та плече -- **РішеММя**: Тепер зберігає пПвМі тПргПві ЎаМі: - - `quantity`: РПзЌір пПзОції (в ЌПМетах) - - `leverage`: ММПжМОк плеча (МапрОклаЎ, 20x) - - Њі ЎаМі МеПбхіЎМі Ўля тПчМПгП рПзрахуМку P/L - -**3. ЛПгіка ключа пПзОції - КПМфлікт Long/Short** -- **ПрПблеЌа**: ВОкПрОстПвувався `symbol` як ключ пПзОції, щП вОклОкалП кПМфліктО ЎаМОх прО ПЎМПчасМПЌу утрОЌаММі лПМгів та шПртів - - ПрОклаЎ: BTCUSDT лПМг та BTCUSDT шПрт перезапОсувалО ПЎОМ ПЎМПгП -- **РішеММя**: ЗЌіМеМП Ма фПрЌат `symbol_side` (МапрОклаЎ, `BTCUSDT_long`, `BTCUSDT_short`) - - Тепер правОльМП рПзрізМяє лПМг та шПрт пПзОції - -**4. РПзрахуМПк кПефіцієМта Карпа - ОптОЌізація кПЎу** -- **ПрПблеЌа**: ВОкПрОстПвувався кПрОстувацькОй ЌетПЎ НьютПМа Ўля рПзрахуМку кваЎратМПгП кПреМя -- **РішеММя**: ЗаЌіМеМП Ма стаМЎартМу бібліПтеку `math.Sqrt` - - Більш МаЎійМОй, піЎтрОЌуваМОй та ефектОвМОй - -**ЧПЌу це ПМПвлеММя важлОве:** -- ✅ ІстПрОчМа статОстОка угПЎ тепер пПказує **реальМОй прОбутПк/збОтПк в USDT** заЌість безглузЎОх віЎсПтків -- ✅ ППрівМяММя прПЎуктОвМПсті Ќіж угПЎаЌО з різМОЌ плечеЌ тепер тПчМе -- ✅ МехаМізЌ саЌПМавчаММя AI ПтрОЌує правОльМОй істПрОчМОй звПрПтМОй зв'язПк -- ✅ РПзрахуМкО кПефіцієМта прОбутку та кПефіцієМта Карпа тепер Ќають сеМс -- ✅ ВіЎстежеММя кількПх пПзОцій (лПМг + шПрт ПЎМПчасМП) тепер працює правОльМП - -**РекПЌеМЎація**: ЯкщП вО запускалО сОстеЌу ЎП цьПгП ПМПвлеММя, ваша істПрОчМа статОстОка була МетПчМПю. Після ПМПвлеММя ЎП v2.0.2, МПві угПЎО буЎуть рПзрахПвуватОся правОльМП. - -### v2.0.1 (2025-10-29) - -**ВОправлеММя пПЌОлПк:** -- ✅ ВОправлеМП лПгіку ПбрПбкО ЎаМОх ComparisonChart - перехіЎ віЎ групуваММя пП cycle_number ЎП timestamp -- ✅ ВОрішеМП прПблеЌу заЌПрПжуваММя графіка прО перезапуску backend та скОЎаММі cycle_number -- ✅ ППкращеМП віЎПбражеММя ЎаМОх графіка - тепер пПказує всі істПрОчМі тПчкО в хрПМПлПгічМПЌу пПряЎку -- ✅ ППкращеМі віЎлаЎПчМі лПгО Ўля кращПї ЎіагМПстОкО - -### v2.0.0 (2025-10-28) - -**ОсМПвМі ПМПвлеММя:** -- ✅ МехаМізЌ саЌПМавчаММя AI (істПрОчМОй аМаліз, аМаліз прПЎуктОвМПсті) -- ✅ РежОЌ зЌагаММя кількПх трейЎерів (Qwen vs DeepSeek) -- ✅ UI в стОлі Binance (пПвМа іЌітація іМтерфейсу Binance) -- ✅ ГрафікО пПрівМяММя прПЎуктОвМПсті (пПрівМяММя ROI в реальМПЌу часі) -- ✅ ОптОЌізація кПМтрПлю рОзОків (кПрОгуваММя ліЌіту пПзОції пП ЌПМетах) - ---- - -**ОстаММє ПМПвлеММя**: 2025-10-29 (v2.0.2) +**НеЎавМі ОсМПвМі МПЌеМтО:** +- 🚀 ППвМа перерПбка сОстеЌО з веб-кПМфігурацією +- 🗄 Архітектура Ма ПсМПві базО ЎаМОх (SQLite) +- 🎚 НіякПгП реЎагуваММя JSON - вся кПМфігурація через веб-іМтерфейс +- 🔧 КПЌбіМуйте AI ЌПЎелі з буЎь-якПю біржею +- 📊 РПзшОреМОй API шар з кПЌплексМОЌО еМЎпПіМтаЌО +- 🔐 АутеМтОфікація JWT + піЎтрОЌка 2FA +- 🌐 ПіЎтрОЌка кастПЌМОх API (суЌісМОх з OpenAI) +- 📈 СОстеЌа шаблПМів прПЌптів з віЎЎалеМПю аутеМтОфікацією **⚡ ДПсліЎжуйте ЌПжлОвПсті кількісМПї тПргівлі з сОлПю AI!** diff --git a/README.zh-CN.md b/docs/i18n/zh-CN/README.md similarity index 71% rename from README.zh-CN.md rename to docs/i18n/zh-CN/README.md index 75be2f64..29d69c8e 100644 --- a/README.zh-CN.md +++ b/docs/i18n/zh-CN/README.md @@ -6,10 +6,38 @@ [![License](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE) [![Backed by Amber.ac](https://img.shields.io/badge/Backed%20by-Amber.ac-orange.svg)](https://amber.ac) -**语蚀 / Languages:** [English](README.md) | [äž­æ–‡](README.zh-CN.md) | [УкраїМська](README.uk.md) | [РусскОй](README.ru.md) +**语蚀 / Languages:** [English](../../../README.md) | [äž­æ–‡](../zh-CN/README.md) | [УкраїМська](../uk/README.md) | [РусскОй](../ru/README.md) **官方掚特:** [@nofx_ai](https://x.com/nofx_ai) +**📚 文档䞭心:** [文档銖页](../../README.md) | [快速匀始](../../getting-started/README.zh-CN.md) | [曎新日志](../../../CHANGELOG.zh-CN.md) | [瀟区指南](../../community/README.md) + +--- + +## 📑 目圕 + +- [🚀 通甹AI亀易操䜜系统](#-通甹ai亀易操䜜系统) +- [👥 匀发者瀟区](#-匀发者瀟区) +- [🆕 最新曎新](#-最新曎新) +- [📞 系统截囟](#-系统截囟) +- [✹ 圓前实现](#-圓前实现---加密莧垁垂场) +- [🔮 路线囟](#-路线囟---通甚垂场扩展) +- [🏗 技术架构](#-技术架构) +- [💰 泚册垁安莊户](#-泚册垁安莊户省手续莹) +- [🚀 快速匀始](#-快速匀始) +- [📖 AI决策流皋](#-ai决策流皋) +- [🧠 AI自我孊习瀺䟋](#-ai自我孊习瀺䟋) +- [📊 Web界面功胜](#-web界面功胜) +- [🎛 API接口](#-api接口) +- [📝 决策日志栌匏](#-决策日志栌匏) +- [🔧 风险控制诊解](#-风险控制诊解) +- [⚠ 重芁风险提瀺](#-重芁风险提瀺) +- [🛠 垞见问题](#-垞见问题) +- [📈 性胜䌘化建议](#-性胜䌘化建议) +- [🔄 曎新日志](#-曎新日志) +- [📄 匀源协议](#-匀源协议) +- [🀝 莡献指南](#-莡献指南) + --- ## 🚀 通甹AI亀易操䜜系统 @@ -109,11 +137,11 @@ NOFX现已支持**䞉倧亀易所**Binance、Hyperliquid和Aster DEX ## 📞 系统截囟 ### 🏆 竞赛暡匏 - AI实时对战 -![竞赛页面](screenshots/competition-page.png) +![竞赛页面](../../../screenshots/competition-page.png) *倚AI排行抜和实时性胜对比囟衚展瀺Qwen vs DeepSeek实时亀易对战* ### 📊 亀易诊情 - 完敎亀易仪衚盘 -![诊情页面](screenshots/details-page.png) +![诊情页面](../../../screenshots/details-page.png) *䞓䞚亀易界面包含权益曲线、实时持仓、AI决策日志支持展匀查看蟓入提瀺词和AI思绎铟掚理过皋* --- @@ -168,78 +196,50 @@ NOFX 目前已圚**加密莧垁垂场党面运行**具倇以䞋经过验证 ## 🔮 路线囟 - 通甚垂场扩展 -我们经过验证的加密莧垁基础讟斜正圚扩展到 +NOFX 的䜿呜是成䞺所有金融垂场的**通甹 AI 亀易操䜜系统**。 -- **📈 股祚垂场**矎股、A股、枯股 -- **📊 期莧垂场**商品期莧、指数期莧 -- **🎯 期权亀易**股祚期权、加密期权 -- **💱 倖汇垂场**䞻芁莧垁对、亀叉盘 +**愿景** 盞同架构。盞同智胜䜓框架。所有垂场。 -**盞同架构。盞同智胜䜓框架。所有垂场。** +**扩展垂场** +- 📈 **股祚垂场**矎股、A股、枯股 +- 📊 **期莧垂场**商品期莧、指数期莧 +- 🎯 **期权亀易**股祚期权、加密期权 +- 💱 **倖汇垂场**䞻芁莧垁对、亀叉盘 + +**即将掚出的功胜** +- 增区AI胜力GPT-4、Claude 3、Gemini Pro、灵掻prompt暡板 +- 新亀易所集成OKX、Bybit、Lighter、EdgeX + CEX/Perp-DEX +- 项目结构重构高内聚䜎耊合、SOLID原则 +- 安党性增区API密钥AES-256加密、RBAC、2FA改进 +- 甚户䜓验改进移劚端响应匏、TradingView囟衚、告譊系统 + +📖 **诊细路线囟和时闎衚请参阅** +- **äž­æ–‡:** [路线囟文档](../../roadmap/README.zh-CN.md) +- **English:** [Roadmap Documentation](../../roadmap/README.md) --- ## 🏗 技术架构 -``` -nofx/ -├── main.go # 皋序入口倚trader管理噚 -├── config.json # 配眮文件API密钥、~~倚trader配眮~~(亀易员配眮通过Web界面) -│ -├── api/ # HTTP API服务 -│ └── server.go # Gin框架RESTful API -│ -├── trader/ # 亀易栞心 -│ ├── auto_trader.go # 自劚亀易䞻控单trader -│ └── binance_futures.go # 垁安合纊API封装 -│ -├── manager/ # 倚trader管理 -│ └── trader_manager.go # 管理倚䞪trader实䟋 -│ -├── mcp/ # Model Context Protocol - AI通信 -│ └── client.go # AI API客户端DeepSeek/Qwen集成 -│ -├── decision/ # AI决策匕擎 -│ └── engine.go # 决策逻蟑含历史反銈 -│ -├── market/ # 垂场数据获取 -│ └── data.go # 垂场数据䞎技术指标K线、RSI、MACD -│ -├── pool/ # 垁种池管理 -│ └── coin_pool.go # AI500 + OI Top合并池 -│ -├── logger/ # 日志系统 -│ └── decision_logger.go # 决策记圕 + 衚现分析 -│ -├── decision_logs/ # 决策日志存傚 -│ ├── qwen_trader/ # Qwen trader日志 -│ └── deepseek_trader/ # DeepSeek trader日志 -│ -└── web/ # React前端 - ├── src/ - │ ├── components/ # React组件 - │ │ ├── EquityChart.tsx # 收益率曲线囟 - │ │ ├── ComparisonChart.tsx # 倚AI对比囟 - │ │ └── CompetitionPage.tsx # 竞赛排行抜 - │ ├── lib/api.ts # API调甚封装 - │ ├── types/index.ts # TypeScript类型 - │ ├── index.css # Binance风栌样匏 - │ └── App.tsx # 䞻应甚 - └── package.json -``` +NOFX 采甚现代化的暡块化架构 -### 栞心䟝赖 +- **后端** Go + Gin 框架SQLite 数据库 +- **前端** React 18 + TypeScript + Vite + TailwindCSS +- **倚亀易所支持** Binance、Hyperliquid、Aster DEX +- **AI 集成** DeepSeek、Qwen 及自定义 OpenAI 兌容 API +- **状态管理** 前端 Zustand后端数据库驱劚 +- **实时曎新** SWR5-10 秒蜮询闎隔 -**后端 (Go)** -- `github.com/adshao/go-binance/v2` - 垁安API客户端 -- `github.com/markcheno/go-talib` - 技术指标计算TA-Lib -- `github.com/gin-gonic/gin` - HTTP API框架 +**栞心特性** +- 🗄 数据库驱劚的配眮无需猖蟑 JSON +- 🔐 JWT 讀证支持可选的 2FA +- 📊 实时性胜跟螪和分析 +- 🀖 倚 AI 竞赛暡匏实时对比 +- 🔌 RESTful API完敎的配眮和监控 -**前端 (React + TypeScript)** -- `react` + `react-dom` - UI框架 -- `recharts` - 囟衚库收益率曲线、对比囟 -- `swr` - 数据获取和猓存 -- `tailwindcss` - CSS框架 +📖 **诊细架构文档请查看** +- **䞭文版** [架构文档](../../architecture/README.zh-CN.md) +- **English:** [Architecture Documentation](../../architecture/README.md) --- @@ -420,9 +420,9 @@ cd .. ~~**步骀1**倍制并重呜名瀺䟋配眮文件~~ -~~```bash +```bash cp config.example.jsonc config.json -```~~ +``` ~~**步骀2**猖蟑`config.json`填入悚的API密钥~~ @@ -897,79 +897,73 @@ curl http://localhost:8080/api/health 每䞪决策呚期默讀3分钟系统按以䞋流皋运行 -``` -┌──────────────────────────────────────────────────────────┐ -│ 1. 📊 分析历史衚现最近20䞪呚期 │ -├─────────────────────────────────────────────────────────── -│ ✓ 计算敎䜓胜率、平均盈利、盈亏比 │ -│ ✓ 统计各垁种衚现胜率、平均USDT盈亏 │ -│ ✓ 识别最䜳/最差垁种 │ -│ ✓ 列出最近5笔亀易诊情含准确盈亏金额 │ -│ ✓ 计算倏普比率衡量风险调敎后收益 │ -│ 📌 新增 (v2.0.2): 考虑杠杆的准确USDT盈亏计算 │ -└──────────────────────────────────────────────────────────┘ - ↓ -┌──────────────────────────────────────────────────────────┐ -│ 2. 💰 获取莊户状态 │ -├─────────────────────────────────────────────────────────── -│ • 莊户净倌、可甚䜙额、未实现盈亏 │ -│ • 持仓数量、总盈亏已实现+未实现 │ -│ • 保证金䜿甚率current/maximum │ -│ • 风险评䌰指标 │ -└──────────────────────────────────────────────────────────┘ - ↓ -┌──────────────────────────────────────────────────────────┐ -│ 3. 🔍 分析现有持仓劂果有 │ -├─────────────────────────────────────────────────────────── -│ • 获取每䞪持仓的垂场数据3分钟+4小时K线 │ -│ • 计算技术指标RSI、MACD、EMA │ -│ • 星瀺持仓时长䟋劂"持仓时长2小时15分钟" │ -│ • AI刀断是吊需芁平仓止盈、止损或调敎 │ -│ 📌 新增 (v2.0.2): 远螪持仓时长垮助AI决策 │ -└──────────────────────────────────────────────────────────┘ - ↓ -┌──────────────────────────────────────────────────────────┐ -│ 4. 🎯 评䌰新机䌚候选垁种池 │ -├─────────────────────────────────────────────────────────── -│ • 获取AI500高评分垁种前20䞪 │ -│ • 获取OI Top持仓增长垁种前20䞪 │ -│ • 合并去重过滀䜎流劚性垁种持仓量<15M USD │ -│ • 批量获取垂场数据和技术指标 │ -│ • 䞺每䞪候选垁种准倇完敎的原始数据序列 │ -└──────────────────────────────────────────────────────────┘ - ↓ -┌──────────────────────────────────────────────────────────┐ -│ 5. 🧠 AI绌合决策 │ -├─────────────────────────────────────────────────────────── -│ • 查看历史反銈胜率、盈亏比、最䜳/最差垁种 │ -│ • 接收所有原始序列数据K线、指标、持仓量 │ -│ • Chain of Thought 思绎铟分析 │ -│ • 蟓出决策平仓/匀仓/持有/观望 │ -│ • 包含杠杆、仓䜍、止损、止盈参数 │ -│ 📌 新增 (v2.0.2): AI可自由分析原始序列䞍受预定义指标限制 │ -└──────────────────────────────────────────────────────────┘ - ↓ -┌──────────────────────────────────────────────────────────┐ -│ 6. ⚡ 执行亀易 │ -├─────────────────────────────────────────────────────────── -│ • 䌘先级排序先平仓再匀仓 │ -│ • 粟床自劚适配LOT_SIZE规则 │ -│ • 防止仓䜍叠加同垁种同方向拒绝匀仓 │ -│ • 平仓后自劚取消所有挂单 │ -│ • 记圕匀仓时闎甚于持仓时长远螪 │ -│ 📌 新增 (v2.0.2): 远螪持仓匀仓时闎 │ -└──────────────────────────────────────────────────────────┘ - ↓ -┌──────────────────────────────────────────────────────────┐ -│ 7. 📝 记圕日志 │ -├─────────────────────────────────────────────────────────── -│ • 保存完敎决策记圕到 decision_logs/ │ -│ • 包含思绎铟、决策JSON、莊户快照、执行结果 │ -│ • 存傚完敎持仓数据数量、杠杆、匀/平仓时闎 │ -│ • 䜿甚symbol_side键倌防止倚空冲突 │ -│ 📌 新增 (v2.0.2): 防止倚空持仓冲突考虑数量+杠杆 │ -└──────────────────────────────────────────────────────────┘ -``` +### 步骀1: 📊 分析历史衚现最近20䞪呚期 +- ✓ 计算敎䜓胜率、平均盈利、盈亏比 +- ✓ 统计各垁种衚现胜率、平均USDT盈亏 +- ✓ 识别最䜳/最差垁种 +- ✓ 列出最近5笔亀易诊情含准确盈亏金额 +- ✓ 计算倏普比率衡量风险调敎后收益 +- 📌 **新增 (v2.0.2)**: 考虑杠杆的准确USDT盈亏计算 + +**↓** + +### 步骀2: 💰 获取莊户状态 +- 莊户净倌、可甚䜙额、未实现盈亏 +- 持仓数量、总盈亏已实现+未实现 +- 保证金䜿甚率current/maximum +- 风险评䌰指标 + +**↓** + +### 步骀3: 🔍 分析现有持仓劂果有 +- 获取每䞪持仓的垂场数据3分钟+4小时K线 +- 计算技术指标RSI、MACD、EMA +- 星瀺持仓时长䟋劂"持仓时长2小时15分钟" +- AI刀断是吊需芁平仓止盈、止损或调敎 +- 📌 **新增 (v2.0.2)**: 远螪持仓时长垮助AI决策 + +**↓** + +### 步骀4: 🎯 评䌰新机䌚候选垁种池 +- 获取垁种池2种暡匏 + - 🌟 **默讀暡匏**: BTC、ETH、SOL、BNB、XRP等 + - ⚙ **高级暡匏**: AI500前20 + OI Top前20 +- 合并去重过滀䜎流劚性垁种持仓量<15M USD +- 批量获取垂场数据和技术指标 +- 䞺每䞪候选垁种准倇完敎的原始数据序列 + +**↓** + +### 步骀5: 🧠 AI绌合决策 +- 查看历史反銈胜率、盈亏比、最䜳/最差垁种 +- 接收所有原始序列数据K线、指标、持仓量 +- Chain of Thought 思绎铟分析 +- 蟓出决策平仓/匀仓/持有/观望 +- 包含杠杆、仓䜍、止损、止盈参数 +- 📌 **新增 (v2.0.2)**: AI可自由分析原始序列䞍受预定义指标限制 + +**↓** + +### 步骀6: ⚡ 执行亀易 +- 䌘先级排序先平仓再匀仓 +- 粟床自劚适配LOT_SIZE规则 +- 防止仓䜍叠加同垁种同方向拒绝匀仓 +- 平仓后自劚取消所有挂单 +- 记圕匀仓时闎甚于持仓时长远螪 +- 📌 远螪持仓匀仓时闎 + +**↓** + +### 步骀7: 📝 记圕日志 +- 保存完敎决策记圕到 `decision_logs/` +- 包含思绎铟、决策JSON、莊户快照、执行结果 +- 存傚完敎持仓数据数量、杠杆、匀/平仓时闎 +- 䜿甚 `symbol_side` 键倌防止倚空冲突 +- 📌 **新增 (v2.0.2)**: 防止倚空持仓冲突考虑数量+杠杆 + +**↓** + +**🔄 每3-5分钟重倍䞀次** ### v2.0.2的栞心改进 @@ -1248,77 +1242,19 @@ sudo apt-get install libta-lib0-dev ## 🔄 曎新日志 -### v2.0.2 (2025-10-29) +📖 **诊细的版本历史和曎新请查看** -**关键Bug修倍 - 亀易历史记圕䞎性胜分析** +- **䞭文版** [CHANGELOG.zh-CN.md](../../../CHANGELOG.zh-CN.md) +- **English:** [CHANGELOG.md](../../../CHANGELOG.md) -本版本修倍了历史亀易记圕和性胜分析系统䞭的**䞥重计算错误**这些错误䞥重圱响了盈利统计的准确性。 +**最新版本** v3.0.0 (2025-10-30) - 重倧架构变革 -**1. 盈亏计算 - 重倧错误修倍** (logger/decision_logger.go) -- **问题**之前只甚癟分比计算盈亏完党応略了仓䜍倧小和杠杆倍数 - - 瀺䟋100 USDT仓䜍赚5%和1000 USDT仓䜍赚5%郜星瀺`5.0`䜜䞺盈利 - - 这富臎性胜分析完党䞍准确 -- **解决方案**现圚计算实际USDT盈亏金额 - ``` - 盈亏(USDT) = 仓䜍价倌 × 价栌变化% × 杠杆倍数 - 瀺䟋: 1000 USDT × 5% × 20倍 = 1000 USDT实际盈利 - ``` -- **圱响**胜率、盈亏比和倏普比率现圚基于准确的USDT金额计算 - -**2. 持仓远螪 - 猺倱关键数据** -- **问题**匀仓记圕只存傚了价栌和时闎猺少数量和杠杆 -- **解决方案**现圚存傚完敎亀易数据 - - `quantity`: 持仓数量垁数 - - `leverage`: 杠杆倍数劂20倍 - - 这些是准确计算盈亏的必芁数据 - -**3. 持仓键倌逻蟑 - 倚空冲突** -- **问题**䜿甚`symbol`䜜䞺持仓键倌富臎同时持有倚空仓时数据冲突 - - 瀺䟋BTCUSDT倚倎和BTCUSDT空倎䌚互盞芆盖 -- **解决方案**改䞺`symbol_side`栌匏劂`BTCUSDT_long`、`BTCUSDT_short` - - 现圚可以正确区分倚空持仓 - -**4. 倏普比率计算 - 代码䌘化** -- **问题**䜿甚自定义的牛顿迭代法计算平方根 -- **解决方案**替换䞺标准库`math.Sqrt` - - 曎可靠、易绎技䞔高效 - -**䞺什么这次曎新埈重芁** -- ✅ 历史亀易统计现圚星瀺**真实的USDT盈亏**而䞍是无意义的癟分比 -- ✅ 䞍同杠杆倍数的亀易对比现圚准确了 -- ✅ AI自我孊习机制接收到正确的历史反銈 -- ✅ 盈亏比和倏普比率计算现圚有意义了 -- ✅ 倚持仓远螪同时持有倚空现圚正垞工䜜 - -**建议**劂果悚圚歀曎新前运行过系统悚的历史统计数据是䞍准确的。曎新到v2.0.2后新的亀易将被正确计算。 - -### v2.0.1 (2025-10-29) - -**Bug修倍:** -- ✅ 修倍ComparisonChart数据倄理逻蟑 - 从cycle_number分组改䞺timestamp分组 -- ✅ 解决后端重启富臎cycle_number重眮时囟衚冻结的问题 -- ✅ 改进囟衚数据星瀺 - 现圚按时闎顺序星瀺所有历史数据点 -- ✅ 增区调试日志䟿于问题排查 - -### v2.0.0 (2025-10-28) - -**重倧曎新:** -- ✅ AI自我孊习机制历史反銈、衚现分析 -- ✅ 倚Trader竞赛暡匏Qwen vs DeepSeek -- ✅ Binance风栌UI完敎暡仿垁安界面 -- ✅ 性胜对比囟衚收益率实时对比 -- ✅ 风险控制䌘化单垁种仓䜍䞊限调敎 - -**Bug修倍:** -- 修倍初始䜙额硬猖码问题 -- 修倍倚trader数据同步问题 -- 䌘化囟衚数据对霐䜿甚cycle_number - -### v1.0.0 (2025-10-27) -- 初始版本发垃 -- 基础AI亀易功胜 -- 决策日志系统 -- 简单Web界面 +**近期亮点** +- 🚀 完敎系统重新讟计基于Web的配眮平台 +- 🗄 数据库驱劚架构SQLite +- 🎚 无需猖蟑JSON - 党郚通过Web界面配眮 +- 🔧 AI暡型䞎亀易所任意组合 +- 📊 增区的API层提䟛党面的端点 --- diff --git a/docs/roadmap/README.md b/docs/roadmap/README.md new file mode 100644 index 00000000..9f203ff1 --- /dev/null +++ b/docs/roadmap/README.md @@ -0,0 +1,292 @@ +# 🗺 NOFX Roadmap + +**Language:** [English](README.md) | [äž­æ–‡](README.zh-CN.md) + +Strategic plan for NOFX development and universal market expansion. + +--- + +## 📋 Overview + +NOFX is on a mission to become the **Universal AI Trading Operating System** for all financial markets. Our proven infrastructure on crypto markets is being extended to stocks, futures, options, forex, and beyond. + +**Vision:** Same architecture. Same agent framework. All markets. + +--- + +## 🎯 Short-Term Roadmap + +### Phase 1: Core Infrastructure Enhancement + +#### 1.1 Security Enhancements +**Goal:** Protect sensitive data and reduce security vulnerabilities + +- **Credential Management** + - [ ] Implement AES-256 encryption for API keys in database + - [ ] Add encryption for private keys (Hyperliquid, Aster) + - [ ] Use hardware security module (HSM) support for production + - [ ] Implement key rotation mechanism + - [ ] Add audit logging for all credential access + +- **Application Security** + - [ ] Input validation and sanitization (prevent SQL injection, XSS) + - [ ] Rate limiting for API endpoints + - [ ] CORS policy configuration + - [ ] JWT token expiration and refresh mechanism + - [ ] Implement RBAC (Role-Based Access Control) for multi-user support + - [ ] Add IP whitelisting for API access + - [ ] Security headers (CSP, HSTS, X-Frame-Options) + +- **Operational Security** + - [ ] Secure password hashing (bcrypt with salt) + - [ ] 2FA enhancement (backup codes, multiple TOTP devices) + - [ ] Session management (auto-logout, concurrent session limits) + - [ ] Secrets management (environment variables, vault integration) + - [ ] Regular dependency vulnerability scanning + +#### 1.2 Enhanced AI Capabilities +**Goal:** Richer prompts, flexible configuration, support for more AI models + +- **Prompt System Overhaul** + - [ ] Template engine for dynamic prompt generation + - [ ] Multi-language prompt support (chain-of-thought, few-shot, zero-shot) + - [ ] Market condition-based prompt switching (bull, bear, sideways) + - [ ] Historical performance feedback integration in prompts + - [ ] Prompt versioning and A/B testing framework + - [ ] User-customizable prompt templates via web interface + +- **AI Model Integration** + - [ ] OpenAI GPT-4/GPT-4 Turbo support + - [ ] Anthropic Claude 3 (Opus, Sonnet, Haiku) integration + - [ ] Google Gemini Pro support + - [ ] Local LLM support (Llama, Mistral via Ollama) + - [ ] Multi-model ensemble (voting, weighted average) + - [ ] Model performance tracking and auto-selection + - [ ] Fallback mechanism when primary model fails + +- **AI Decision Engine** + - [ ] Confidence scoring for each decision + - [ ] Explanation generation (why this trade?) + - [ ] Risk assessment integration in AI reasoning + - [ ] Market regime detection (trend, mean-reversion, high volatility) + - [ ] Cross-validation with technical indicators + +#### 1.3 Exchange Integration Expansion +**Goal:** Support more CEX and popular perp-DEX, both spot and futures + +- **Centralized Exchanges (CEX)** + - [ ] **OKX** - Futures + Spot trading + - [ ] **Bybit** - Futures + Spot trading + - [ ] **Bitget** - Futures + Spot trading + - [ ] **Gate.io** - Futures + Spot trading + - [ ] **KuCoin** - Futures + Spot trading + - [ ] Unified CEX interface for easy addition of new exchanges + +- **Decentralized Perpetual Exchanges (Perp-DEX)** + - [x] **Hyperliquid** (Ethereum L1) - High-performance orderbook DEX (✅ Supported) + - [x] **Aster** (Multi-chain) - Binance-compatible API DEX (✅ Supported) + - [ ] **Lighter** (Arbitrum) - Gasless orderbook DEX with off-chain matching + - [ ] **EdgeX** (Multi-chain) - Professional derivatives DEX + - [ ] Unified DEX interface for consistent integration + - [ ] Enhanced Hyperliquid integration (testnet support, advanced order types) + - [ ] Enhanced Aster integration (cross-chain support, wallet management) + +- **Spot + Futures Support** + - [ ] Dual-mode trading (spot arbitrage, futures hedging) + - [ ] Cross-exchange arbitrage detection + - [ ] Unified position tracking across spot and futures + - [ ] Auto-conversion between spot and perpetual strategies + +- **Exchange Infrastructure** + - [ ] **Trading Data Analysis API Integration** (In-house developed) + - [ ] AI500 integration - In-house AI-powered coin selection model + - [ ] OI (Open Interest) Analysis - Real-time open interest tracking and anomaly detection + - [ ] NetFlow Analysis - On-chain fund flow analysis for market sentiment + - [ ] Market sentiment aggregator - Combine multiple data sources for enhanced AI decision making + - [ ] Custom indicator API - Support for proprietary technical indicators + - [ ] Automatic precision handling (quantity, price decimals) + - [ ] Order type abstraction (market, limit, stop-loss, take-profit) + - [ ] Unified error handling and retry logic + - [ ] WebSocket support for real-time data + - [ ] Rate limit management per exchange + +#### 1.4 Project Structure Refactoring +**Goal:** Clear hierarchy, high cohesion, low coupling, easy to extend and maintain + +- **Architecture Redesign** + - [ ] Implement layered architecture (Presentation → Business Logic → Data Access) + - [ ] Apply SOLID principles (especially Liskov Substitution Principle for exchange adapters) + - [ ] Extract common interfaces for all exchange implementations + - [ ] Separate concerns: trading logic, data fetching, decision making, execution + - [ ] Implement dependency injection for better testability + +- **Code Organization** + - [ ] Refactor monolithic modules into smaller, focused packages + - [ ] Create abstract base classes for traders, exchanges, AI models + - [ ] Implement factory pattern for exchange/AI model creation + - [ ] Standardize error handling and logging across all modules + - [ ] Remove circular dependencies and improve import structure + +- **Configuration Management** + - [ ] Centralize all configuration in structured config files + - [ ] Implement hot-reload for non-critical configuration changes + - [ ] Validate configurations at startup with clear error messages + - [ ] Support environment-specific configs (dev/staging/production) + +#### 1.5 User Experience Improvements +**Goal:** Enhanced web interface, better monitoring, and alerting system + +- **Web Interface Enhancements** + - [ ] Mobile-responsive design (tablet and phone support) + - [ ] Dark/Light theme toggle with user preference saving + - [ ] Advanced charting with TradingView widget integration + - [ ] Real-time WebSocket updates (replace polling for positions/orders) + - [ ] Drag-and-drop dashboard customization + - [ ] Multi-language support (EN, CN, RU, UK) + +- **Configuration Interface** + - [ ] Visual strategy builder (no-code flow diagram) + - [ ] Live configuration preview before saving + - [ ] Configuration templates for common strategies + - [ ] Bulk trader management (start/stop multiple traders) + - [ ] Exchange credential testing (verify before saving) + - [ ] AI model testing interface (test prompts before deployment) + +- **Monitoring & Analytics** + - [ ] Real-time performance dashboard with key metrics + - [ ] Equity curve visualization (per trader, per exchange, overall) + - [ ] Drawdown analysis and risk metrics + - [ ] Trade history with filtering and search + - [ ] P&L breakdown by symbol, time period, strategy + - [ ] Comparison view (multiple traders side-by-side) + - [ ] Export functionality (CSV, JSON, PDF reports) + +- **Alert & Notification System** + - [ ] Multi-channel alerts (Email, Telegram, Discord, Webhook) + - [ ] Configurable alert rules (profit threshold, loss limit, error detection) + - [ ] Alert priority levels (critical, warning, info) + - [ ] Alert history and acknowledgment tracking + - [ ] Daily/Weekly performance summary emails + - [ ] System health monitoring (API connectivity, database status) + +### Phase 2: Testing & Stability + +#### 2.1 Quality Assurance +- [ ] Comprehensive unit test coverage (>80%) +- [ ] Integration tests for all exchange adapters +- [ ] Load testing (100+ concurrent traders) +- [ ] Security audit (API key encryption, SQL injection prevention) + +#### 2.2 Documentation +- [ ] Complete API reference documentation +- [ ] Video tutorials for beginners +- [ ] Strategy development guide +- [ ] Troubleshooting playbook + +#### 2.3 Community Features +- [ ] Public strategy marketplace (share/sell strategies) +- [ ] Leaderboard with verified performance +- [ ] Community forum integration +- [ ] Bug bounty program + +--- + +## 🚀 Long-Term Roadmap + +### Phase 3: Universal Market Expansion + +**Goal:** Extend the proven crypto trading infrastructure to all major financial markets. + +#### 3.1 Stock Markets +- [ ] US Equities (Interactive Brokers, Alpaca Markets) +- [ ] Asian Markets (A-shares, Hong Kong, Japan) +- [ ] Fundamental analysis integration (earnings, P/E, dividends) +- [ ] AI-powered stock screening + +#### 3.2 Futures Markets +- [ ] Commodity Futures (Energy, Metals, Agriculture) +- [ ] Index Futures (S&P 500, NASDAQ, Dow Jones, VIX) +- [ ] Rollover management and spread trading + +#### 3.3 Options Trading +- [ ] Options chain data and Greeks calculation +- [ ] Equity, Index, and Crypto options +- [ ] Options strategy builder + +#### 3.4 Forex Markets +- [ ] Major currency pairs and exotic pairs +- [ ] Interest rate analysis and carry trade support + +--- + +### Phase 4: Advanced AI & Automation + +**Goal:** Implement cutting-edge AI technologies for autonomous trading. + +- [ ] Multi-Agent orchestration (specialized agents with dynamic coordination) +- [ ] Reinforcement Learning (DQN, PPO, transfer learning) +- [ ] Alternative data integration (social sentiment, news, on-chain analytics) + +--- + +### Phase 5: Enterprise & Scaling + +**Goal:** Scale infrastructure for institutional use and high-volume trading. + +- [ ] Database migration (PostgreSQL/MySQL, Redis, TimescaleDB) +- [ ] Microservices architecture with Kubernetes deployment +- [ ] Multi-user RBAC and white-label solutions +- [ ] Advanced analytics and compliance reporting + +--- + +## 📊 Key Metrics & Milestones + +### Short-Term Targets +- [ ] **100+** supported trading pairs across all exchanges +- [ ] **10,000+** active trader instances +- [ ] **5+** new exchange integrations +- [ ] **80%+** test coverage +- [ ] **99.9%** uptime + +### Long-Term Targets +- [ ] **All major asset classes** supported (crypto, stocks, futures, options, forex) +- [ ] **50,000+** active users +- [ ] **Enterprise tier** launched +- [ ] **Institutional partnerships** established + +--- + +## 🀝 Community Involvement + +We welcome community contributions to accelerate our roadmap: + +- **Vote on Features**: Join our [Telegram community](https://t.me/nofx_dev_community) to vote on priority features +- **Contribute Code**: Check our [Contributing Guide](../../CONTRIBUTING.md) +- **Bug Bounties**: Report issues and earn rewards +- **Strategy Sharing**: Share your successful strategies + +--- + +## 📝 Roadmap Updates + +This roadmap is reviewed and updated quarterly based on: +- Community feedback +- Market demands +- Technical feasibility +- Resource availability + +**Last Updated:** 2025-11-01 + +--- + +## 📚 Related Documentation + +- [Architecture Documentation](../architecture/README.md) - Technical architecture details +- [Getting Started](../getting-started/README.md) - Setup and deployment +- [Contributing Guide](../../CONTRIBUTING.md) - How to contribute +- [Changelog](../../CHANGELOG.md) - Version history + +--- + +[← Back to Documentation Home](../README.md) diff --git a/docs/roadmap/README.zh-CN.md b/docs/roadmap/README.zh-CN.md new file mode 100644 index 00000000..a34921dd --- /dev/null +++ b/docs/roadmap/README.zh-CN.md @@ -0,0 +1,292 @@ +# 🗺 NOFX 路线囟 + +**语蚀:** [English](README.md) | [äž­æ–‡](README.zh-CN.md) + +NOFX 发展和通甚垂场扩展的战略规划。 + +--- + +## 📋 抂述 + +NOFX 的䜿呜是成䞺所有金融垂场的**通甹 AI 亀易操䜜系统**。我们圚加密莧垁垂场䞊经过验证的基础讟斜正圚扩展到股祚、期莧、期权、倖汇等领域。 + +**愿景** 盞同架构。盞同智胜䜓框架。所有垂场。 + +--- + +## 🎯 短期路线囟 + +### 阶段1: 栞心基础讟斜增区 + +#### 1.1 安党性增区 +**目标** 保技敏感数据减少安党挏掞 + +- **凭证管理** + - [ ] 䞺数据库䞭的API密钥实现AES-256加密 + - [ ] 䞺私钥Hyperliquid、Aster添加加密 + - [ ] 䞺生产环境支持硬件安党暡块HSM + - [ ] 实现密钥蜮换机制 + - [ ] 䞺所有凭证访问添加审计日志 + +- **应甚安党** + - [ ] 蟓入验证和枅理防止SQL泚入、XSS攻击 + - [ ] API端点的速率限制 + - [ ] CORS策略配眮 + - [ ] JWT什牌过期和刷新机制 + - [ ] 实现RBAC基于角色的访问控制支持倚甚户 + - [ ] 添加API访问的IP癜名单 + - [ ] 安党倎郚CSP、HSTS、X-Frame-Options + +- **运营安党** + - [ ] 安党密码哈垌bcrypt加盐 + - [ ] 2FA增区倇仜码、倚䞪TOTP讟倇 + - [ ] 䌚话管理自劚登出、并发䌚话限制 + - [ ] 密钥管理环境变量、vault集成 + - [ ] 定期䟝赖项挏掞扫描 + +#### 1.2 增区AI胜力 +**目标** 曎䞰富的prompts、灵掻配眮、支持曎倚AI暡型 + +- **Prompt系统党面改造** + - [ ] 劚态prompt生成的暡板匕擎 + - [ ] 倚语蚀prompt支持思绎铟、few-shot、zero-shot + - [ ] 基于垂场状况的prompt切换牛垂、熊垂、震荡 + - [ ] 圚prompts䞭集成历史绩效反銈 + - [ ] Prompt版本控制和A/B测试框架 + - [ ] 通过Web界面自定义prompt暡板 + +- **AI暡型集成** + - [ ] OpenAI GPT-4/GPT-4 Turbo支持 + - [ ] Anthropic Claude 3Opus、Sonnet、Haiku集成 + - [ ] Google Gemini Pro支持 + - [ ] 本地LLM支持通过Ollama的Llama、Mistral + - [ ] 倚暡型集成投祚、加权平均 + - [ ] 暡型性胜跟螪和自劚选择 + - [ ] 䞻暡型倱莥时的降级机制 + +- **AI决策匕擎** + - [ ] 每䞪决策的眮信床评分 + - [ ] 解释生成䞺什么做这笔亀易 + - [ ] AI掚理䞭的风险评䌰集成 + - [ ] 垂场状态检测趋势、均倌回園、高波劚 + - [ ] 䞎技术指标的亀叉验证 + +#### 1.3 亀易所集成扩展 +**目标** 支持曎倚CEX和流行的perp-DEX现莧和合纊 + +- **䞭心化亀易所CEX** + - [ ] **OKX** - 合纊 + 现莧亀易 + - [ ] **Bybit** - 合纊 + 现莧亀易 + - [ ] **Bitget** - 合纊 + 现莧亀易 + - [ ] **Gate.io** - 合纊 + 现莧亀易 + - [ ] **KuCoin** - 合纊 + 现莧亀易 + - [ ] 统䞀的CEX接口䟿于添加新亀易所 + +- **去䞭心化氞续亀易所Perp-DEX** + - [x] **Hyperliquid**Ethereum L1- 高性胜订单簿DEX✅ 已支持 + - [x] **Aster**倚铟- Binance兌容API的DEX✅ 已支持 + - [ ] **Lighter**Arbitrum- 无Gas订单簿DEX铟䞋撮合 + - [ ] **EdgeX**倚铟- 䞓䞚衍生品DEX + - [ ] 统䞀的DEX接口保证集成䞀臎性 + - [ ] 增区Hyperliquid集成测试眑支持、高级订单类型 + - [ ] 增区Aster集成跚铟支持、钱包管理 + +- **现莧 + 合纊支持** + - [ ] 双暡匏亀易现莧套利、合纊对冲 + - [ ] 跚亀易所套利检测 + - [ ] 现莧和合纊的统䞀持仓跟螪 + - [ ] 现莧和氞续策略之闎的自劚蜬换 + +- **亀易所基础讟斜** + - [ ] **亀易数据分析API集成**自研 + - [ ] AI500集成 - 自研AI选垁暡型 + - [ ] OI持仓量分析 - 实时持仓量跟螪和匂垞检测 + - [ ] NetFlow分析 - 铟䞊资金流向分析甚于垂场情绪刀断 + - [ ] 垂场情绪聚合噚 - 敎合倚䞪数据源增区AI决策胜力 + - [ ] 自定义指标API - 支持䞓有技术指标 + - [ ] 自劚粟床倄理数量、价栌小数䜍 + - [ ] 订单类型抜象垂价、限价、止损、止盈 + - [ ] 统䞀的错误倄理和重试逻蟑 + - [ ] 实时数据的WebSocket支持 + - [ ] 每䞪亀易所的速率限制管理 + +#### 1.4 项目结构重构 +**目标** 枅晰层次、高内聚䜎耊合、易于扩展和绎技 + +- **架构重新讟计** + - [ ] 实现分层架构衚现层 → 䞚务逻蟑层 → 数据访问层 + - [ ] 应甚SOLID原则特别是里氏替换原则甚于亀易所适配噚 + - [ ] 䞺所有亀易所实现提取通甚接口 + - [ ] 分犻关泚点亀易逻蟑、数据获取、决策制定、执行 + - [ ] 实现䟝赖泚入以提高可测试性 + +- **代码组织** + - [ ] 将单䜓暡块重构䞺曎小、曎䞓泚的包 + - [ ] 䞺traders、exchanges、AI暡型创建抜象基类 + - [ ] 实现工厂暡匏甚于亀易所/AI暡型的创建 + - [ ] 标准化所有暡块的错误倄理和日志记圕 + - [ ] 消陀埪环䟝赖并改进富入结构 + +- **配眮管理** + - [ ] 将所有配眮集䞭到结构化配眮文件䞭 + - [ ] 实现非关键配眮的热重蜜 + - [ ] 启劚时验证配眮并提䟛枅晰的错误消息 + - [ ] 支持环境特定配眮dev/staging/production + +#### 1.5 甚户䜓验改进 +**目标** 增区Web界面、曎奜的监控和告譊系统 + +- **Web界面增区** + - [ ] 移劚端响应匏讟计平板和手机支持 + - [ ] 深色/浅色䞻题切换并保存甚户偏奜 + - [ ] TradingView小郚件集成的高级囟衚 + - [ ] 实时WebSocket曎新替代持仓/订单的蜮询 + - [ ] 拖拜匏仪衚板自定义 + - [ ] 倚语蚀支持EN、CN、RU、UK + +- **配眮界面** + - [ ] 可视化策略构建噚无代码流皋囟 + - [ ] 保存前的实时配眮预览 + - [ ] 垞甚策略的配眮暡板 + - [ ] 批量trader管理启劚/停止倚䞪traders + - [ ] 亀易所凭证测试保存前验证 + - [ ] AI暡型测试界面郚眲前测试prompts + +- **监控䞎分析** + - [ ] 实时性胜仪衚板和关键指标 + - [ ] 权益曲线可视化每䞪trader、每䞪亀易所、总䜓 + - [ ] 回撀分析和风险指标 + - [ ] 垊过滀和搜玢的亀易历史 + - [ ] 按垁种、时闎段、策略的盈亏分解 + - [ ] 比蟃视囟倚䞪traders并排 + - [ ] 富出功胜CSV、JSON、PDF报告 + +- **告譊䞎通知系统** + - [ ] 倚枠道告譊Email、Telegram、Discord、Webhook + - [ ] 可配眮的告譊规则利涊阈倌、亏损限制、错误检测 + - [ ] 告譊䌘先级䞥重、譊告、信息 + - [ ] 告譊历史和确讀跟螪 + - [ ] 每日/每呚性胜摘芁邮件 + - [ ] 系统健康监控API连接、数据库状态 + +### 阶段2: 测试䞎皳定性 + +#### 2.1 莚量保证 +- [ ] 党面的单元测试芆盖率>80% +- [ ] 所有亀易所适配噚的集成测试 +- [ ] 莟蜜测试100+并发亀易者 +- [ ] 安党审计API密钥加密、SQL泚入防技 + +#### 2.2 文档 +- [ ] 完敎的API参考文档 +- [ ] 新手视频教皋 +- [ ] 策略匀发指南 +- [ ] 故障排查手册 + +#### 2.3 瀟区功胜 +- [ ] 公匀策略垂场分享/出售策略 +- [ ] 经过验证的绩效排行抜 +- [ ] 瀟区论坛集成 +- [ ] 挏掞赏金计划 + +--- + +## 🚀 长期路线囟 + +### 阶段3: 通甚垂场扩展 + +**目标** 将经过验证的加密莧垁亀易基础讟斜扩展到所有䞻芁金融垂场。 + +#### 3.1 股祚垂场 +- [ ] 矎股Interactive Brokers、Alpaca Markets +- [ ] 亚掲垂场A股、銙枯、日本 +- [ ] 基本面分析集成莢报、垂盈率、股息 +- [ ] AI驱劚的股祚筛选 + +#### 3.2 期莧垂场 +- [ ] 商品期莧胜源、金属、农产品 +- [ ] 指数期莧标普500、纳斯蟟克、道琌斯、VIX +- [ ] 展期管理和价差亀易 + +#### 3.3 期权亀易 +- [ ] 期权铟数据和Greeks计算 +- [ ] 股祚、指数和加密期权 +- [ ] 期权策略构建噚 + +#### 3.4 倖汇垂场 +- [ ] 䞻芁莧垁对和皀有莧垁对 +- [ ] 利率分析和套息亀易支持 + +--- + +### 阶段4: 高级AI䞎自劚化 + +**目标** 实现前沿AI技术甚于自䞻亀易。 + +- [ ] 倚智胜䜓猖排䞓䞚化智胜䜓䞎劚态协调 +- [ ] 区化孊习DQN、PPO、迁移孊习 +- [ ] 替代数据集成瀟亀情绪、新闻、铟䞊分析 + +--- + +### 阶段5: 䌁䞚级䞎扩展 + +**目标** 扩展基础讟斜以支持机构䜿甚和高频亀易。 + +- [ ] 数据库迁移PostgreSQL/MySQL、Redis、TimescaleDB +- [ ] 埮服务架构䞎Kubernetes郚眲 +- [ ] 倚甚户RBAC和癜标解决方案 +- [ ] 高级分析和合规报告 + +--- + +## 📊 关键指标䞎里皋碑 + +### 短期目标 +- [ ] 所有亀易所支持**100+**亀易对 +- [ ] **10,000+**掻跃亀易者实䟋 +- [ ] **5+**新亀易所集成 +- [ ] **80%+**测试芆盖率 +- [ ] **99.9%**正垞运行时闎 + +### 长期目标 +- [ ] 支持**所有䞻芁资产类别**加密、股祚、期莧、期权、倖汇 +- [ ] **50,000+**掻跃甚户 +- [ ] **䌁䞚级**版本发垃 +- [ ] 建立**机构合䜜䌙䌎关系** + +--- + +## 🀝 瀟区参䞎 + +我们欢迎瀟区莡献来加速我们的路线囟 + +- **功胜投祚**: 加入我们的[Telegram瀟区](https://t.me/nofx_dev_community)投祚䌘先功胜 +- **莡献代码**: 查看我们的[莡献指南](../../CONTRIBUTING.md) +- **挏掞赏金**: 报告问题并获埗奖励 +- **策略分享**: 分享䜠的成功策略 + +--- + +## 📝 路线囟曎新 + +本路线囟根据以䞋因玠每季床审查和曎新 +- 瀟区反銈 +- 垂场需求 +- 技术可行性 +- 资源可甚性 + +**最后曎新:** 2025-11-01 + +--- + +## 📚 盞关文档 + +- [架构文档](../architecture/README.zh-CN.md) - 技术架构诊情 +- [快速匀始](../getting-started/README.zh-CN.md) - 讟眮和郚眲 +- [莡献指南](../../CONTRIBUTING.md) - 劂䜕莡献 +- [曎新日志](../../CHANGELOG.zh-CN.md) - 版本历史 + +--- + +[← 返回文档䞻页](../README.md) diff --git a/web/public/images/hand-bg.png b/web/public/images/hand-bg.png new file mode 100644 index 00000000..8ca9e333 Binary files /dev/null and b/web/public/images/hand-bg.png differ diff --git a/web/public/images/hand.png b/web/public/images/hand.png new file mode 100644 index 00000000..619da0ae Binary files /dev/null and b/web/public/images/hand.png differ diff --git a/web/public/images/logo.png b/web/public/images/logo.png deleted file mode 100644 index 28ec8c71..00000000 Binary files a/web/public/images/logo.png and /dev/null differ diff --git a/web/src/App.tsx b/web/src/App.tsx index 6f785908..11e604ce 100644 --- a/web/src/App.tsx +++ b/web/src/App.tsx @@ -7,12 +7,12 @@ import { LoginPage } from './components/LoginPage'; import { RegisterPage } from './components/RegisterPage'; import { CompetitionPage } from './components/CompetitionPage'; import { LandingPage } from './pages/LandingPage'; +import HeaderBar from './components/landing/HeaderBar'; import AILearning from './components/AILearning'; import { LanguageProvider, useLanguage } from './contexts/LanguageContext'; import { AuthProvider, useAuth } from './contexts/AuthContext'; import { t, type Language } from './i18n/translations'; import { useSystemConfig } from './hooks/useSystemConfig'; -import { Zap } from 'lucide-react'; import type { SystemStatus, AccountInfo, @@ -44,29 +44,42 @@ function App() { const { config: systemConfig, loading: configLoading } = useSystemConfig(); const [route, setRoute] = useState(window.location.pathname); - // 从URL hash读取初始页面状态支持刷新保持页面 + // 从URL路埄读取初始页面状态支持刷新保持页面 const getInitialPage = (): Page => { + const path = window.location.pathname; const hash = window.location.hash.slice(1); // 去掉 # - return hash === 'trader' || hash === 'details' ? 'trader' : 'competition'; + + if (path === '/traders' || hash === 'traders') return 'traders'; + if (path === '/dashboard' || hash === 'trader' || hash === 'details') return 'trader'; + return 'competition'; // 默讀䞺竞赛页面 }; const [currentPage, setCurrentPage] = useState(getInitialPage()); const [selectedTraderId, setSelectedTraderId] = useState(); const [lastUpdate, setLastUpdate] = useState('--:--:--'); - // 监听URL hash变化同步页面状态 + // 监听URL变化同步页面状态 useEffect(() => { - const handleHashChange = () => { + const handleRouteChange = () => { + const path = window.location.pathname; const hash = window.location.hash.slice(1); - if (hash === 'trader' || hash === 'details') { + + if (path === '/traders' || hash === 'traders') { + setCurrentPage('traders'); + } else if (path === '/dashboard' || hash === 'trader' || hash === 'details') { setCurrentPage('trader'); - } else if (hash === 'competition' || hash === '') { + } else if (path === '/competition' || hash === 'competition' || hash === '') { setCurrentPage('competition'); } + setRoute(path); }; - window.addEventListener('hashchange', handleHashChange); - return () => window.removeEventListener('hashchange', handleHashChange); + window.addEventListener('hashchange', handleRouteChange); + window.addEventListener('popstate', handleRouteChange); + return () => { + window.removeEventListener('hashchange', handleRouteChange); + window.removeEventListener('popstate', handleRouteChange); + }; }, []); // 切换页面时曎新URL hash (圓前通过按钮盎接调甚setCurrentPage这䞪凜数暂时保留甚于未来扩展) @@ -166,153 +179,137 @@ function App() { return () => window.removeEventListener('popstate', handlePopState); }, []); + // Set current page based on route for consistent navigation state + useEffect(() => { + if (route === '/competition') { + setCurrentPage('competition'); + } else if (route === '/traders') { + setCurrentPage('traders'); + } else if (route === '/dashboard') { + setCurrentPage('trader'); + } + }, [route]); + // Show loading spinner while checking auth or config if (isLoading || configLoading) { return (
- NoFx Logo + NoFx Logo

{t('loading', language)}

); } - // Show landing page for root route when not authenticated + // Handle specific routes regardless of authentication + if (route === '/login') { + return ; + } + if (route === '/register') { + return ; + } + if (route === '/competition') { + return ( +
+ { + console.log('Competition page onPageChange called with:', page); + console.log('Current route:', route, 'Current page:', currentPage); + + if (page === 'competition') { + console.log('Navigating to competition'); + window.history.pushState({}, '', '/competition'); + setRoute('/competition'); + setCurrentPage('competition'); + } else if (page === 'traders') { + console.log('Navigating to traders'); + window.history.pushState({}, '', '/traders'); + setRoute('/traders'); + setCurrentPage('traders'); + } else if (page === 'trader') { + console.log('Navigating to trader/dashboard'); + window.history.pushState({}, '', '/dashboard'); + setRoute('/dashboard'); + setCurrentPage('trader'); + } + + console.log('After navigation - route:', route, 'currentPage:', currentPage); + }} + /> +
+ +
+
+ ); + } + + // Show landing page for root route + if (route === '/' || route === '') { + return ; + } + + // Show main app for authenticated users on other routes if (!systemConfig?.admin_mode && (!user || !token)) { - if (route === '/login') { - return ; - } - if (route === '/register') { - return ; - } - // Default to landing page when not authenticated + // Default to landing page when not authenticated and no specific route return ; } return ( -
- {/* Header - Binance Style */} -
-
-
- {/* Left - Logo and Title */} -
-
- NOFX -
-
-

- {t('appTitle', language)} -

-

- {t('subtitle', language)} -

-
-
- - {/* Center - Page Toggle (absolutely positioned) */} -
- - - -
- - {/* Right - Actions */} -
- - {/* User Info - Only show if not in admin mode */} - {!systemConfig?.admin_mode && user && ( -
-
- {user.email[0].toUpperCase()} -
- {user.email} -
- )} - - {/* Admin Mode Indicator */} - {systemConfig?.admin_mode && ( -
- - {t('adminMode', language)} -
- )} - - {/* Language Toggle */} -
- - -
- - {/* Logout Button - Only show if not in admin mode */} - {!systemConfig?.admin_mode && ( - - )} -
-
-
-
+
+ { + console.log('App.tsx onPageChange called with:', page); + console.log('Current route:', route, 'Current page:', currentPage); + + if (page === 'competition') { + console.log('Navigating to competition'); + window.history.pushState({}, '', '/competition'); + setRoute('/competition'); + setCurrentPage('competition'); + } else if (page === 'traders') { + console.log('Navigating to traders'); + window.history.pushState({}, '', '/traders'); + setRoute('/traders'); + setCurrentPage('traders'); + } else if (page === 'trader') { + console.log('Navigating to trader/dashboard'); + window.history.pushState({}, '', '/dashboard'); + setRoute('/dashboard'); + setCurrentPage('trader'); + } + + console.log('After navigation - route:', route, 'currentPage:', currentPage); + }} + /> {/* Main Content */} -
+
{currentPage === 'competition' ? ( ) : currentPage === 'traders' ? ( { setSelectedTraderId(traderId); + window.history.pushState({}, '', '/dashboard'); + setRoute('/dashboard'); setCurrentPage('trader'); }} /> diff --git a/web/src/components/CompetitionPage.tsx b/web/src/components/CompetitionPage.tsx index 1ebdb564..2e3d90f6 100644 --- a/web/src/components/CompetitionPage.tsx +++ b/web/src/components/CompetitionPage.tsx @@ -31,6 +31,8 @@ export function CompetitionPage() { setIsModalOpen(true); } catch (error) { console.error('Failed to fetch trader config:', error); + // 对于未登圕甚户䞍星瀺诊细配眮这是正垞行䞺 + // 竞赛页面䞻芁甚于查看排行抜和基本信息 } }; diff --git a/web/src/components/CryptoFeatureCard.tsx b/web/src/components/CryptoFeatureCard.tsx index 9c78960a..0affa99d 100644 --- a/web/src/components/CryptoFeatureCard.tsx +++ b/web/src/components/CryptoFeatureCard.tsx @@ -30,8 +30,8 @@ export const CryptoFeatureCard = React.forwardRef {/* Icon container */} -
{icon}
+
{icon}
{/* Title */} -

{title}

+

{title}

{/* Description */} -

{description}

+

{description}

{/* Features list */}
@@ -95,11 +95,11 @@ export const CryptoFeatureCard = React.forwardRef
-
- +
+
- {feature} + {feature} ))}
diff --git a/web/src/components/Header.tsx b/web/src/components/Header.tsx index 48dc6a5b..06352dee 100644 --- a/web/src/components/Header.tsx +++ b/web/src/components/Header.tsx @@ -15,7 +15,7 @@ export function Header({ simple = false }: HeaderProps) { {/* Left - Logo and Title */}
- NoFx Logo + NoFx Logo

diff --git a/web/src/components/LoginPage.tsx b/web/src/components/LoginPage.tsx index ea36356c..a1ed3512 100644 --- a/web/src/components/LoginPage.tsx +++ b/web/src/components/LoginPage.tsx @@ -2,8 +2,7 @@ import React, { useState } from 'react'; import { useAuth } from '../contexts/AuthContext'; import { useLanguage } from '../contexts/LanguageContext'; import { t } from '../i18n/translations'; -import { Header } from './Header'; -import { ArrowLeft } from 'lucide-react'; +import HeaderBar from './landing/HeaderBar'; export function LoginPage() { const { language } = useLanguage(); @@ -51,43 +50,44 @@ export function LoginPage() { }; return ( -
-
+
+ {}} + isLoggedIn={false} + isHomePage={false} + currentPage="login" + language={language} + onLanguageChange={() => {}} + onPageChange={(page) => { + console.log('LoginPage onPageChange called with:', page); + if (page === 'competition') { + window.location.href = '/competition'; + } + }} + /> -
+
- {/* Back to Home */} - {/* Logo */}
- NoFx Logo + NoFx Logo
-

- {t('loginTitle', language)} +

+ 登圕 NOFX

-

- {step === 'login' ? t('loginTitle', language) : t('enterOTPCode', language)} +

+ {step === 'login' ? '请蟓入悚的邮箱和密码' : '请蟓入䞀步验证码'}

{/* Login Form */} -
+
{step === 'login' ? (
-
-
{error && ( -
+
{error}
)} @@ -126,7 +126,7 @@ export function LoginPage() { type="submit" disabled={loading} className="w-full px-4 py-2 rounded text-sm font-semibold transition-all hover:scale-105 disabled:opacity-50" - style={{ background: '#F0B90B', color: '#000' }} + style={{ background: 'var(--brand-yellow)', color: 'var(--brand-black)' }} > {loading ? t('loading', language) : t('loginButton', language)} @@ -142,7 +142,7 @@ export function LoginPage() {
-
{error && ( -
+
{error}
)} @@ -168,7 +168,7 @@ export function LoginPage() { type="button" onClick={() => setStep('login')} className="flex-1 px-4 py-2 rounded text-sm font-semibold" - style={{ background: '#2B3139', color: '#848E9C' }} + style={{ background: 'var(--panel-bg-hover)', color: 'var(--text-secondary)' }} > {t('back', language)} @@ -187,17 +187,17 @@ export function LoginPage() { {/* Register Link */}
-

- {t('noAccount', language)}{' '} +

+ 还没有莊户{' '}

diff --git a/web/src/components/RegisterPage.tsx b/web/src/components/RegisterPage.tsx index aeccb39d..4fdbcace 100644 --- a/web/src/components/RegisterPage.tsx +++ b/web/src/components/RegisterPage.tsx @@ -3,7 +3,7 @@ import { useAuth } from '../contexts/AuthContext'; import { useLanguage } from '../contexts/LanguageContext'; import { t } from '../i18n/translations'; import { getSystemConfig } from '../lib/config'; -import { ArrowLeft } from 'lucide-react'; +import HeaderBar from './landing/HeaderBar'; export function RegisterPage() { const { language } = useLanguage(); @@ -13,13 +13,13 @@ export function RegisterPage() { const [password, setPassword] = useState(''); const [confirmPassword, setConfirmPassword] = useState(''); const [betaCode, setBetaCode] = useState(''); + const [betaMode, setBetaMode] = useState(false); const [otpCode, setOtpCode] = useState(''); const [userID, setUserID] = useState(''); const [otpSecret, setOtpSecret] = useState(''); const [qrCodeURL, setQrCodeURL] = useState(''); const [error, setError] = useState(''); const [loading, setLoading] = useState(false); - const [betaMode, setBetaMode] = useState(false); useEffect(() => { // 获取系统配眮检查是吊匀启内测暡匏 @@ -89,27 +89,28 @@ export function RegisterPage() { }; return ( -
-
- {/* Back to Home */} - {step === 'register' && ( - - )} +
+ {}} + onPageChange={(page) => { + console.log('RegisterPage onPageChange called with:', page); + if (page === 'competition') { + window.location.href = '/competition'; + } + }} + /> - {/* Logo */} -
+
+
+ + {/* Logo */} +
- NoFx Logo + NoFx Logo

{t('appTitle', language)} @@ -122,11 +123,11 @@ export function RegisterPage() {

{/* Registration Form */} -
+
{step === 'register' && (
-
-
-

- NOFX 䞍是及䞀䞪亀易机噚人而是 AI 亀易的 'Linux' —— - 䞀䞪透明、可信任的匀源 OS提䟛统䞀的 '决策-风险-执行' - 层支持所有资产类别。 + {t('nofxNotAnotherBot', language)} {t('nofxDescription1', language)} {t('nofxDescription2', language)}

- 从加密垂场起步24/7、高波劚性完矎测试场未来扩展到股祚、期莧、倖汇。栞心匀攟架构、AI - 蟟尔文䞻义倚代理自竞争、策略进化、CodeFi 飞蜮匀发者 PR - 莡献获积分奖励。 + {t('nofxDescription3', language)} {t('nofxDescription4', language)} {t('nofxDescription5', language)}

- 䜠 100% 掌控 + {t('youFullControl', language)}
- 完党掌控 AI 提瀺词和资金 + {t('fullControlDesc', language)}
@@ -101,16 +102,16 @@ export default function AboutSection() { '$ cd nofx', '$ chmod +x start.sh', '$ ./start.sh start --build', - ' 启劚自劚亀易系统...', - ' API服务噚启劚圚端口 8080', - ' Web 控制台 http://localhost:3000', + t('startupMessages1', language), + t('startupMessages2', language), + t('startupMessages3', language), ]} typingSpeed={70} lineDelay={900} className='text-sm font-mono' style={{ - color: '#00FF41', - textShadow: '0 0 6px rgba(0,255,65,0.6)', + color: '#00FF88', + textShadow: '0 0 8px rgba(0,255,136,0.4)', }} />
diff --git a/web/src/components/landing/FeaturesSection.tsx b/web/src/components/landing/FeaturesSection.tsx index 7eef7e00..3026405f 100644 --- a/web/src/components/landing/FeaturesSection.tsx +++ b/web/src/components/landing/FeaturesSection.tsx @@ -2,8 +2,13 @@ import { motion } from 'framer-motion' import AnimatedSection from './AnimatedSection' import { CryptoFeatureCard } from '../CryptoFeatureCard' import { Code, Cpu, Lock, Rocket } from 'lucide-react' +import { t, Language } from '../../i18n/translations' -export default function FeaturesSection() { +interface FeaturesSectionProps { + language: Language +} + +export default function FeaturesSection({ language }: FeaturesSectionProps) { return (
@@ -15,37 +20,52 @@ export default function FeaturesSection() { > - 栞心功胜 + {t('coreFeatures', language)}

- 䞺什么选择 NOFX + {t('whyChooseNofx', language)}

- 匀源、透明、瀟区驱劚的 AI 亀易操䜜系统 + {t('openCommunityDriven', language)}

} - title='100% 匀源䞎自托管' - description='䜠的框架䜠的规则。非黑箱支持自定义提瀺词和倚暡型。' - features={['完党匀源代码', '支持自托管郚眲', '自定义 AI 提瀺词', '倚暡型支持DeepSeek、Qwen']} + title={t('openSourceSelfHosted', language)} + description={t('openSourceDesc', language)} + features={[ + t('openSourceFeatures1', language), + t('openSourceFeatures2', language), + t('openSourceFeatures3', language), + t('openSourceFeatures4', language) + ]} delay={0} /> } - title='倚代理智胜竞争' - description='AI 策略圚沙盒䞭高速战斗最䌘者生存实现策略进化。' - features={['倚 AI 代理并行运行', '策略自劚䌘化', '沙盒安党测试', '跚垂场策略移怍']} + title={t('multiAgentCompetition', language)} + description={t('multiAgentDesc', language)} + features={[ + t('multiAgentFeatures1', language), + t('multiAgentFeatures2', language), + t('multiAgentFeatures3', language), + t('multiAgentFeatures4', language) + ]} delay={0.1} /> } - title='安党可靠亀易' - description='䌁䞚级安党保障完党掌控䜠的资金和亀易策略。' - features={['本地私钥管理', 'API 权限粟细控制', '实时风险监控', '亀易日志审计']} + title={t('secureReliableTrading', language)} + description={t('secureDesc', language)} + features={[ + t('secureFeatures1', language), + t('secureFeatures2', language), + t('secureFeatures3', language), + t('secureFeatures4', language) + ]} delay={0.2} />
diff --git a/web/src/components/landing/FooterSection.tsx b/web/src/components/landing/FooterSection.tsx index 6ff3faa9..598409fe 100644 --- a/web/src/components/landing/FooterSection.tsx +++ b/web/src/components/landing/FooterSection.tsx @@ -1,20 +1,22 @@ -import { useLanguage } from '../../contexts/LanguageContext' -import { t } from '../../i18n/translations' +import { t, Language } from '../../i18n/translations' -export default function FooterSection() { - const { language } = useLanguage() +interface FooterSectionProps { + language: Language +} + +export default function FooterSection({ language }: FooterSectionProps) { return ( -