Files
trading_bot_v4/N8N_WORKFLOW_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

214 lines
5.1 KiB
Markdown

# n8n Trading Bot v4 Workflow - Setup Instructions
## Step 1: Create API Credential in n8n
1. Go to n8n → **Credentials****New Credential**
2. Search for **"Header Auth"**
3. Configure:
- **Name**: `Trading Bot API Key`
- **Name** (field): `Authorization`
- **Value**: `Bearer 2a344f0149442c857fb56c038c0c7d1b113883b830bec792c76f1e0efa15d6bb`
4. Click **Save**
## Step 2: Update Your Telegram Credential
Make sure your Telegram Bot credential exists in n8n:
- **Credential Name**: `Telegram Bot`
- **Chat ID**: `579304651` (or change in workflow to your ID)
## Step 3: Import the Workflow
1. Download: `/home/icke/traderv4/n8n-complete-workflow.json`
2. Go to n8n → **Workflows****Import from File**
3. Select the downloaded JSON file
4. Click **Import**
## Step 4: Configure Credentials
After importing, update the credential references:
### For "Check Risk" and "Execute Trade" nodes:
- Click on the node
- Under **Authentication****Credential for Header Auth**
- Select: `Trading Bot API Key` (the one you created in Step 1)
### For all Telegram nodes:
- Click on each Telegram node
- Under **Credential for Telegram API**
- Select your Telegram Bot credential
## Step 5: Test the Webhook
1. **Activate** the workflow
2. Get the webhook URL (shown in the Webhook node)
3. Test with curl:
```bash
curl -X POST "https://your-n8n-instance.com/webhook/tradingview-bot-v4" \\
-H "Content-Type: application/json" \\
-d '{"body": "Buy SOL | Entry: 140.50"}'
```
## Workflow Flow
```
TradingView Alert
[Webhook] Receives signal
[Parse Signal] Extracts data (symbol, direction, timeframe)
[Check Risk] Validates trade (API call)
[Risk Passed?] Decision
↓ ↓
YES NO
↓ ↓
[Execute Trade] [Risk Blocked Message]
[Trade Success?] Decision
↓ ↓
SUCCESS FAILED
↓ ↓
[Success Msg] [Error Msg]
```
## Expected Telegram Notifications
### Success Message:
```
🟢 TRADE OPENED SUCCESSFULLY
Buy SOL | Entry: 140.50
📊 Symbol: SOL-PERP
📈 Direction: LONG
💰 Entry: $140.5000
💵 Size: $500.00
⚡ Leverage: 10x
🎯 Take Profit:
TP1: $141.48 (+0.7%)
TP2: $142.63 (+1.5%)
🛑 Stop Loss:
SL: $138.39 (-1.5%)
📊 Slippage: 0.023%
⏰ 14:32
✅ Position monitored automatically
🤖 Auto-exit at TP/SL levels
```
### Risk Blocked Message:
```
⚠️ TRADE BLOCKED - RISK LIMITS
Buy SOL | Entry: 140.50
📊 Symbol: SOL-PERP
📈 Direction: LONG
🛑 Reason: Daily drawdown limit reached
📝 Details: Check risk management settings
⏰ 14:32
✅ Trade will be allowed when conditions improve
```
### Error Message:
```
🔴 TRADE EXECUTION FAILED
Buy SOL | Entry: 140.50
📊 Symbol: SOL-PERP
📈 Direction: LONG
❌ Error: Drift wallet not configured
⏰ 14:32
⚠️ Check bot logs:
docker logs trading-bot-v4 --tail=50
```
## TradingView Alert Format
Your TradingView alerts should send data in this format:
**Simple format (recommended):**
```
Buy SOL | Entry: 140.50
```
or
```
Sell BTC | Entry: 67890.00
```
The workflow will automatically detect:
- **Symbol**: SOL, BTC, ETH (defaults to SOL if not found)
- **Direction**: Buy/Long → long, Sell/Short → short
- **Timeframe**: Fixed at 5 minutes
## API Endpoints Used
1. **Risk Check**: `http://10.0.0.48:3001/api/trading/check-risk`
- Method: POST
- Body: `{"symbol": "SOL-PERP", "direction": "long"}`
2. **Execute Trade**: `http://10.0.0.48:3001/api/trading/execute`
- Method: POST
- Body: `{"symbol": "SOL-PERP", "direction": "long", "timeframe": "5", "signalStrength": "strong"}`
## Troubleshooting
### "Connection refused" error:
- Check if trading bot is running: `docker ps | grep trading-bot`
- Verify the bot is accessible: `curl http://10.0.0.48:3001/api/trading/positions`
### "Unauthorized" error:
- Check API key credential is set correctly
- Verify the Bearer token format: `Bearer <your-api-key>`
### Telegram not sending:
- Verify your Telegram bot token is valid
- Check chat ID is correct (must be a number)
- Test Telegram node independently
### No response from webhook:
- Make sure workflow is **activated**
- Check webhook path matches your TradingView alert
- Verify n8n is accessible from TradingView
## Quick Commands
```bash
# Check bot status
docker ps | grep trading-bot
# View bot logs
docker logs trading-bot-v4 --tail=50 -f
# Test API directly
curl -X POST http://10.0.0.48:3001/api/trading/check-risk \\
-H "Authorization: Bearer 2a344f0149442c857fb56c038c0c7d1b113883b830bec792c76f1e0efa15d6bb" \\
-H "Content-Type: application/json" \\
-d '{"symbol":"SOL-PERP","direction":"long"}'
# Check active positions
curl http://localhost:3001/api/trading/positions \\
-H "Authorization: Bearer 2a344f0149442c857fb56c038c0c7d1b113883b830bec792c76f1e0efa15d6bb"
```
## Next Steps
1. ✅ Import workflow
2. ✅ Configure credentials
3. ✅ Activate workflow
4. ⚠️ Configure Drift wallet in trading bot (see main README.md)
5. 🚀 Set up TradingView alerts
6. 💰 Start trading!