Organization: - Created docs/ with setup/, guides/, history/ subdirectories - Created workflows/ with trading/, analytics/, telegram/, archive/ subdirectories - Created scripts/ with docker/, setup/, testing/ subdirectories - Created tests/ for TypeScript test files - Created archive/ for unused reference files Moved files: - 17 documentation files → docs/ - 16 workflow JSON files → workflows/ - 10 shell scripts → scripts/ - 4 test files → tests/ - 5 unused files → archive/ Updated: - README.md with new file structure and documentation paths Deleted: - data/ (empty directory) - screenshots/ (empty directory) Critical files remain in root: - telegram_command_bot.py (active bot - used by Dockerfile) - watch-restart.sh (systemd service dependency) - All Dockerfiles and docker-compose files - All environment files Validation: Containers running (trading-bot-v4, telegram-trade-bot, postgres) API responding (positions endpoint tested) Telegram bot functional (/status command tested) All critical files present in root No code changes - purely organizational. System continues running without interruption. Recovery: git revert HEAD or git reset --hard cleanup-before
7.7 KiB
7.7 KiB
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:
- Go to https://drift.trade
- Connect your wallet
- Deposit USDC for trading
- 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
- Import workflow from
n8n-workflow-v4.json - Set environment variables in n8n:
TRADING_BOT_API_URL=https://your-bot-domain.comAPI_SECRET_KEY=your_secret_keyTRADINGVIEW_WEBHOOK_SECRET=another_secret
- Activate workflow
- Copy webhook URL
7. Configure TradingView Alert
- Create alert on your 5-minute chart
- Webhook URL:
https://your-n8n.com/webhook/tradingview-signal?secret=YOUR_SECRET - Message (JSON):
{
"action": "{{strategy.order.action}}",
"symbol": "{{ticker}}",
"timeframe": "{{interval}}",
"price": "{{close}}",
"timestamp": "{{timenow}}",
"signal_type": "buy",
"strength": "strong"
}
- Enable Webhook URL notification
- 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
- Import collection from docs
- Set environment variables
- 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.localto git - Keep your private key secure
- Use a dedicated trading wallet
- Start with small position sizes
- Test on devnet first if possible
💡 Tips
- Start small: Use $100 position size first
- Test signals: Manually trigger alerts to test flow
- Monitor closely: Watch first 5-10 trades carefully
- Check Drift UI: Verify positions at https://drift.trade
- 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
- Test Drift connection
- Deploy to production
- Configure n8n webhook
- Set up TradingView alerts
- Start with paper trading (small size)
- Scale up after 10+ successful trades
🎓 Resources
- Drift Protocol: https://drift.trade
- Drift Docs: https://docs.drift.trade
- n8n Workflow: See
TRADING_BOT_V4_MANUAL.md - Full Manual: See
QUICKSTART_V4.md
Ready to trade! 🚀
Remember: Always start with small position sizes and monitor closely.