# Trading Bot v4 - Setup Instructions ## ๏ฟฝ 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) ## ๏ฟฝ๐Ÿš€ 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.*