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
This commit is contained in:
mindesbunister
2025-10-24 14:24:36 +02:00
commit 2405bff68a
45 changed files with 15683 additions and 0 deletions

328
PHASE_1_COMPLETE.md Normal file
View File

@@ -0,0 +1,328 @@
# Trading Bot v4 - Phase 1 Complete! 🎉
## ✅ What's Been Built
### Core Components
1. **Configuration System** (`v4/config/trading.ts`)
- Trading parameters (leverage, stops, targets)
- Market configurations (SOL, BTC, ETH)
- Environment variable support
- Validation and merging logic
2. **Drift Integration** (`v4/lib/drift/`)
- `client.ts` - Drift SDK client wrapper
- `orders.ts` - Market order execution (open/close)
- Account health monitoring
- Position tracking
- Oracle price feeds
3. **API Endpoints** (`v4/app/api/trading/`)
- `execute/route.ts` - Execute trades from n8n
- `check-risk/route.ts` - Pre-trade risk validation
- Authentication with API keys
- Error handling
4. **Documentation**
- `SETUP.md` - Detailed setup instructions
- `.env.example` - Environment template
- `test-drift-v4.ts` - Integration test script
### n8n Integration
- ✅ Workflow JSON exported (`n8n-workflow-v4.json`)
- ✅ TradingView webhook → n8n → Trading Bot flow
- ✅ Multi-channel notifications (Telegram/Discord)
- ✅ Risk checks before execution
- ✅ Trade confirmation messages
## 🎯 How It Works
### Signal Flow
```
1. TradingView Alert (5min chart, green/red dot)
2. Webhook to n8n (with secret validation)
3. n8n extracts signal data
4. n8n calls /api/trading/check-risk
5. If approved, n8n calls /api/trading/execute
6. Bot opens position on Drift Protocol
7. n8n sends Telegram/Discord notification
8. Trade is live! (monitoring in Phase 2)
```
### Example Trade Execution
```
Signal: BUY SOLUSDT @ $100.00
Configuration:
- Position: $1,000
- Leverage: 10x
- Total: $10,000
Order Placement:
✅ Market buy executed
✅ Fill price: $100.02 (0.02% slippage)
✅ Size: 99.98 SOL
Targets Set:
🔴 Stop Loss: $98.52 (-1.5% = -$150 account loss)
🟡 TP1 (50%): $100.72 (+0.7% = +$70 account gain)
🟢 TP2 (50%): $101.52 (+1.5% = +$150 account gain)
Status: Position active, monitoring will start in Phase 2
```
## 🧪 Testing
### Test Your Setup
```bash
# 1. Navigate to v4 directory
cd v4
# 2. Run integration test
npx tsx test-drift-v4.ts
# Expected output:
# ✅ Config loaded
# ✅ Drift service initialized
# ✅ USDC Balance: $XXX.XX
# ✅ Account health: ...
# ✅ All tests passed!
```
### Test API Endpoints
```bash
# 1. Start Next.js server
npm run dev
# 2. Test risk check
curl -X POST http://localhost:3000/api/trading/check-risk \
-H "Authorization: Bearer YOUR_API_SECRET_KEY" \
-H "Content-Type: application/json" \
-d '{"symbol":"SOL-PERP","direction":"long"}'
# Expected: {"allowed":true,"details":"All risk checks passed"}
```
### Test Full Flow (CAREFUL!)
```bash
# This will open a REAL position!
curl -X POST http://localhost:3000/api/trading/execute \
-H "Authorization: Bearer YOUR_API_SECRET_KEY" \
-H "Content-Type: application/json" \
-d '{
"symbol": "SOLUSDT",
"direction": "long",
"timeframe": "5",
"signalStrength": "strong"
}'
```
## 🚧 What's Missing (Phase 2)
### Critical Components
1. **Price Monitoring System**
- Pyth WebSocket integration
- Real-time price updates (every 2s)
- Price cache management
2. **Position Manager**
- Track active trades
- Monitor P&L in real-time
- Handle multiple concurrent positions
3. **Auto Exit Logic**
- Check SL/TP1/TP2 conditions
- Execute market closes automatically
- Move SL to breakeven after TP1
- Lock profit at triggers
4. **Risk Manager**
- Daily P&L tracking
- Trades per hour limiting
- Cooldown enforcement
- Account health monitoring
5. **Database Integration**
- Save trades to PostgreSQL
- Trade history
- P&L reporting
- Performance analytics
6. **Notifications**
- Telegram trade updates
- Discord rich embeds
- Email reports
- Exit notifications
## 📝 Setup Checklist
Before going live:
- [ ] `.env.local` configured with all required variables
- [ ] Drift wallet funded with USDC
- [ ] Drift account initialized at drift.trade
- [ ] Test script passes (`npx tsx v4/test-drift-v4.ts`)
- [ ] n8n workflow imported and activated
- [ ] n8n environment variables set
- [ ] Telegram bot configured
- [ ] TradingView alert created
- [ ] Test alert triggered successfully
- [ ] Small test trade executed successfully ($100)
- [ ] Position verified in Drift UI
## 🎬 Quick Start Guide
### 1. Environment Setup
```bash
# Copy environment template
cp v4/.env.example .env.local
# Edit .env.local and add:
# - DRIFT_WALLET_PRIVATE_KEY
# - API_SECRET_KEY
# - SOLANA_RPC_URL (if not already set)
```
### 2. Test Drift Connection
```bash
npx tsx v4/test-drift-v4.ts
```
### 3. Configure n8n
```
1. Import n8n-workflow-v4.json
2. Set TRADING_BOT_API_URL
3. Set API_SECRET_KEY
4. Set TRADINGVIEW_WEBHOOK_SECRET
5. Configure Telegram credentials
6. Activate workflow
```
### 4. Configure TradingView
```
1. Create alert on 5min chart
2. Set webhook URL: https://your-n8n.com/webhook/tradingview-signal?secret=SECRET
3. Set message format (see SETUP.md)
4. Enable "Webhook URL" notification
5. Test alert
```
### 5. Start Trading!
```
Manually trigger TradingView alert
Check n8n execution logs
Verify position opened in Drift
Monitor position at drift.trade
Manually close for now (Phase 2 will auto-close)
```
## 💡 Important Notes
### Current Limitations
1. **No automatic exits** - You must manually close positions or wait for Drift's liquidation
2. **No price monitoring** - Bot doesn't track prices after entry
3. **No risk limits** - All trades are approved (risk check is placeholder)
4. **No trade history** - Trades aren't saved to database yet
### Workarounds for Phase 1
1. **Monitor positions manually** at https://drift.trade
2. **Set up Drift UI alerts** for your TP/SL levels
3. **Close positions manually** when targets hit
4. **Track trades in a spreadsheet** for now
5. **Use small position sizes** ($100-500 recommended)
## 🔐 Security Reminders
-`.env.local` is gitignored (don't commit it!)
- ✅ API keys should be random (use `openssl rand -hex 32`)
- ✅ Use a dedicated wallet for trading
- ✅ Keep private keys secure
- ✅ Start with small positions
- ✅ Monitor closely during testing
## 📊 Recommended Testing Strategy
### Week 1: Paper Testing
- Use $100 position size
- Trade 5-10 times
- Manually close all positions
- Track results in spreadsheet
### Week 2: Small Live
- Increase to $300 position size
- Let some positions hit TP/SL naturally
- Monitor slippage and execution
- Verify n8n notifications
### Week 3: Scale Up
- Gradually increase to $500-1000
- Add more symbols
- Fine-tune parameters
- Prepare for Phase 2 (auto-exits)
## 🎯 Next Development Priorities
### Phase 2 Features (in order)
1. **Pyth Price Monitor** (critical for auto-exits)
2. **Position Manager** (track active trades)
3. **Auto Exit Logic** (SL/TP execution)
4. **Database Integration** (trade history)
5. **Risk Manager** (daily limits)
6. **Enhanced Notifications** (trade updates)
Want me to build Phase 2 next?
## 📞 Support
If you encounter issues:
1. Check `v4/SETUP.md` for troubleshooting
2. Review `TRADING_BOT_V4_MANUAL.md` for full documentation
3. Test with `v4/test-drift-v4.ts`
4. Check Drift UI for account status
5. Review n8n execution logs
---
## 🎉 Congratulations!
You now have a clean, working Trading Bot v4 foundation with:
- ✅ Drift Protocol integration
- ✅ n8n automation
- ✅ TradingView webhooks
- ✅ Market order execution
- ✅ Telegram notifications
**The bot can now execute trades automatically when TradingView signals come in!**
Ready to test it? Follow the Quick Start Guide above.
Want to add auto-exits? Let me know and I'll build Phase 2!
🚀 Happy trading!