'use client' import React, { useState, useEffect } from 'react' // Available timeframes for automation (matching analysis page format) const timeframes = [ { label: '5m', value: '5' }, { label: '15m', value: '15' }, { label: '30m', value: '30' }, { label: '1h', value: '60' }, { label: '2h', value: '120' }, { label: '4h', value: '240' }, { label: '1d', value: 'D' }, ] export default function AutomationPageV2() { const [config, setConfig] = useState({ mode: 'SIMULATION', dexProvider: 'DRIFT', symbol: 'SOLUSD', timeframe: '1h', // Primary timeframe for backwards compatibility selectedTimeframes: ['60'], // Multi-timeframe support tradingAmount: 100, balancePercentage: 50, // Default to 50% of available balance // stopLossPercent and takeProfitPercent removed - AI calculates these automatically }) const [status, setStatus] = useState(null) const [balance, setBalance] = useState(null) const [positions, setPositions] = useState([]) const [loading, setLoading] = useState(false) const [nextAnalysisCountdown, setNextAnalysisCountdown] = useState(0) useEffect(() => { fetchStatus() fetchBalance() fetchPositions() const interval = setInterval(() => { fetchStatus() fetchBalance() fetchPositions() }, 30000) return () => clearInterval(interval) }, []) // Timer effect for countdown useEffect(() => { let countdownInterval = null if (status?.isActive && status?.nextAnalysisIn > 0) { setNextAnalysisCountdown(status.nextAnalysisIn) countdownInterval = setInterval(() => { setNextAnalysisCountdown(prev => { if (prev <= 1) { // Refresh status when timer reaches 0 fetchStatus() return 0 } return prev - 1 }) }, 1000) } else { setNextAnalysisCountdown(0) } return () => { if (countdownInterval) { clearInterval(countdownInterval) } } }, [status?.nextAnalysisIn, status?.isActive]) // Helper function to format countdown time const formatCountdown = (seconds) => { if (seconds <= 0) return 'Analyzing now...' const hours = Math.floor(seconds / 3600) const minutes = Math.floor((seconds % 3600) / 60) const secs = seconds % 60 if (hours > 0) { return `${hours}h ${minutes}m ${secs}s` } else if (minutes > 0) { return `${minutes}m ${secs}s` } else { return `${secs}s` } } const toggleTimeframe = (timeframe) => { setConfig(prev => ({ ...prev, selectedTimeframes: prev.selectedTimeframes.includes(timeframe) ? prev.selectedTimeframes.filter(tf => tf !== timeframe) : [...prev.selectedTimeframes, timeframe] })) } const fetchStatus = async () => { try { const response = await fetch('/api/automation/status') const data = await response.json() console.log('Status fetched:', data) // Debug log if (data.success) { setStatus(data.status) } } catch (error) { console.error('Failed to fetch status:', error) } } const fetchBalance = async () => { try { const response = await fetch('/api/drift/balance') const data = await response.json() if (data.success) { setBalance(data) } } catch (error) { console.error('Failed to fetch balance:', error) } } const fetchPositions = async () => { try { const response = await fetch('/api/drift/positions') const data = await response.json() if (data.success) { setPositions(data.positions || []) } } catch (error) { console.error('Failed to fetch positions:', error) } } const handleStart = async () => { console.log('š Starting OPTIMIZED automation with batch processing!') setLoading(true) try { // Ensure we have selectedTimeframes before starting if (config.selectedTimeframes.length === 0) { alert('Please select at least one timeframe for analysis') setLoading(false) return } console.log('š„ Starting OPTIMIZED automation with config:', { ...config, selectedTimeframes: config.selectedTimeframes }) // š„ USE THE NEW FANCY OPTIMIZED ENDPOINT! š„ const optimizedConfig = { symbol: config.symbol, // FIX: Use config.symbol not config.asset timeframes: config.selectedTimeframes, layouts: ['ai', 'diy'], analyze: true, automationMode: true, // Flag to indicate this is automation, not just testing mode: config.mode, // Pass the user's trading mode choice tradingAmount: config.tradingAmount, balancePercentage: config.balancePercentage, dexProvider: config.dexProvider } const startTime = Date.now() const response = await fetch('/api/analysis-optimized', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(optimizedConfig) }) const duration = ((Date.now() - startTime) / 1000).toFixed(1) const data = await response.json() if (data.success) { console.log(`š OPTIMIZED automation completed in ${duration}s!`) console.log(`šø Screenshots: ${data.screenshots?.length || 0}`) console.log(`š¤ Analysis: ${data.analysis ? 'Yes' : 'No'}`) // Show clean success message without performance spam const message = data.mode === 'automation' ? `š Optimized Automation Started!\n\nā±ļø Duration: ${duration}s\nļæ½ Analysis: ${data.analysis ? `${data.analysis.overallRecommendation} (${data.analysis.confidence}% confidence)` : 'Completed'}\nš° Trade: ${data.trade?.executed ? `${data.trade.direction} executed` : 'No trade executed'}` : `ā Analysis Complete!\n\nā±ļø Duration: ${duration}s\nš Recommendation: ${data.analysis ? `${data.analysis.overallRecommendation} (${data.analysis.confidence}% confidence)` : 'No analysis'}` alert(message) fetchStatus() // Refresh to show automation status } else { alert('Failed to start optimized automation: ' + data.error) } } catch (error) { console.error('Failed to start automation:', error) alert('Failed to start automation') } finally { setLoading(false) } } const handleStop = async () => { console.log('Stop button clicked') // Debug log setLoading(true) try { const response = await fetch('/api/automation/stop', { method: 'POST' }) const data = await response.json() console.log('Stop response:', data) // Debug log if (data.success) { fetchStatus() } else { alert('Failed to stop automation: ' + data.error) } } catch (error) { console.error('Failed to stop automation:', error) alert('Failed to stop automation') } finally { setLoading(false) } } const handleOptimizedTest = async () => { console.log('š Testing optimized analysis...') setLoading(true) try { // Ensure we have selectedTimeframes before testing if (config.selectedTimeframes.length === 0) { alert('Please select at least one timeframe for optimized analysis test') setLoading(false) return } const testConfig = { symbol: config.symbol, // FIX: Use config.symbol not config.asset timeframes: config.selectedTimeframes, layouts: ['ai', 'diy'], analyze: true } console.log('š¬ Testing with config:', testConfig) const startTime = Date.now() const response = await fetch('/api/analysis-optimized', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(testConfig) }) const duration = ((Date.now() - startTime) / 1000).toFixed(1) const data = await response.json() if (data.success) { console.log('ā Optimized analysis completed!') console.log(`ā±ļø Duration: ${duration}s`) console.log(`šø Screenshots: ${data.screenshots?.length || 0}`) console.log(`š¤ Analysis: ${data.analysis ? 'Yes' : 'No'}`) console.log(`š Efficiency: ${data.optimization?.efficiency || 'N/A'}`) alert(`ā Optimized Analysis Complete!\n\nā±ļø Duration: ${duration}s\nšø Screenshots: ${data.screenshots?.length || 0}\nš Efficiency: ${data.optimization?.efficiency || 'N/A'}\n\n${data.analysis ? `š Recommendation: ${data.analysis.overallRecommendation} (${data.analysis.confidence}% confidence)` : ''}`) } else { console.error('ā Optimized analysis failed:', data.error) alert(`ā Optimized analysis failed: ${data.error}`) } } catch (error) { console.error('Failed to run optimized analysis:', error) alert('Failed to run optimized analysis: ' + error.message) } finally { setLoading(false) } } return (
70% faster processing ⢠Single AI call ⢠Parallel screenshot capture
Drift Protocol - Multi-Timeframe Batch Analysis (70% Faster)
Stop loss and take profit levels are automatically calculated by the AI based on:
ā Ultra-tight scalping enabled (0.5%+ stop losses proven effective)
Loading bot status...
)}