Files
trading_bot_v4/QUICKREF_PHASE2.md
mindesbunister 2405bff68a feat: Complete Trading Bot v4 with Drift Protocol integration
Features:
- Autonomous trading system with Drift Protocol on Solana
- Real-time position monitoring with Pyth price feeds
- Dynamic stop-loss and take-profit management
- n8n workflow integration for TradingView signals
- Beautiful web UI for settings management
- REST API for trade execution and monitoring

- Next.js 15 with standalone output mode
- TypeScript with strict typing
- Docker containerization with multi-stage builds
- PostgreSQL database for trade history
- Singleton pattern for Drift client connection pooling
- BN.js for BigNumber handling (Drift SDK requirement)

- Configurable stop-loss and take-profit levels
- Breakeven trigger and profit locking
- Daily loss limits and trade cooldowns
- Slippage tolerance controls
- DRY_RUN mode for safe testing

- Real-time risk calculator
- Interactive sliders for all parameters
- Live preview of trade outcomes
- Position sizing and leverage controls
- Beautiful gradient design with Tailwind CSS

- POST /api/trading/execute - Execute trades
- POST /api/trading/close - Close positions
- GET /api/trading/positions - Monitor active trades
- GET /api/trading/check-risk - Validate trade signals
- GET /api/settings - View configuration
- POST /api/settings - Update configuration

- Fixed Borsh serialization errors (simplified order params)
- Resolved RPC rate limiting with singleton pattern
- Fixed BigInt vs BN type mismatches
- Corrected order execution flow
- Improved position state management

- Complete setup guides
- Docker deployment instructions
- n8n workflow configuration
- API reference documentation
- Risk management guidelines

- Runs on port 3001 (external), 3000 (internal)
- Uses Helius RPC for optimal performance
- Production-ready with error handling
- Health monitoring and logging
2025-10-24 14:24:36 +02:00

290 lines
4.5 KiB
Markdown

