Files
trading_bot_v3/v4/SETUP.md
mindesbunister 1345a35680 feat: Complete Phase 2 - Autonomous Trading System
- Add Pyth Network price monitoring (WebSocket + polling fallback)
- Add Position Manager with automatic exit logic (TP1/TP2/SL)
- Implement dynamic stop-loss adjustment (breakeven + profit lock)
- Add real-time P&L tracking and multi-position support
- Create comprehensive test suite (3 test scripts)
- Add 5 detailed documentation files (2500+ lines)
- Update configuration to $50 position size for safe testing
- All Phase 2 features complete and tested

Core Components:
- v4/lib/pyth/price-monitor.ts - Real-time price monitoring
- v4/lib/trading/position-manager.ts - Autonomous position management
- v4/app/api/trading/positions/route.ts - Query positions endpoint
- v4/test-*.ts - Comprehensive testing suite

Documentation:
- PHASE_2_COMPLETE_REPORT.md - Implementation summary
- v4/PHASE_2_SUMMARY.md - Detailed feature overview
- v4/TESTING.md - Testing guide
- v4/QUICKREF_PHASE2.md - Quick reference
- install-phase2.sh - Automated installation script
2025-10-23 14:40:29 +02:00

7.7 KiB
Raw Permalink Blame History

Trading Bot v4 - Setup Instructions

<EFBFBD> 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)

<EFBFBD>🚀 Quick Setup

1. Install Dependencies

Since v4 uses the existing project structure, dependencies should already be installed. If not:

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:

# 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

# 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:

# 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):
{
  "action": "{{strategy.order.action}}",
  "symbol": "{{ticker}}",
  "timeframe": "{{interval}}",
  "price": "{{close}}",
  "timestamp": "{{timenow}}",
  "signal_type": "buy",
  "strength": "strong"
}
  1. Enable Webhook URL notification
  2. Test alert

8. Test Full Flow

# 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

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

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)

# 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


Ready to trade! 🚀

Remember: Always start with small position sizes and monitor closely.