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

View File

@@ -0,0 +1,297 @@
{
"name": "Trader - Trading Bot v4 Integration",
"nodes": [
{
"parameters": {
"httpMethod": "POST",
"path": "3371ad7c-0866-4161-90a4-f251de4aceb8",
"options": {}
},
"id": "683db7ad-2df6-44c7-afaa-d2f40705f268",
"name": "Webhook",
"type": "n8n-nodes-base.webhook",
"typeVersion": 1,
"position": [500, 460],
"webhookId": "3371ad7c-0866-4161-90a4-f251de4aceb8"
},
{
"parameters": {
"fields": {
"values": [
{
"name": "signal",
"stringValue": "={{ $json.body.split('|')[0].trim() }}"
},
{
"name": "symbol",
"stringValue": "={{ $json.body.includes('SOL') ? 'SOL-PERP' : ($json.body.includes('BTC') ? 'BTC-PERP' : ($json.body.includes('ETH') ? 'ETH-PERP' : 'SOL-PERP')) }}"
},
{
"name": "direction",
"stringValue": "={{ $json.signal.toLowerCase().includes('buy') || $json.signal.toLowerCase().includes('long') ? 'long' : 'short' }}"
},
{
"name": "timeframe",
"stringValue": "5"
}
]
},
"options": {}
},
"id": "1844fbcb-282b-4b01-9744-b21adda235e9",
"name": "Edit Fields",
"type": "n8n-nodes-base.set",
"typeVersion": 3.2,
"position": [700, 460]
},
{
"parameters": {
"url": "http://trading-bot-v4:3000/api/trading/check-risk",
"authentication": "genericCredentialType",
"genericAuthType": "httpHeaderAuth",
"sendHeaders": true,
"headerParameters": {
"parameters": [
{
"name": "Authorization",
"value": "=Bearer {{ $env.API_SECRET_KEY }}"
},
{
"name": "Content-Type",
"value": "application/json"
}
]
},
"sendBody": true,
"specifyBody": "json",
"jsonBody": "={\n \"symbol\": \"{{ $json.symbol }}\",\n \"direction\": \"{{ $json.direction }}\"\n}",
"options": {
"timeout": 10000
}
},
"id": "check-risk-node",
"name": "Check Risk Limits",
"type": "n8n-nodes-base.httpRequest",
"typeVersion": 4.1,
"position": [900, 460]
},
{
"parameters": {
"conditions": {
"boolean": [
{
"value1": "={{ $json.allowed }}",
"value2": true
}
]
}
},
"id": "risk-check-condition",
"name": "Risk Check Passed?",
"type": "n8n-nodes-base.if",
"typeVersion": 1,
"position": [1100, 460]
},
{
"parameters": {
"url": "http://trading-bot-v4:3000/api/trading/execute",
"authentication": "genericCredentialType",
"genericAuthType": "httpHeaderAuth",
"sendHeaders": true,
"headerParameters": {
"parameters": [
{
"name": "Authorization",
"value": "=Bearer {{ $env.API_SECRET_KEY }}"
},
{
"name": "Content-Type",
"value": "application/json"
}
]
},
"sendBody": true,
"specifyBody": "json",
"jsonBody": "={\n \"symbol\": \"{{ $('Edit Fields').item.json.symbol }}\",\n \"direction\": \"{{ $('Edit Fields').item.json.direction }}\",\n \"timeframe\": \"{{ $('Edit Fields').item.json.timeframe }}\",\n \"signalStrength\": \"strong\"\n}",
"options": {
"timeout": 30000
}
},
"id": "execute-trade-node",
"name": "Execute Trade on Bot",
"type": "n8n-nodes-base.httpRequest",
"typeVersion": 4.1,
"position": [1300, 360]
},
{
"parameters": {
"conditions": {
"boolean": [
{
"value1": "={{ $json.success }}",
"value2": true
}
]
}
},
"id": "trade-success-condition",
"name": "Trade Successful?",
"type": "n8n-nodes-base.if",
"typeVersion": 1,
"position": [1500, 360]
},
{
"parameters": {
"chatId": "579304651",
"text": "=🟢 TRADE EXECUTED SUCCESSFULLY\n\n{{ $json.signal }}\n\n📊 Symbol: {{ $('Edit Fields').item.json.symbol }}\n📈 Direction: {{ $('Edit Fields').item.json.direction.toUpperCase() }}\n💰 Entry: ${{ $json.entryPrice ? $json.entryPrice.toFixed(4) : 'N/A' }}\n💵 Size: ${{ $json.positionSize ? $json.positionSize.toFixed(2) : 'N/A' }}\n⚡ Leverage: {{ $json.leverage || '10' }}x\n\n🎯 Targets:\n SL: ${{ $json.stopLoss ? $json.stopLoss.toFixed(2) : 'N/A' }} ({{ $json.stopLossPercent || '-1.5' }}%)\n TP1: ${{ $json.takeProfit1 ? $json.takeProfit1.toFixed(2) : 'N/A' }} ({{ $json.tp1Percent || '+0.7' }}%)\n TP2: ${{ $json.takeProfit2 ? $json.takeProfit2.toFixed(2) : 'N/A' }} ({{ $json.tp2Percent || '+1.5' }}%)\n\n⏰ {{ new Date().toLocaleTimeString() }}\n\n✅ Position monitored automatically",
"additionalFields": {
"appendAttribution": false
}
},
"id": "telegram-success",
"name": "Telegram - Success",
"type": "n8n-nodes-base.telegram",
"typeVersion": 1.1,
"position": [1700, 260],
"credentials": {
"telegramApi": {
"id": "Csk5cg4HtaSqP5jJ",
"name": "Telegram account"
}
}
},
{
"parameters": {
"chatId": "579304651",
"text": "=🔴 TRADE EXECUTION FAILED\n\n{{ $('Edit Fields').item.json.signal }}\n\n📊 Symbol: {{ $('Edit Fields').item.json.symbol }}\n📈 Direction: {{ $('Edit Fields').item.json.direction.toUpperCase() }}\n\n❌ Error: {{ $json.error || $json.message || 'Unknown error' }}\n\n⏰ {{ new Date().toLocaleTimeString() }}\n\n⚠ Check bot logs for details",
"additionalFields": {
"appendAttribution": false
}
},
"id": "telegram-error",
"name": "Telegram - Error",
"type": "n8n-nodes-base.telegram",
"typeVersion": 1.1,
"position": [1700, 460],
"credentials": {
"telegramApi": {
"id": "Csk5cg4HtaSqP5jJ",
"name": "Telegram account"
}
}
},
{
"parameters": {
"chatId": "579304651",
"text": "=⚠️ TRADE BLOCKED - RISK LIMITS\n\n{{ $('Edit Fields').item.json.signal }}\n\n📊 Symbol: {{ $('Edit Fields').item.json.symbol }}\n📈 Direction: {{ $('Edit Fields').item.json.direction.toUpperCase() }}\n\n🛑 Reason: {{ $('Check Risk Limits').item.json.reason || 'Risk limits exceeded' }}\n\n⏰ {{ new Date().toLocaleTimeString() }}\n\n✅ Trade will be allowed when conditions improve",
"additionalFields": {
"appendAttribution": false
}
},
"id": "telegram-risk-blocked",
"name": "Telegram - Risk Blocked",
"type": "n8n-nodes-base.telegram",
"typeVersion": 1.1,
"position": [1300, 560],
"credentials": {
"telegramApi": {
"id": "Csk5cg4HtaSqP5jJ",
"name": "Telegram account"
}
}
}
],
"pinData": {},
"connections": {
"Webhook": {
"main": [
[
{
"node": "Edit Fields",
"type": "main",
"index": 0
}
]
]
},
"Edit Fields": {
"main": [
[
{
"node": "Check Risk Limits",
"type": "main",
"index": 0
}
]
]
},
"Check Risk Limits": {
"main": [
[
{
"node": "Risk Check Passed?",
"type": "main",
"index": 0
}
]
]
},
"Risk Check Passed?": {
"main": [
[
{
"node": "Execute Trade on Bot",
"type": "main",
"index": 0
}
],
[
{
"node": "Telegram - Risk Blocked",
"type": "main",
"index": 0
}
]
]
},
"Execute Trade on Bot": {
"main": [
[
{
"node": "Trade Successful?",
"type": "main",
"index": 0
}
]
]
},
"Trade Successful?": {
"main": [
[
{
"node": "Telegram - Success",
"type": "main",
"index": 0
}
],
[
{
"node": "Telegram - Error",
"type": "main",
"index": 0
}
]
]
}
},
"active": true,
"settings": {
"executionOrder": "v1"
},
"versionId": "updated-with-trading-bot-v4",
"id": "Bg1iplLiwLdVexG1",
"meta": {
"instanceId": "e766d4f0b5def8ee8cb8561cd9d2b9ba7733e1907990b6987bca40175f82c379"
},
"tags": []
}