# 🚀 Phase 2 Quick Reference
## What's New
**Fully Autonomous Trading**
- Opens positions from signals
- Monitors prices in real-time
- Closes automatically at TP/SL
- Adjusts stops dynamically
---
## Quick Start
### 1. Install
```bash
./install-phase2.sh
```
### 2. Configure
```bash
# Edit .env.local:
DRIFT_WALLET_PRIVATE_KEY=your_key
SOLANA_RPC_URL=your_rpc
API_KEY=your_secret
```
### 3. Test
```bash
cd v4
# Test price monitoring
npx tsx test-price-monitor.ts
# Test position manager
npx tsx test-position-manager.ts
# Test full flow (REAL TRADE!)
npx tsx test-full-flow.ts
```
### 4. Trade
```bash
# Start server
npm run dev
# Trigger TradingView alert
# Bot handles everything!
```
---
## Key Features
### Smart Exits
- **TP1 (+0.7%)**: Close 50%, move SL to breakeven
- **TP2 (+1.5%)**: Close remaining 50%
- **SL (-1.5%)**: Close 100%
- **Emergency (-2.0%)**: Hard stop
### Dynamic SL
- After TP1: Move to breakeven
- At +1.0% profit: Move to +0.4%
- Never moves backward
- Protects all gains
### Real-Time
- Pyth WebSocket (~400ms)
- Polling fallback (2s)
- Checks every 2 seconds
- Market orders for speed
---
## API Endpoints
### Execute Trade
```bash
POST /api/trading/execute
{
"symbol": "SOLUSDT",
"direction": "long",
"timeframe": "5"
}
```
### Get Positions
```bash
GET /api/trading/positions
```
---
## Trade Example
### Entry
```
Signal: LONG SOL @ $140.00
Position: $1,000 (10x = $10,000)
SL: $137.90 (-1.5% = -$150)
TP1: $140.98 (+0.7% = +$70)
TP2: $142.10 (+1.5% = +$150)
```
### TP1 Hit
```
✅ Price: $140.98
→ Close 50% (+$70)
→ Move SL to $140.21 (breakeven)
→ Risk = $0
```
### TP2 Hit
```
✅ Price: $142.10
→ Close 50% (+$150)
→ Total P&L: +$220 (+22%)
→ Trade complete!
```
---
## Testing Checklist
- [ ] Run install-phase2.sh
- [ ] Configure .env.local
- [ ] Test price monitor (no risk)
- [ ] Test position manager (no risk)
- [ ] Test full flow with $10-50 position
- [ ] Watch first 5-10 auto-exits
- [ ] Verify on Drift UI
- [ ] Scale up gradually
---
## Configuration
### Risk Parameters
```env
MAX_POSITION_SIZE_USD=1000
LEVERAGE=10
STOP_LOSS_PERCENT=-1.5
TAKE_PROFIT_1_PERCENT=0.7
TAKE_PROFIT_2_PERCENT=1.5
EMERGENCY_STOP_PERCENT=-2.0
```
### Monitoring
```env
PRICE_CHECK_INTERVAL_MS=2000
SLIPPAGE_TOLERANCE=1.0
```
---
## Troubleshooting
### "Cannot find module"
```bash
npm install @pythnetwork/price-service-client
```
### "Drift service not initialized"
```bash
# Check .env.local has:
DRIFT_WALLET_PRIVATE_KEY=...
SOLANA_RPC_URL=...
```
### "WebSocket disconnected"
```
Normal - will reconnect automatically
Polling fallback handles updates
```
### "Position not closing"
```
Check:
1. Is price hitting targets?
2. Are logs showing price checks?
3. Is position manager running?
Most likely: Targets not hit yet!
```
---
## Performance Targets
### 5-Minute Scalping
- **Win Rate**: 60-70%
- **Avg Win**: +7% to +22%
- **Avg Loss**: -15%
- **Daily Target**: +2% to +5%
- **Trades/Day**: 5-15
### Example Day
```
Trade 1: +7% (TP1)
Trade 2: +22% (TP1+TP2)
Trade 3: -15% (SL)
Trade 4: +7% (TP1)
Trade 5: +22% (TP1+TP2)
Daily: +43% 🎉
```
---
## Safety Rules
1. **Start small**: $10-50 positions
2. **Monitor closely**: First 10 trades
3. **Verify exits**: Check Drift UI
4. **Scale gradually**: Increase 2x weekly
5. **Max risk**: Never > 20% per trade
---
## Documentation
- `PHASE_2_COMPLETE.md` - Full features
- `PHASE_2_SUMMARY.md` - Overview
- `TESTING.md` - Testing guide
- `SETUP.md` - Setup instructions
- `TRADING_BOT_V4_MANUAL.md` - Complete manual
---
## What's Next (Phase 3)
- Database integration
- Trade history persistence
- Risk manager enforcement
- Enhanced notifications
- Performance analytics
- Web dashboard
**But you can trade NOW!**
---
## Support
### Common Commands
```bash
# Install Phase 2
./install-phase2.sh
# Test monitoring
cd v4 && npx tsx test-price-monitor.ts
# Test manager
cd v4 && npx tsx test-position-manager.ts
# Test full flow
cd v4 && npx tsx test-full-flow.ts
# Start server
npm run dev
# Check positions
curl http://localhost:3000/api/trading/positions \
-H "Authorization: Bearer YOUR_API_KEY"
```
### Files Changed
```
New:
+ v4/lib/pyth/price-monitor.ts
+ v4/lib/trading/position-manager.ts
+ v4/app/api/trading/positions/route.ts
+ v4/test-price-monitor.ts
+ v4/test-position-manager.ts
+ v4/test-full-flow.ts
+ v4/PHASE_2_COMPLETE.md
+ v4/PHASE_2_SUMMARY.md
+ v4/TESTING.md
+ install-phase2.sh
Updated:
~ v4/app/api/trading/execute/route.ts
~ v4/SETUP.md
```
---
**Phase 2 Complete! Let the bot trade! 🚀**
*Start small, monitor closely, scale gradually!*