- Extract timeframe from TradingView message format: 'SOLUSDT.P 15' - Added 'timeframe-filter' IF node after Parse Signal - Only allows trades on 15-minute chart signals - Blocks 5-minute and other timeframe signals - Regex pattern: \.P\s+(\d+) matches '.P 15' format This prevents bot from trading on wrong timeframe alerts.
Trading Bot v4 🚀
Fully Autonomous Trading Bot for TradingView → n8n → Drift Protocol (Solana)
Status
| Phase | Status | Description |
|---|---|---|
| Phase 1 | ✅ COMPLETE | Trade execution from TradingView signals |
| Phase 2 | ✅ COMPLETE | Real-time monitoring & automatic exits |
| Phase 3 | ✅ COMPLETE | Web UI, settings management, Docker deployment |
What It Does
- Receives signals from TradingView (5-minute chart)
- Executes trades on Drift Protocol (Solana DEX)
- Monitors prices in real-time via Pyth Network
- Closes positions automatically at TP1/TP2/SL
- Adjusts stops dynamically (breakeven, profit lock)
- Provides web UI for configuration and monitoring
100% autonomous. No manual intervention required!
Quick Start (Docker)
1. Deploy with Docker Compose
# Build and start
docker compose up -d
# View logs
docker compose logs -f trading-bot
# Stop
docker compose down
2. Access Web Interface
- Settings UI:
http://YOUR_HOST:3001/settings - API Endpoints:
http://YOUR_HOST:3001/api/
3. Configure Settings
Open http://YOUR_HOST:3001/settings in your browser to:
- Adjust position size and leverage
- Set stop-loss and take-profit levels
- Configure dynamic stop-loss triggers
- Set daily loss limits
- Toggle DRY_RUN mode
4. Setup n8n Workflow
Import n8n-complete-workflow.json into your n8n instance and configure TradingView alerts.
Alternative: Manual Setup
1. Install Dependencies
npm install
2. Configure Environment
# Copy and edit .env
cp .env.example .env
# Required variables:
DRIFT_WALLET_PRIVATE_KEY=[your_wallet_array]
SOLANA_RPC_URL=https://mainnet.helius-rpc.com/?api-key=YOUR_KEY
API_SECRET_KEY=your_random_secret_key
DRY_RUN=false
3. Run
# Development
npm run dev
# Production
npm run build
npm start
Features
Phase 1: Trade Execution ✅
- Drift Protocol integration
- Market order execution
- TradingView signal normalization
- n8n webhook endpoint
- Risk validation API
Phase 2: Autonomous Trading ✅
- Pyth price monitoring (WebSocket + polling)
- Position manager (tracks all trades)
- Automatic exits (TP1/TP2/SL/Emergency)
- Dynamic SL (breakeven + profit lock)
- Multi-position support
- Real-time P&L tracking
Phase 3: Production Ready ✅
- Web UI for settings management
- Docker deployment with multi-stage builds
- REST API for all operations
- Risk calculator with live preview
- Settings persistence to .env file
- PostgreSQL integration ready
Web Interface
Settings Page (/settings)
Beautiful web interface for managing all trading parameters:
Position Sizing:
- Adjust position size ($10-$10,000 USD)
- Set leverage (1x-20x)
Risk Management:
- Stop-loss percentage
- Take-profit 1 & 2 levels
- Emergency stop level
Dynamic Stop-Loss:
- Breakeven trigger
- Profit lock trigger and amount
Safety Limits:
- Max daily loss
- Max trades per hour
- Cooldown between trades
Execution:
- Slippage tolerance
- DRY_RUN toggle for testing
Live Risk Calculator:
- Shows max loss in USD
- TP1 and TP2 gains
- Risk/Reward ratio
API Endpoints
All endpoints require Authorization: Bearer YOUR_API_SECRET_KEY
Trade Execution:
# Execute a trade
POST /api/trading/execute
{
"symbol": "SOL-PERP",
"direction": "long",
"timeframe": "5",
"signalStrength": "strong"
}
# Close a position
POST /api/trading/close
{
"symbol": "SOL-PERP",
"percentToClose": 100
}
# Get active positions
GET /api/trading/positions
# Validate trade (risk check)
POST /api/trading/check-risk
{
"symbol": "SOL-PERP",
"direction": "long"
}
Settings Management:
# Get current settings
GET /api/settings
# Update settings
POST /api/settings
{
"MAX_POSITION_SIZE_USD": 100,
"LEVERAGE": 10,
"STOP_LOSS_PERCENT": -1.5,
...
}
# Restart bot container (apply settings)
POST /api/restart
Notes:
- Settings changes require container restart to take effect
- Use the web UI's "Restart Bot" button or call
/api/restart - Restart watcher must be running (see setup below)
Update settings
POST /api/settings { "MAX_POSITION_SIZE_USD": 100, "LEVERAGE": 5, "STOP_LOSS_PERCENT": -1.5, ... }
---
## Docker Deployment
### Architecture
- **Multi-stage build** for optimized image size
- **Next.js standalone** output for production
- **PostgreSQL** for trade history
- **Isolated network** (172.28.0.0/16)
- **Health monitoring** and logging
### Container Details
- **Port:** 3001 (external) → 3000 (internal)
- **Image:** Node 20 Alpine
- **Size:** ~400MB (optimized)
- **Restart:** unless-stopped
### Commands
```bash
# Build image
docker compose build trading-bot
# Start services
docker compose up -d
# View logs
docker compose logs -f trading-bot
# Restart after config changes
docker compose restart trading-bot
# Stop everything
docker compose down
Restart Watcher (Required for Web UI Restart Button)
The restart watcher monitors for restart requests from the web UI:
# Start watcher manually
cd /home/icke/traderv4
nohup ./watch-restart.sh > logs/restart-watcher.log 2>&1 &
# OR install as systemd service (recommended)
sudo cp trading-bot-restart-watcher.service /etc/systemd/system/
sudo systemctl daemon-reload
sudo systemctl enable trading-bot-restart-watcher
sudo systemctl start trading-bot-restart-watcher
# Check watcher status
sudo systemctl status trading-bot-restart-watcher
The watcher enables the "Restart Bot" button in the web UI to automatically restart the container when settings are changed.
Environment Variables
All settings are configured via .env file:
- Drift wallet credentials
- Solana RPC endpoint (Helius recommended)
- Trading parameters (size, leverage, SL, TP)
- Risk limits and safety controls
- API authentication key
Changes to .env require container restart to take effect.
File Structure
traderv4/
├── README.md ← You are here
├── docker-compose.yml ← Docker orchestration
├── Dockerfile ← Multi-stage build
├── .env ← Configuration (template)
├── package.json ← Dependencies
│
├── docs/ ← Documentation
│ ├── setup/
│ │ ├── DOCKER.md ← Docker deployment guide
│ │ ├── SETUP.md ← Setup instructions
│ │ ├── SETTINGS_SETUP.md ← Settings guide
│ │ ├── TELEGRAM_BOT_README.md ← Telegram bot guide
│ │ ├── N8N_WORKFLOW_SETUP.md ← n8n workflow setup
│ │ └── N8N_DATABASE_SETUP.md ← n8n database setup
│ ├── guides/
│ │ ├── TESTING.md ← Testing guide
│ │ ├── N8N_WORKFLOW_GUIDE.md ← n8n usage guide
│ │ └── WORKFLOW_VERIFICATION.md ← Workflow testing
│ └── history/
│ ├── PHASE_1_COMPLETE.md ← Phase 1 completion
│ ├── PHASE_2_COMPLETE.md ← Phase 2 completion
│ └── ... ← Development history
│
├── workflows/ ← n8n workflow files
│ ├── trading/ ← Main trading workflows
│ ├── analytics/ ← Analytics workflows
│ └── telegram/ ← Telegram bot workflows
│
├── scripts/ ← Utility scripts
│ ├── docker/ ← Docker helpers
│ ├── setup/ ← Setup scripts
│ └── testing/ ← Test scripts
│
├── tests/ ← Test files
│
├── app/
│ ├── layout.tsx ← Root layout
│ ├── globals.css ← Tailwind styles
│ ├── settings/
│ │ └── page.tsx ← Settings UI
│ └── api/
│ ├── settings/
│ │ └── route.ts ← Settings API
│ └── trading/
│ ├── execute/route.ts ← Execute trades
│ ├── close/route.ts ← Close positions
│ ├── positions/route.ts ← Query positions
│ └── check-risk/route.ts ← Risk validation
│
├── lib/
│ ├── drift/
│ │ ├── client.ts ← Drift SDK wrapper
│ │ └── orders.ts ← Order execution
│ ├── pyth/
│ │ └── price-monitor.ts ← Real-time prices
│ └── trading/
│ └── position-manager.ts ← Auto-exit logic
│
├── config/
│ └── trading.ts ← Market configurations
│
├── prisma/
│ └── schema.prisma ← Database schema
Documentation
| Document | Purpose |
|---|---|
README.md |
This overview |
docs/setup/SETUP.md |
Detailed setup instructions |
docs/setup/DOCKER.md |
Docker deployment guide |
docs/setup/TELEGRAM_BOT_README.md |
Telegram bot setup |
docs/guides/TESTING.md |
Comprehensive testing guide |
docs/history/PHASE_2_COMPLETE.md |
Phase 2 feature overview |
workflows/trading/ |
n8n workflow files |
../N8N_SETUP_GUIDE.md- n8n configuration
Trade Example
Entry Signal
TradingView: LONG SOL @ $140.00
Position: $1,000 (10x = $10,000)
SL: $137.90 (-1.5%)
TP1: $140.98 (+0.7%)
TP2: $142.10 (+1.5%)
TP1 Hit
✅ Price reaches $140.98
→ Auto-close 50% (+$70)
→ Move SL to $140.21 (breakeven)
→ Trade is now RISK-FREE
TP2 Hit
✅ Price reaches $142.10
→ Auto-close remaining 50% (+$150)
→ Total P&L: +$220 (+22% account)
→ Trade complete!
Safety Guidelines
- Start Small: Use $10-50 positions first
- Test Thoroughly: Run all test scripts
- Monitor Closely: Watch first 10 auto-exits
- Verify Fills: Check Drift UI after exits
- Scale Gradually: Increase size weekly
Resources
- Drift Protocol: https://drift.trade
- Drift Docs: https://docs.drift.trade
- Pyth Network: https://pyth.network
- Solana RPC: https://helius.dev
Ready to trade autonomously? Read QUICKREF_PHASE2.md to get started! 🚀
Start small, monitor closely, scale gradually!