# AI-Powered Trading Bot Dashboard This is a Next.js 15 App Router application with TypeScript, Tailwind CSS, and API routes. It's a production-ready trading bot with AI analysis, automated screenshot capture, and real-time trading execution via Drift Protocol and Jupiter DEX. **Prerequisites:** - Docker and Docker Compose v2 (uses `docker compose` command syntax) - All development must be done inside Docker containers for browser automation compatibility ## Core Architecture ### Dual-Session Screenshot Automation - **AI Layout**: `Z1TzpUrf` - RSI (top), EMAs, MACD (bottom) - **DIY Layout**: `vWVvjLhP` - Stochastic RSI (top), VWAP, OBV (bottom) - Parallel browser sessions for multi-layout capture in `lib/enhanced-screenshot.ts` - TradingView automation with session persistence in `lib/tradingview-automation.ts` - Session data stored in `.tradingview-session/` volume mount to avoid captchas ### AI-Driven Dynamic Leverage System ✅ **Complete AI leverage calculator with intelligent position sizing:** - `lib/ai-leverage-calculator.ts` - Core AI leverage calculation engine with risk management - Account-based strategies: <$1k uses 100% balance (aggressive), >$1k uses 50% balance (conservative) - Safety mechanisms: 10% buffer between liquidation price and stop loss - Platform integration: Drift Protocol with maximum 20x leverage constraints - **Integration**: Enhanced `lib/automation-service-simple.ts` uses AI-calculated leverage for all positions ### AI-Driven DCA (Dollar Cost Averaging) System ✅ **Revolutionary position scaling that maximizes profits while managing risk:** - `lib/ai-dca-manager.ts` - AI-powered DCA analysis engine with reversal detection - **Multi-factor Analysis**: Price movements, 24h trends, RSI levels, support/resistance - **Smart Scaling**: Adds to positions when AI detects reversal potential (50%+ confidence threshold) - **Risk Management**: Respects leverage limits, adjusts stop loss/take profit for new average price - **Account Integration**: Uses available balance strategically (up to 50% for DCA operations) - **Real Example**: SOL position at $185.98 entry, $183.87 current → AI recommends 1.08 SOL DCA for 5.2:1 R/R improvement **DCA Decision Factors:** - Price movement against position (1-10% optimal range) - 24h market sentiment alignment with DCA direction - Technical indicators (RSI oversold/overbought zones) - Proximity to support/resistance levels - Available balance and current leverage headroom - Liquidation distance and safety buffers **Integration Points:** - `lib/automation-service-simple.ts` - Automated DCA monitoring in main trading cycle - `prisma/schema.prisma` - DCARecord model for tracking all scaling operations - Database tracking of DCA count, total amount, and performance metrics ### Trading Integration - **Drift Protocol**: Perpetual futures trading via `@drift-labs/sdk` - **Jupiter DEX**: Spot trading on Solana - Position management and P&L tracking in `lib/drift-trading-final.ts` - Real-time account balance and collateral monitoring ## Critical Development Patterns ### Automation System Development Wisdom **Key lessons from building and debugging the automation system:** #### AI Risk Management vs Manual Controls - **NEVER mix manual TP/SL inputs with AI automation** - causes conflicts and unpredictable behavior - When implementing AI-driven automation, remove all manual percentage inputs from the UI - AI should calculate dynamic stop losses and take profits based on market conditions, not user-defined percentages - Always validate that UI selections (timeframes, strategies) are properly passed to backend services #### Balance and P&L Calculation Critical Rules - **ALWAYS use Drift SDK's built-in calculation methods** instead of manual calculations - Use `driftClient.getUser().getTotalCollateral()` for accurate collateral values - Use `driftClient.getUser().getUnrealizedPNL()` for accurate P&L calculations - **NEVER use hardcoded prices** (like $195 for SOL) - always get current market data - **NEVER use empirical precision factors** - use official SDK precision handling - Test balance calculations against actual Drift interface values for validation - Unrealized P&L should match position-level P&L calculations #### Timeframe Handling Best Practices - **Always use minute values first** in timeframe mapping to avoid TradingView confusion - Example: `'4h': ['240', '240m', '4h', '4H']` - 240 minutes FIRST, then alternatives - Validate that UI timeframe selections reach the automation service correctly - Log timeframe values at every step to catch hardcoded overrides #### System Integration Debugging - **Always validate data flow** from UI → API → Service → Trading execution - Check for hardcoded values that override user selections (especially timeframes) - Verify correct protocol usage (Drift vs Jupiter) in trading execution - Test cleanup systems regularly - memory leaks kill automation reliability - Implement comprehensive logging for multi-step processes #### Analysis Timer Implementation - Store `nextScheduled` timestamps in database for persistence across restarts - Calculate countdown dynamically based on current time vs scheduled time - Update timer fields in automation status responses for real-time UI updates - Format countdown as "XhYm" or "Xm Ys" for better user experience ### Docker Container Development (Required) **All development happens inside Docker containers** using Docker Compose v2. Browser automation requires specific system dependencies that are only available in the containerized environment: **IMPORTANT: Use Docker Compose v2 syntax** - All commands use `docker compose` (with space) instead of `docker-compose` (with hyphen). ```bash # Development environment - Docker Compose v2 dev setup npm run docker:dev # Port 9001:3000, hot reload, debug mode # Direct v2 command: docker compose -f docker-compose.dev.yml up --build # Production environment npm run docker:up # Port 9000:3000, optimized build # Direct v2 command: docker compose -f docker-compose.prod.yml up --build # Debugging commands npm run docker:logs # View container logs # Direct v2 command: docker compose -f docker-compose.dev.yml logs -f npm run docker:exec # Shell access for debugging inside container # Direct v2 command: docker compose -f docker-compose.dev.yml exec app bash ``` **Port Configuration:** - **Development**: External port `9001` → Internal port `3000` (http://localhost:9001) - **Production**: External port `9000` → Internal port `3000` (http://localhost:9000) ### Docker Volume Mount Troubleshooting & Direct Container Development **Common Issue**: File edits not reflecting in container due to volume mount sync issues. **Container-First Development Workflow:** For immediate results and faster iteration, edit files directly inside the running container first, then rebuild for persistence: ```bash # 1. Access running container for immediate edits docker compose -f docker-compose.dev.yml exec app bash # 2. Edit files directly in container (immediate effect) # Use nano, vi, or echo for quick changes nano /app/lib/enhanced-screenshot.ts echo "console.log('Debug: immediate test');" >> /app/debug.js # 3. Test changes immediately (no rebuild needed) # Changes take effect instantly for hot reload # 4. Once everything works, copy changes back to host docker cp container_name:/app/modified-file.js ./modified-file.js # 5. Commit successful changes to git BEFORE rebuilding git add . git commit -m "feat: implement working solution for [specific feature]" git push origin development # 6. Rebuild container for persistence docker compose -f docker-compose.dev.yml down docker compose -f docker-compose.dev.yml up --build -d # 7. Final validation and commit completion # Test that changes persist after rebuild curl http://localhost:9001 # Verify functionality git add . && git commit -m "chore: confirm container persistence" && git push ``` **Alternative Solutions:** 1. **Fresh Implementation Approach**: When modifying existing files fails, create new files (e.g., `page-v2.js`) instead of editing corrupted files 2. **Container Restart**: `docker compose -f docker-compose.dev.yml restart app` 3. **Full Rebuild**: `docker compose -f docker-compose.dev.yml down && docker compose -f docker-compose.dev.yml up --build` 4. **Manual Copy**: Use `docker cp` to copy files directly into container for immediate testing 5. **Avoid sed/awk**: Direct text manipulation commands often corrupt JSX syntax - prefer file replacement **Volume Mount Verification:** ```bash # Test volume mount sync echo "test-$(date)" > test-volume-mount.txt docker compose -f docker-compose.dev.yml exec app cat test-volume-mount.txt ``` **Container Development Best Practices:** - **Speed**: Direct container edits = immediate testing - **Persistence**: Always rebuild container after successful tests - **Backup**: Use `docker cp` to extract working changes before rebuild - **Debugging**: Use container shell for real-time log inspection and debugging ### Multi-Timeframe Feature Copy Pattern When copying multi-timeframe functionality between pages: **Step 1: Identify Source Implementation** ```bash # Search for existing timeframe patterns grep -r "timeframes.*=.*\[" app/ --include="*.js" --include="*.jsx" grep -r "selectedTimeframes" app/ --include="*.js" --include="*.jsx" ``` **Step 2: Copy Core State Management** ```javascript // Always include these state hooks const [selectedTimeframes, setSelectedTimeframes] = useState(['1h', '4h']); const [balance, setBalance] = useState({ balance: 0, collateral: 0 }); // Essential toggle function const toggleTimeframe = (tf) => { setSelectedTimeframes(prev => prev.includes(tf) ? prev.filter(t => t !== tf) : [...prev, tf] ); }; ``` **Step 3: Copy UI Components** - Timeframe checkbox grid - Preset buttons (Scalping, Day Trading, Swing Trading) - Auto-sizing position calculator - Formatted balance display **Step 4: Avoid Docker Issues** - Create new file instead of editing existing if volume mount issues persist - Use fresh filename like `page-v2.js` or `automation-v2/page.js` - Test in container before committing ### API Route Structure All core functionality exposed via Next.js API routes: ```typescript // Enhanced screenshot with progress tracking and robust cleanup POST /api/enhanced-screenshot { symbol: "SOLUSD", timeframe: "240", layouts: ["ai", "diy"], analyze: true } // Returns: { screenshots, analysis, sessionId } // Note: Includes automatic Chromium process cleanup via finally blocks // Drift trading endpoints GET /api/balance # Account balance/collateral POST /api/trading # Execute trades GET /api/status # Trading status ``` **API Development Tips:** - All browser automation APIs include guaranteed cleanup via finally blocks - Use session tracking for long-running operations - Test API endpoints directly with curl before UI integration - Monitor Chromium processes during API testing: `pgrep -f chrome | wc -l` ### Progress Tracking System Real-time operation tracking for long-running tasks: - `lib/progress-tracker.ts` manages EventEmitter-based progress - SessionId-based tracking for multi-step operations - Steps: init → auth → navigation → loading → capture → analysis - Stream endpoint: `/api/progress/[sessionId]/stream` ### Browser Process Management & Cleanup System **Critical Issue**: Chromium processes accumulate during automated trading, consuming system resources over time. **Robust Cleanup Implementation:** The trading bot includes a comprehensive cleanup system to prevent Chromium process accumulation: **Core Cleanup Components:** 1. **Enhanced Screenshot Service** (`lib/enhanced-screenshot-robust.ts`) - Guaranteed cleanup via `finally` blocks in all browser operations - Active session tracking to prevent orphaned browsers - Session cleanup tasks array for systematic teardown 2. **Automated Cleanup Service** (`lib/automated-cleanup-service.ts`) - Background monitoring service for orphaned processes - Multiple kill strategies: graceful → force → system cleanup - Periodic cleanup of temporary files and browser data 3. **Aggressive Cleanup Utilities** (`lib/aggressive-cleanup.ts`) - System-level process killing for stubborn Chromium processes - Port cleanup and temporary directory management - Emergency cleanup functions for resource recovery **Implementation Patterns:** ```typescript // Always use finally blocks for guaranteed cleanup try { const browser = await puppeteer.launch(options); // ... browser operations } finally { // Guaranteed cleanup regardless of success/failure await ensureBrowserCleanup(browser, sessionId); await cleanupSessionTasks(sessionId); } // Background monitoring for long-running operations const cleanupService = new AutomatedCleanupService(); cleanupService.startPeriodicCleanup(); // Every 10 minutes ``` **Cleanup Testing:** ```bash # Test cleanup system functionality node test-cleanup-system.js # Monitor Chromium processes during automation watch 'pgrep -f "chrome|chromium" | wc -l' # Manual cleanup if needed node -e "require('./lib/aggressive-cleanup.ts').performAggressiveCleanup()" ``` **Prevention Strategies:** - Use session tracking for all browser instances - Implement timeout protection for long-running operations - Monitor resource usage during extended automation cycles - Restart containers periodically for fresh environment Critical timeframe handling to avoid TradingView confusion: ```typescript // ALWAYS use minute values first, then alternatives '4h': ['240', '240m', '4h', '4H'] // 240 minutes FIRST '1h': ['60', '60m', '1h', '1H'] // 60 minutes FIRST '15m': ['15', '15m'] ``` Layout URL mappings for direct navigation: ```typescript const LAYOUT_URLS = { 'ai': 'Z1TzpUrf', // RSI + EMAs + MACD 'diy': 'vWVvjLhP' // Stochastic RSI + VWAP + OBV } ``` ### Component Architecture - `app/layout.js` - Root layout with gradient styling and navigation - `components/Navigation.tsx` - Multi-page navigation system - `components/AIAnalysisPanel.tsx` - Multi-timeframe analysis interface - `components/Dashboard.tsx` - Main trading dashboard with real Drift positions - `components/AdvancedTradingPanel.tsx` - Drift Protocol trading interface ### Cleanup System Architecture **Critical Production Issue**: Chromium processes accumulate during automated trading, leading to resource exhaustion after several hours of operation. **Solution Components:** 1. **Enhanced Screenshot Service** (`lib/enhanced-screenshot-robust.ts`) - Replaces original screenshot service with guaranteed cleanup - Uses `finally` blocks to ensure browser cleanup regardless of success/failure - Active session tracking with cleanup task arrays - Force-kill functionality for stubborn processes 2. **Automated Cleanup Service** (`lib/automated-cleanup-service.ts`) - Background monitoring service that runs every 10 minutes - Multiple cleanup strategies: graceful → force → system-level cleanup - Temporary file cleanup and browser data directory management - Orphaned process detection and elimination 3. **Aggressive Cleanup Utilities** (`lib/aggressive-cleanup.ts`) - Emergency cleanup functions for critical resource recovery - System-level process management with multiple kill strategies - Port cleanup and zombie process elimination - Used by both automated service and manual intervention **Integration Pattern:** ```typescript // In API routes - always use finally blocks app/api/enhanced-screenshot/route.js: try { const result = await enhancedScreenshot.captureAndAnalyze(...); return NextResponse.json(result); } finally { // Guaranteed cleanup execution await enhancedScreenshot.cleanup(); } // Background monitoring lib/automated-cleanup-service.ts: setInterval(async () => { await this.performCleanup(); }, 10 * 60 * 1000); // Every 10 minutes ``` **Testing Cleanup System:** ```bash # Monitor process count during operation watch 'pgrep -f "chrome|chromium" | wc -l' # Test cleanup functionality node test-cleanup-system.js # Manual cleanup if needed docker compose exec app node -e "require('./lib/aggressive-cleanup.ts').forceKillAllChromium()" ``` ### Page Structure & Multi-Timeframe Implementation - `app/analysis/page.js` - Original analysis page with multi-timeframe functionality - `app/automation/page.js` - Original automation page (legacy, may have issues) - `app/automation-v2/page.js` - **NEW**: Clean automation page with full multi-timeframe support - `app/automation/page-v2.js` - Alternative implementation, same functionality as automation-v2 **Multi-Timeframe Architecture Pattern:** ```javascript // Standard timeframes array - use this exact format const timeframes = ['5m', '15m', '30m', '1h', '2h', '4h', '1d']; // State management for multi-timeframe selection const [selectedTimeframes, setSelectedTimeframes] = useState(['1h', '4h']); // Toggle function with proper array handling const toggleTimeframe = (tf) => { setSelectedTimeframes(prev => prev.includes(tf) ? prev.filter(t => t !== tf) // Remove if selected : [...prev, tf] // Add if not selected ); }; // Preset configurations for trading styles const presets = { scalping: ['5m', '15m', '1h'], day: ['1h', '4h', '1d'], swing: ['4h', '1d'] }; ``` **UI Pattern for Timeframe Selection:** ```jsx // Checkbox grid layout with visual feedback