Files
trading_bot_v4/README.md
mindesbunister 9e0d9b88f9 docs: Update README with Docker deployment and web interface details
- Added Docker deployment section with architecture details
- Documented web interface (/settings) features
- Added API endpoint examples for all operations
- Updated Phase 3 status to COMPLETE
- Added settings management API documentation
- Included Docker commands and container details
- Updated file structure to reflect current layout
2025-10-24 14:36:05 +02:00

352 lines
8.2 KiB
Markdown

# 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
1. **Receives signals** from TradingView (5-minute chart)
2. **Executes trades** on Drift Protocol (Solana DEX)
3. **Monitors prices** in real-time via Pyth Network
4. **Closes positions** automatically at TP1/TP2/SL
5. **Adjusts stops** dynamically (breakeven, profit lock)
6. **Provides web UI** for configuration and monitoring
**100% autonomous. No manual intervention required!**
## Quick Start (Docker)
### 1. Deploy with Docker Compose
```bash
# 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
```bash
npm install
```
### 2. Configure Environment
```bash
# 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
```bash
# 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:**
```bash
# 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:**
```bash
# Get current settings
GET /api/settings
# 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
```
### 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.md ← Docker deployment guide
├── SETUP.md ← Setup instructions
├── TESTING.md ← Testing guide
├── docker-compose.yml ← Docker orchestration
├── Dockerfile ← Multi-stage build
├── .env ← Configuration (template)
├── package.json ← Dependencies
├── 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
├── n8n-complete-workflow.json ← Full n8n workflow
└── n8n-trader-workflow.json ← Alternative workflow
```
---
## Documentation
| Document | Purpose |
|----------|---------|
| `README.md` | This overview |
| `QUICKREF_PHASE2.md` | Quick reference card |
| `SETUP.md` | Detailed setup instructions |
| `TESTING.md` | Comprehensive testing guide |
| `PHASE_2_COMPLETE.md` | Phase 2 feature overview |
| `PHASE_2_SUMMARY.md` | Detailed Phase 2 summary |
**Root documentation:**
- `../TRADING_BOT_V4_MANUAL.md` - Complete manual
- `../QUICKSTART_V4.md` - Quick start guide
- `../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
1. **Start Small**: Use $10-50 positions first
2. **Test Thoroughly**: Run all test scripts
3. **Monitor Closely**: Watch first 10 auto-exits
4. **Verify Fills**: Check Drift UI after exits
5. **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!*