Files
trading_bot_v4/SETUP.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

316 lines
7.7 KiB
Markdown
Raw Blame History

# Trading Bot v4 - Setup Instructions
## <20> Phase Overview
- **Phase 1**: Basic trade execution (✅ COMPLETE)
- **Phase 2**: Automatic exits with real-time monitoring (✅ COMPLETE)
- **Phase 3**: Database, risk manager, notifications (Coming soon)
## <20>🚀 Quick Setup
### 1. Install Dependencies
Since v4 uses the existing project structure, dependencies should already be installed. If not:
```bash
npm install
```
Required packages (should already be in package.json):
- `@solana/web3.js`
- `@coral-xyz/anchor`
- `@drift-labs/sdk`
- `@pythnetwork/price-service-client` (for Phase 2 price monitoring)
### 2. Configure Environment Variables
Add these to your `.env.local`:
```env
# Drift Trading (v4)
DRIFT_WALLET_PRIVATE_KEY=your_base58_private_key_here
DRIFT_ENV=mainnet-beta
API_SECRET_KEY=your_random_secret_for_n8n
# Already configured (from v3)
SOLANA_RPC_URL=https://mainnet.helius-rpc.com/?api-key=YOUR_KEY
# Optional: Override default risk parameters
MAX_POSITION_SIZE_USD=1000
LEVERAGE=10
STOP_LOSS_PERCENT=-1.5
TAKE_PROFIT_1_PERCENT=0.7
TAKE_PROFIT_2_PERCENT=1.5
MAX_DAILY_DRAWDOWN=-150
MAX_TRADES_PER_HOUR=6
```
### 3. Get Your Drift Wallet Private Key
```bash
# If using Phantom wallet, export private key from Settings
# Then convert to base58 format (it's usually already in base58)
# Test your key works:
node -e "const {Keypair} = require('@solana/web3.js'); const kp = Keypair.fromSecretKey(Buffer.from('YOUR_KEY', 'base58')); console.log('Wallet:', kp.publicKey.toString())"
```
### 4. Initialize Drift Account
If you haven't already:
1. Go to https://drift.trade
2. Connect your wallet
3. Deposit USDC for trading
4. Initialize your account (one-time setup)
### 5. Test Drift Connection
Create a test script:
```bash
# Create test file
cat > test-drift-v4.ts << 'EOF'
import { initializeDriftService } from './v4/lib/drift/client'
async function test() {
console.log('🧪 Testing Drift connection...')
const drift = await initializeDriftService()
const balance = await drift.getUSDCBalance()
console.log(`💰 USDC Balance: $${balance.toFixed(2)}`)
const positions = await drift.getAllPositions()
console.log(`📊 Active positions: ${positions.length}`)
const health = await drift.getAccountHealth()
console.log(`💊 Free collateral: $${health.freeCollateral.toFixed(2)}`)
await drift.disconnect()
console.log('✅ Test complete!')
}
test().catch(console.error)
EOF
# Run test
npx tsx test-drift-v4.ts
```
### 6. Configure n8n Webhook
1. **Import workflow** from `n8n-workflow-v4.json`
2. **Set environment variables** in n8n:
- `TRADING_BOT_API_URL=https://your-bot-domain.com`
- `API_SECRET_KEY=your_secret_key`
- `TRADINGVIEW_WEBHOOK_SECRET=another_secret`
3. **Activate workflow**
4. **Copy webhook URL**
### 7. Configure TradingView Alert
1. Create alert on your 5-minute chart
2. **Webhook URL**: `https://your-n8n.com/webhook/tradingview-signal?secret=YOUR_SECRET`
3. **Message** (JSON):
```json
{
"action": "{{strategy.order.action}}",
"symbol": "{{ticker}}",
"timeframe": "{{interval}}",
"price": "{{close}}",
"timestamp": "{{timenow}}",
"signal_type": "buy",
"strength": "strong"
}
```
4. Enable **Webhook URL** notification
5. Test alert
### 8. Test Full Flow
```bash
# 1. Start your Next.js server
npm run dev
# 2. Trigger TradingView alert manually
# 3. Check n8n execution logs
# 4. Check your bot API logs
# 5. Check Drift account for position
```
## 🔧 API Endpoints
### Execute Trade
```bash
POST http://localhost:3000/api/trading/execute
Authorization: Bearer YOUR_API_SECRET_KEY
Content-Type: application/json
{
"symbol": "SOLUSDT",
"direction": "long",
"timeframe": "5",
"signalStrength": "strong"
}
```
### Check Risk
```bash
POST http://localhost:3000/api/trading/check-risk
Authorization: Bearer YOUR_API_SECRET_KEY
Content-Type: application/json
{
"symbol": "SOL-PERP",
"direction": "long"
}
```
## 🧪 Testing
### Test with curl (without n8n)
```bash
# 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"}'
# Test trade execution (CAREFUL - 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"
}'
```
### Test with Postman
1. Import collection from docs
2. Set environment variables
3. Run tests
## 📁 v4 File Structure
```
v4/
├── config/
│ └── trading.ts # Trading configuration
├── lib/
│ ├── drift/
│ │ ├── client.ts # Drift SDK client ✅
│ │ └── orders.ts # Order execution ✅
│ ├── pyth/
│ │ └── price-monitor.ts # Real-time prices ✅ (Phase 2)
│ └── trading/
│ └── position-manager.ts # Auto-exit logic ✅ (Phase 2)
└── app/
└── api/
└── trading/
├── execute/
│ └── route.ts # Execute trade endpoint ✅
├── check-risk/
│ └── route.ts # Risk check endpoint ✅
└── positions/
└── route.ts # Query positions ✅ (Phase 2)
```
## ✅ Phase 1 Complete
- ✅ Drift Protocol integration
- ✅ Market order execution (open/close)
- ✅ n8n webhook endpoint (execute trade)
- ✅ Basic risk check endpoint
- ✅ Trading configuration
- ✅ TradingView symbol normalization
## ✅ Phase 2 Complete
- ✅ Pyth price monitoring (WebSocket + polling)
- ✅ Position manager (track active trades)
- ✅ Auto-exit logic (TP1/TP2/SL/Emergency)
- ✅ Dynamic SL adjustment (breakeven, profit lock)
- ✅ Multi-position support
- ✅ Positions query endpoint
## 🚧 Coming Next (Phase 3)
- ⏳ Database integration (PostgreSQL/Prisma)
- ⏳ Trade history persistence
- ⏳ Risk manager (daily limits, cooldowns, frequency checks)
- ⏳ Enhanced notifications (Telegram/Discord/Email)
- ⏳ Performance analytics
- ⏳ Web dashboard for monitoring
## 🔐 Security
**IMPORTANT:**
- Never commit `.env.local` to git
- Keep your private key secure
- Use a dedicated trading wallet
- Start with small position sizes
- Test on devnet first if possible
## 💡 Tips
1. **Start small**: Use $100 position size first
2. **Test signals**: Manually trigger alerts to test flow
3. **Monitor closely**: Watch first 5-10 trades carefully
4. **Check Drift UI**: Verify positions at https://drift.trade
5. **Backup strategy**: Have emergency close ready
## 🆘 Troubleshooting
### "Drift service not initialized"
- Make sure DRIFT_WALLET_PRIVATE_KEY is set
- Check wallet has SOL for gas fees
- Verify Drift account is initialized
### "Insufficient collateral"
- Deposit more USDC to Drift account
- Check account health at drift.trade
- Reduce position size
### "Webhook not working"
- Verify n8n workflow is active
- Check API_SECRET_KEY matches
- Test with curl first
### "Order execution failed"
- Check market is active on Drift
- Verify minimum order size
- Check RPC connection
- Review Drift UI for errors
## 📞 Next Steps
1. Test Drift connection
2. Deploy to production
3. Configure n8n webhook
4. Set up TradingView alerts
5. Start with paper trading (small size)
6. Scale up after 10+ successful trades
## 🎓 Resources
- Drift Protocol: https://drift.trade
- Drift Docs: https://docs.drift.trade
- n8n Workflow: See `TRADING_BOT_V4_MANUAL.md`
- Full Manual: See `QUICKSTART_V4.md`
---
**Ready to trade! 🚀**
*Remember: Always start with small position sizes and monitor closely.*