docs: Enhance bug report template and add comprehensive troubleshooting guide

- Enhanced bug report template with detailed log capture instructions
  - Added bug categorization system (6 main categories)
  - Frontend error capture guide (DevTools Console/Network tabs)
  - Backend log capture for Docker and PM2 deployments
  - Trading/decision logs location and usage
  - Comprehensive environment information checklist
  - Quick diagnostic tips for faster issue resolution
- Created bilingual troubleshooting guides (EN/ZH)
  - Common trading issues (e.g., Issue #202: only short positions)
  - Detailed explanation of Binance position mode requirements
  - AI decision problems and diagnostics
  - Connection and API error solutions
  - Frontend and database issues
  - Complete log capture instructions with commands
  - Emergency reset procedures
- Updated documentation cross-references
  - Added troubleshooting guide links to bug report template
  - Added links in README Common Issues section
  - Bilingual support for better accessibility
This reduces maintainer workload by helping users self-diagnose issues
and submit higher-quality bug reports with all necessary information.
Addresses Issue #202 root cause documentation.
Co-Authored-By: tinkle-community <tinklefund@gmail.com>
This commit is contained in:
Liu Xiang Qian
2025-11-02 09:58:30 +08:00
parent de6f602a5a
commit b1a0f015d7
4 changed files with 1082 additions and 16 deletions
+136 -16
View File
@@ -6,42 +6,162 @@ labels: bug
assignees: ''
---
> **⚠️ Before submitting:** Please check the [Troubleshooting Guide](../../docs/guides/TROUBLESHOOTING.md) ([中文版](../../docs/guides/TROUBLESHOOTING.zh-CN.md)) to see if your issue can be resolved quickly.
## 🐛 Bug Description
<!-- A clear and concise description of what the bug is -->
## 🔍 Bug Category
<!-- Check the category that best describes this bug -->
- [ ] Trading execution (orders not executing, wrong position size, etc.)
- [ ] AI decision issues (unexpected decisions, only opening one direction, etc.)
- [ ] Exchange connection (API errors, authentication failures, etc.)
- [ ] UI/Frontend (display issues, buttons not working, data not updating, etc.)
- [ ] Backend/API (server errors, crashes, performance issues, etc.)
- [ ] Configuration (settings not saving, database errors, etc.)
- [ ] Other: _________________
## 📋 Steps to Reproduce
1. Go to '...'
2. Click on '...'
3. Run command '...'
2. Click on '...' / Run command '...'
3. Configure '...'
4. See error
## ✅ Expected Behavior
<!-- What you expected to happen -->
## ❌ Actual Behavior
<!-- What actually happened -->
## 📸 Screenshots / Logs
<!-- If applicable, add screenshots or error logs to help explain your problem -->
## 📸 Screenshots & Logs
### Frontend Error (if applicable)
<!-- How to capture frontend errors: -->
<!-- 1. Open browser DevTools (F12 or Right-click → Inspect) -->
<!-- 2. Go to "Console" tab to see JavaScript errors -->
<!-- 3. Screenshot the error messages -->
<!-- 4. Check "Network" tab for failed API requests (show status code & response) -->
**Browser Console Screenshot:**
<!-- Paste screenshot here -->
**Network Tab (failed requests):**
<!-- Paste screenshot of failed API calls here -->
### Backend Logs (if applicable)
<!-- How to capture backend logs: -->
**Docker users:**
```bash
# View backend logs
docker compose logs backend --tail=100
# OR continuously follow logs
docker compose logs -f backend
```
Paste logs here
**Manual/PM2 users:**
```bash
# Terminal output where you ran: ./nofx
# OR PM2 logs:
pm2 logs nofx --lines 100
```
**Backend Log Output:**
```
Paste backend logs here (last 50-100 lines around the error)
```
### Trading/Decision Logs (if trading issue)
<!-- Decision logs are saved in: decision_logs/{trader_id}/ -->
<!-- Find the latest JSON file and paste relevant parts -->
**Decision Log Path:** `decision_logs/{trader_id}/{timestamp}.json`
```json
{
"paste relevant decision log here if applicable"
}
```
## 💻 Environment
**System:**
- **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]
- **Deployment:** [Docker / Manual / PM2]
**Backend:**
- **Go Version:** [run: `go version`]
- **NOFX Version:** [run: `git log -1 --oneline` or check release tag]
**Frontend:**
- **Browser:** [e.g. Chrome 120, Firefox 121, Safari 17]
- **Node.js Version:** [run: `node -v`]
**Trading Setup:**
- **Exchange:** [Binance / Hyperliquid / Aster]
- **Account Type:** [Main Account / Subaccount]
- **Position Mode:** [Hedge Mode (Dual) / One-way Mode] ← **Important for trading bugs!**
- **AI Model:** [DeepSeek / Qwen / Custom]
- **Number of Traders:** [e.g. 1, 2, etc.]
## 🔧 Additional Context
<!-- Add any other context about the problem here -->
## 🔧 Configuration (if relevant)
<!-- Only include non-sensitive parts of your config -->
<!-- ⚠️ NEVER paste API keys or private keys! -->
- Does this happen consistently or intermittently?
- Did it work before? When did it break?
- Any recent configuration changes?
**Leverage Settings:**
```json
{
"btc_eth_leverage": 5,
"altcoin_leverage": 5
}
```
## ✋ Possible Solution
<!-- Optional: If you have ideas on how to fix this -->
**Any custom settings:**
<!-- e.g. modified scan_interval, custom coin list, etc. -->
## 📊 Additional Context
**Frequency:**
- [ ] Happens every time
- [ ] Happens randomly
- [ ] Happened once
**Timeline:**
- Did this work before? [ ] Yes [ ] No
- When did it break? [e.g. after upgrade to v3.0.0, after changing config, etc.]
- Recent changes? [e.g. updated dependencies, changed exchange, etc.]
**Impact:**
- [ ] System cannot start
- [ ] Trading stopped/broken
- [ ] UI broken but trading works
- [ ] Minor visual issue
- [ ] Other: _________________
## 💡 Possible Solution
<!-- Optional: If you have ideas on how to fix this, or workarounds you've tried -->
---
## 📝 Quick Tips for Faster Resolution
**For Trading Issues:**
1. ✅ Check Binance position mode: Go to Futures → ⚙️ Preferences → Position Mode → Must be **Hedge Mode**
2. ✅ Verify API permissions: Futures trading must be enabled
3. ✅ Check decision logs in `decision_logs/{trader_id}/` for AI reasoning
**For Connection Issues:**
4. ✅ Test API connectivity: `curl http://localhost:8080/api/health`
5. ✅ Check API rate limits on exchange
6. ✅ Verify API keys are not expired
**For UI Issues:**
7. ✅ Hard refresh: Ctrl+Shift+R (or Cmd+Shift+R on Mac)
8. ✅ Check browser console (F12) for errors
9. ✅ Verify backend is running: `docker compose ps` or `ps aux | grep nofx`
+2
View File
@@ -1168,6 +1168,8 @@ GET /api/health # Health check
## 🛠️ Common Issues
> 📖 **For detailed troubleshooting:** See the comprehensive [Troubleshooting Guide](docs/guides/TROUBLESHOOTING.md) ([中文版](docs/guides/TROUBLESHOOTING.zh-CN.md))
### 1. Compilation error: TA-Lib not found
**Solution**: Install TA-Lib library
+472
View File
@@ -0,0 +1,472 @@
# 🔧 Troubleshooting Guide
This guide helps you diagnose and fix common issues before submitting a bug report.
---
## 📋 Quick Diagnostic Checklist
Before reporting a bug, please check:
1.**Backend is running**: `docker compose ps` or `ps aux | grep nofx`
2.**Frontend is accessible**: Open http://localhost:3000 in browser
3.**API is responding**: `curl http://localhost:8080/api/health`
4.**Check logs for errors**: See [How to Capture Logs](#how-to-capture-logs) below
---
## 🐛 Common Issues & Solutions
### 1. Trading Issues
#### ❌ Only Opening Short Positions (Issue #202)
**Symptom:** AI only opens short positions, never long positions, even when market is bullish.
**Root Cause:** Binance account is in **One-way Mode** instead of **Hedge Mode**.
**Solution:**
1. Login to [Binance Futures](https://www.binance.com/futures/BTCUSDT)
2. Click **⚙️ Preferences** (top right)
3. Select **Position Mode**
4. Switch to **Hedge Mode** (双向持仓)
5. ⚠️ **Important:** Close all positions before switching
**Why this happens:**
- Code uses `PositionSide(LONG)` and `PositionSide(SHORT)` parameters
- These only work in Hedge Mode
- In One-way Mode, orders fail or only one direction works
**For Subaccounts:**
- Some Binance subaccounts may not have permission to change position mode
- Use main account or contact Binance support to enable this permission
---
#### ❌ Order Error: `code=-4061` Position Side Mismatch
**Error Message:** `Order's position side does not match user's setting`
**Solution:** Same as above - switch to Hedge Mode.
---
#### ❌ Leverage Error: `Subaccounts restricted to 5x leverage`
**Symptom:** Orders fail with leverage error when trying to use >5x leverage.
**Solution:**
1. Open Web UI → Trader Settings
2. Set leverage to 5x or lower:
```json
{
"btc_eth_leverage": 5,
"altcoin_leverage": 5
}
```
3. Or use main account (supports up to 50x BTC/ETH, 20x altcoins)
---
#### ❌ Positions Not Executing
**Check these:**
1. **API Permissions**:
- Go to Binance → API Management
- Verify "Enable Futures" is checked
- Check IP whitelist (if enabled)
2. **Account Balance**:
- Ensure sufficient USDT in Futures wallet
- Check margin usage is not at 100%
3. **Symbol Status**:
- Verify trading pair is active on exchange
- Check if symbol is in maintenance mode
4. **Decision Logs**:
```bash
# Check latest decision
ls -lt decision_logs/your_trader_id/ | head -5
cat decision_logs/your_trader_id/latest_file.json
```
- Look for AI decision: was it "wait", "hold", or actual trade?
- Check if position_size_usd is within limits
---
### 2. AI Decision Issues
#### ❌ AI Always Says "Wait" / "Hold"
**Possible Causes:**
1. **Market Conditions**: AI may genuinely see no good opportunities
2. **Risk Limits**: Account equity too low, margin usage too high
3. **Historical Performance**: AI being cautious after losses
**How to Check:**
```bash
# View latest decision reasoning
cat decision_logs/your_trader_id/$(ls -t decision_logs/your_trader_id/ | head -1)
```
Look at the AI's Chain-of-Thought reasoning section.
**Solutions:**
- Wait for better market conditions
- Check if all candidate coins have low liquidity
- Verify `use_default_coins: true` or coin pool API is working
---
#### ❌ AI Making Bad Decisions
**Remember:** AI trading is experimental and not guaranteed to be profitable.
**Things to Check:**
1. **Decision Interval**: Is it too short? (Recommended: 3-5 minutes)
2. **Leverage Settings**: Too aggressive?
3. **Historical Feedback**: Check performance logs to see if AI is learning
4. **Market Volatility**: High volatility = higher risk
**Adjustments:**
- Reduce leverage for more conservative trading
- Increase decision interval to reduce over-trading
- Use smaller initial balance for testing
---
### 3. Connection & API Issues
#### ❌ Backend Won't Start
**Error:** `port 8080 already in use`
**Solution:**
```bash
# Find what's using the port
lsof -i :8080
# OR
netstat -tulpn | grep 8080
# Kill the process or change port in .env
NOFX_BACKEND_PORT=8081
```
---
#### ❌ Frontend Can't Connect to Backend
**Symptoms:**
- UI shows "Loading..." forever
- Browser console shows 404 or network errors
**Solutions:**
1. **Check backend is running:**
```bash
docker compose ps # Should show backend as "Up"
# OR
curl http://localhost:8080/api/health # Should return {"status":"ok"}
```
2. **Check port configuration:**
- Backend default: 8080
- Frontend default: 3000
- Verify `.env` settings match
3. **CORS Issues:**
- If running frontend and backend on different ports/domains
- Check browser console for CORS errors
- Backend should allow frontend origin
---
#### ❌ Exchange API Errors
**Error:** `invalid signature` / `timestamp` errors
**Solutions:**
1. **Check System Time:**
```bash
date # Should be accurate
# If wrong, sync with NTP:
sudo ntpdate -s time.nist.gov
```
2. **Verify API Keys:**
- Not expired
- Have correct permissions (Futures enabled)
- IP whitelist includes your server IP
3. **Rate Limits:**
- Binance has strict rate limits
- Reduce number of traders or decision frequency
---
### 4. Frontend Issues
#### ❌ UI Not Updating / Showing Old Data
**Solutions:**
1. **Hard Refresh:**
- Chrome/Firefox: `Ctrl+Shift+R` (Windows/Linux) or `Cmd+Shift+R` (Mac)
- Safari: `Cmd+Option+R`
2. **Clear Browser Cache:**
- Settings → Privacy → Clear browsing data
- Or open in Incognito/Private mode
3. **Check SWR Polling:**
- Frontend uses SWR with 5-10s intervals
- Data should auto-refresh
- Check browser console for fetch errors
---
#### ❌ Charts Not Rendering
**Possible Causes:**
1. No historical data yet (system just started)
2. JavaScript errors in console
3. Browser compatibility issues
**Solutions:**
- Wait 5-10 minutes for data to accumulate
- Check browser console (F12) for errors
- Try different browser (Chrome recommended)
- Ensure backend API endpoints are returning data
---
### 5. Database Issues
#### ❌ `database is locked` Error
**Cause:** SQLite database being accessed by multiple processes.
**Solution:**
```bash
# Stop all NOFX processes
docker compose down
# OR
pkill nofx
# Restart
docker compose up -d
# OR
./nofx
```
---
#### ❌ Trader Configuration Not Saving
**Check:**
1. **Permissions:**
```bash
ls -l config.db trading.db
# Should be writable by current user
```
2. **Disk Space:**
```bash
df -h # Ensure disk not full
```
3. **Database Integrity:**
```bash
sqlite3 config.db "PRAGMA integrity_check;"
```
---
## 📊 How to Capture Logs
### Backend Logs
**Docker:**
```bash
# View last 100 lines
docker compose logs backend --tail=100
# Follow live logs
docker compose logs -f backend
# Save to file
docker compose logs backend --tail=500 > backend_logs.txt
```
**Manual/PM2:**
```bash
# Terminal where you ran ./nofx shows logs
# PM2:
pm2 logs nofx --lines 100
# Save to file
pm2 logs nofx --lines 500 > backend_logs.txt
```
---
### Frontend Logs (Browser Console)
1. **Open DevTools:**
- Press `F12` or Right-click → Inspect
2. **Console Tab:**
- See JavaScript errors and warnings
- Look for red error messages
3. **Network Tab:**
- Filter by "XHR" or "Fetch"
- Look for failed requests (red status codes)
- Click on failed request → Preview/Response to see error details
4. **Capture Screenshot:**
- Windows: `Win+Shift+S`
- Mac: `Cmd+Shift+4`
- Or use browser DevTools screenshot feature
---
### Decision Logs (Trading Issues)
```bash
# List recent decision logs
ls -lt decision_logs/your_trader_id/ | head -10
# View latest decision
cat decision_logs/your_trader_id/$(ls -t decision_logs/your_trader_id/ | head -1) | jq .
# Search for specific symbol
grep -r "BTCUSDT" decision_logs/your_trader_id/
# Find decisions that resulted in trades
grep -r '"action": "open_' decision_logs/your_trader_id/
```
**What to look for in decision logs:**
- `chain_of_thought`: AI's reasoning process
- `user_prompt`: Market data AI received
- `decision`: Final decision (action, symbol, leverage, etc.)
- `account_state`: Account balance, margin, positions at decision time
- `execution_result`: Whether trade succeeded or failed
---
## 🔍 Diagnostic Commands
### System Health Check
```bash
# Backend health
curl http://localhost:8080/api/health
# List all traders
curl http://localhost:8080/api/traders
# Check specific trader status
curl http://localhost:8080/api/status?trader_id=your_trader_id
# Get account info
curl http://localhost:8080/api/account?trader_id=your_trader_id
```
### Docker Status
```bash
# Check all containers
docker compose ps
# Check resource usage
docker stats
# Restart specific service
docker compose restart backend
docker compose restart frontend
```
### Database Queries
```bash
# Check traders in database
sqlite3 config.db "SELECT id, name, ai_model_id, exchange_id, is_running FROM traders;"
# Check AI models
sqlite3 config.db "SELECT id, name, model_type, enabled FROM ai_models;"
# Check system config
sqlite3 config.db "SELECT key, value FROM system_config;"
```
---
## 📝 Still Having Issues?
If you've tried all the above and still have problems:
1. **Gather Information:**
- Backend logs (last 100 lines)
- Frontend console screenshot
- Decision logs (if trading issue)
- Your environment details
2. **Submit Bug Report:**
- Use the [Bug Report Template](../../.github/ISSUE_TEMPLATE/bug_report.md)
- Include all logs and screenshots
- Describe what you've already tried
3. **Join Community:**
- [Telegram Developer Community](https://t.me/nofx_dev_community)
- [GitHub Discussions](https://github.com/tinkle-community/nofx/discussions)
---
## 🆘 Emergency: System Completely Broken
**Complete Reset (⚠️ Will lose trading history):**
```bash
# Stop everything
docker compose down
# Backup databases (just in case)
cp config.db config.db.backup
cp trading.db trading.db.backup
# Remove databases (fresh start)
rm config.db trading.db
# Restart
docker compose up -d --build
# Reconfigure through web UI
open http://localhost:3000
```
**Partial Reset (Keep configuration, clear logs):**
```bash
# Clear decision logs
rm -rf decision_logs/*
# Clear Docker cache and rebuild
docker compose down
docker compose build --no-cache
docker compose up -d
```
---
## 📚 Additional Resources
- **[FAQ](faq.en.md)** - Frequently Asked Questions
- **[Getting Started](../getting-started/README.md)** - Setup guide
- **[Architecture Docs](../architecture/README.md)** - How the system works
- **[CLAUDE.md](../../CLAUDE.md)** - Developer documentation
---
**Last Updated:** 2025-11-02
+472
View File
@@ -0,0 +1,472 @@
# 🔧 故障排查指南
本指南帮助您在提交 bug 报告前自行诊断和修复常见问题。
---
## 📋 快速诊断清单
提交 bug 前,请检查:
1.**后端正在运行**: `docker compose ps``ps aux | grep nofx`
2.**前端可访问**: 在浏览器打开 http://localhost:3000
3.**API 正常响应**: `curl http://localhost:8080/api/health`
4.**检查日志中的错误**: 参见下方 [如何捕获日志](#如何捕获日志)
---
## 🐛 常见问题与解决方案
### 1. 交易问题
#### ❌ 只开空单,不开多单 (Issue #202)
**症状:** AI 只开空仓,从不开多仓,即使市场看涨。
**根本原因:** 币安账户处于**单向持仓模式**而非**双向持仓模式**。
**解决方案:**
1. 登录 [币安合约交易](https://www.binance.com/zh-CN/futures/BTCUSDT)
2. 点击右上角 **⚙️ 偏好设置**
3. 选择 **持仓模式**
4. 切换为 **双向持仓** (Hedge Mode)
5. ⚠️ **重要:** 切换前必须先平掉所有持仓
**为什么会这样:**
- 代码使用 `PositionSide(LONG)``PositionSide(SHORT)` 参数
- 这些参数只在双向持仓模式下有效
- 在单向持仓模式下,订单会失败或只有一个方向有效
**关于子账户:**
- 部分币安子账户可能没有权限更改持仓模式
- 使用主账户或联系币安客服开通此权限
---
#### ❌ 订单错误: `code=-4061` 持仓方向不匹配
**错误信息:** `Order's position side does not match user's setting`
**解决方案:** 同上 - 切换到双向持仓模式。
---
#### ❌ 杠杆错误: `子账户限制最高5倍杠杆`
**症状:** 尝试使用 >5倍杠杆时订单失败。
**解决方案:**
1. 打开 Web 界面 → 交易员设置
2. 将杠杆设置为 5倍或更低:
```json
{
"btc_eth_leverage": 5,
"altcoin_leverage": 5
}
```
3. 或使用主账户(支持最高 50倍 BTC/ETH,20倍山寨币)
---
#### ❌ 持仓无法执行
**检查以下内容:**
1. **API 权限**:
- 进入币安 → API 管理
- 确认"启用合约"已勾选
- 检查 IP 白名单(如果启用)
2. **账户余额**:
- 确保合约钱包中有足够的 USDT
- 检查保证金使用率未达到 100%
3. **交易对状态**:
- 确认交易对在交易所处于活跃状态
- 检查交易对是否处于维护模式
4. **决策日志**:
```bash
# 检查最新决策
ls -lt decision_logs/your_trader_id/ | head -5
cat decision_logs/your_trader_id/latest_file.json
```
- 查看 AI 决策:是"wait"、"hold"还是实际交易?
- 检查 position_size_usd 是否在限制范围内
---
### 2. AI 决策问题
#### ❌ AI 总是说"等待"/"持有"
**可能原因:**
1. **市场情况**: AI 可能确实没看到好的机会
2. **风险限制**: 账户净值太低、保证金使用率太高
3. **历史表现**: AI 在亏损后变得谨慎
**如何检查:**
```bash
# 查看最新决策推理
cat decision_logs/your_trader_id/$(ls -t decision_logs/your_trader_id/ | head -1)
```
查看 AI 的思维链(Chain-of-Thought)推理部分。
**解决方案:**
- 等待更好的市场条件
- 检查候选币种是否流动性都太低
- 确认 `use_default_coins: true` 或币种池 API 正常工作
---
#### ❌ AI 做出错误决策
**请记住:** AI 交易是实验性的,不保证盈利。
**需要检查的事项:**
1. **决策间隔**: 是否太短?(推荐: 3-5分钟)
2. **杠杆设置**: 是否过于激进?
3. **历史反馈**: 查看表现日志,看 AI 是否在学习
4. **市场波动**: 高波动 = 更高风险
**调整建议:**
- 降低杠杆以实现更保守的交易
- 增加决策间隔以减少过度交易
- 使用较小的初始余额进行测试
---
### 3. 连接和 API 问题
#### ❌ 后端无法启动
**错误:** `port 8080 already in use`
**解决方案:**
```bash
# 查找占用端口的进程
lsof -i :8080
# 或
netstat -tulpn | grep 8080
# 杀死进程或在 .env 中更改端口
NOFX_BACKEND_PORT=8081
```
---
#### ❌ 前端无法连接后端
**症状:**
- UI 显示"加载中..."一直不结束
- 浏览器控制台显示 404 或网络错误
**解决方案:**
1. **检查后端是否运行:**
```bash
docker compose ps # 应显示 backend 为 "Up"
# 或
curl http://localhost:8080/api/health # 应返回 {"status":"ok"}
```
2. **检查端口配置:**
- 后端默认: 8080
- 前端默认: 3000
- 确认 `.env` 设置匹配
3. **CORS 问题:**
- 如果前端和后端运行在不同端口/域名
- 检查浏览器控制台的 CORS 错误
- 后端应允许前端来源
---
#### ❌ 交易所 API 错误
**错误:** `invalid signature` / `timestamp` 错误
**解决方案:**
1. **检查系统时间:**
```bash
date # 应该准确
# 如果错误,与 NTP 同步:
sudo ntpdate -s time.nist.gov
```
2. **验证 API 密钥:**
- 未过期
- 有正确权限(已启用合约)
- IP 白名单包含您的服务器 IP
3. **速率限制:**
- 币安有严格的速率限制
- 减少交易员数量或决策频率
---
### 4. 前端问题
#### ❌ UI 不更新 / 显示旧数据
**解决方案:**
1. **强制刷新:**
- Chrome/Firefox: `Ctrl+Shift+R` (Windows/Linux) 或 `Cmd+Shift+R` (Mac)
- Safari: `Cmd+Option+R`
2. **清除浏览器缓存:**
- 设置 → 隐私 → 清除浏览数据
- 或在无痕/隐私模式下打开
3. **检查 SWR 轮询:**
- 前端使用 5-10秒间隔的 SWR
- 数据应自动刷新
- 检查浏览器控制台是否有 fetch 错误
---
#### ❌ 图表不渲染
**可能原因:**
1. 暂无历史数据(系统刚启动)
2. 控制台中有 JavaScript 错误
3. 浏览器兼容性问题
**解决方案:**
- 等待 5-10 分钟让数据积累
- 检查浏览器控制台(F12)是否有错误
- 尝试不同浏览器(推荐 Chrome)
- 确保后端 API 端点正在返回数据
---
### 5. 数据库问题
#### ❌ `database is locked` 错误
**原因:** SQLite 数据库被多个进程访问。
**解决方案:**
```bash
# 停止所有 NOFX 进程
docker compose down
# 或
pkill nofx
# 重启
docker compose up -d
# 或
./nofx
```
---
#### ❌ 交易员配置无法保存
**检查:**
1. **权限:**
```bash
ls -l config.db trading.db
# 应该对当前用户可写
```
2. **磁盘空间:**
```bash
df -h # 确保磁盘未满
```
3. **数据库完整性:**
```bash
sqlite3 config.db "PRAGMA integrity_check;"
```
---
## 📊 如何捕获日志
### 后端日志
**Docker:**
```bash
# 查看最后 100 行
docker compose logs backend --tail=100
# 实时跟踪日志
docker compose logs -f backend
# 保存到文件
docker compose logs backend --tail=500 > backend_logs.txt
```
**手动/PM2:**
```bash
# 运行 ./nofx 的终端会显示日志
# PM2:
pm2 logs nofx --lines 100
# 保存到文件
pm2 logs nofx --lines 500 > backend_logs.txt
```
---
### 前端日志(浏览器控制台)
1. **打开开发者工具:**
- 按 `F12` 或右键 → 检查
2. **Console(控制台)标签:**
- 查看 JavaScript 错误和警告
- 寻找红色错误消息
3. **Network(网络)标签:**
- 按"XHR"或"Fetch"筛选
- 查找失败的请求(红色状态码)
- 点击失败的请求 → Preview/Response 查看错误详情
4. **捕获截图:**
- Windows: `Win+Shift+S`
- Mac: `Cmd+Shift+4`
- 或使用浏览器开发者工具截图功能
---
### 决策日志(交易问题)
```bash
# 列出最近的决策日志
ls -lt decision_logs/your_trader_id/ | head -10
# 查看最新决策
cat decision_logs/your_trader_id/$(ls -t decision_logs/your_trader_id/ | head -1) | jq .
# 搜索特定交易对
grep -r "BTCUSDT" decision_logs/your_trader_id/
# 查找执行交易的决策
grep -r '"action": "open_' decision_logs/your_trader_id/
```
**决策日志中要查看的内容:**
- `chain_of_thought`: AI 的推理过程
- `user_prompt`: AI 收到的市场数据
- `decision`: 最终决策(动作、交易对、杠杆等)
- `account_state`: 决策时的账户余额、保证金、持仓
- `execution_result`: 交易是否成功
---
## 🔍 诊断命令
### 系统健康检查
```bash
# 后端健康状态
curl http://localhost:8080/api/health
# 列出所有交易员
curl http://localhost:8080/api/traders
# 检查特定交易员状态
curl http://localhost:8080/api/status?trader_id=your_trader_id
# 获取账户信息
curl http://localhost:8080/api/account?trader_id=your_trader_id
```
### Docker 状态
```bash
# 检查所有容器
docker compose ps
# 检查资源使用
docker stats
# 重启特定服务
docker compose restart backend
docker compose restart frontend
```
### 数据库查询
```bash
# 检查数据库中的交易员
sqlite3 config.db "SELECT id, name, ai_model_id, exchange_id, is_running FROM traders;"
# 检查 AI 模型
sqlite3 config.db "SELECT id, name, model_type, enabled FROM ai_models;"
# 检查系统配置
sqlite3 config.db "SELECT key, value FROM system_config;"
```
---
## 📝 仍有问题?
如果尝试了上述所有方法仍有问题:
1. **收集信息:**
- 后端日志(最后 100 行)
- 前端控制台截图
- 决策日志(如果是交易问题)
- 您的环境详情
2. **提交 Bug 报告:**
- 使用 [Bug 报告模板](../../.github/ISSUE_TEMPLATE/bug_report.md)
- 包含所有日志和截图
- 描述您已尝试的方法
3. **加入社区:**
- [Telegram 开发者社区](https://t.me/nofx_dev_community)
- [GitHub Discussions](https://github.com/tinkle-community/nofx/discussions)
---
## 🆘 紧急情况:系统完全损坏
**完全重置 (⚠️ 将丢失交易历史):**
```bash
# 停止所有服务
docker compose down
# 备份数据库(以防万一)
cp config.db config.db.backup
cp trading.db trading.db.backup
# 删除数据库(全新开始)
rm config.db trading.db
# 重启
docker compose up -d --build
# 通过 Web UI 重新配置
open http://localhost:3000
```
**部分重置(保留配置,清除日志):**
```bash
# 清除决策日志
rm -rf decision_logs/*
# 清除 Docker 缓存并重建
docker compose down
docker compose build --no-cache
docker compose up -d
```
---
## 📚 其他资源
- **[FAQ](faq.zh-CN.md)** - 常见问题
- **[快速开始](../getting-started/README.zh-CN.md)** - 安装指南
- **[架构文档](../architecture/README.zh-CN.md)** - 系统工作原理
- **[CLAUDE.md](../../CLAUDE.md)** - 开发者文档
---
**最后更新:** 2025-11-02