'use client' import React, { useState, useEffect } from 'react' import EnhancedAILearningPanel from '../../components/EnhancedAILearningPanel' // 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: 'LIVE', dexProvider: 'DRIFT', symbol: 'SOLUSD', selectedTimeframes: ['5', '15', '30'], // Default to scalping preset tradingAmount: 100, balancePercentage: 100, // Default to 100% of available balance }) const [status, setStatus] = useState(null) const [balance, setBalance] = useState(null) const [positions, setPositions] = useState([]) const [loading, setLoading] = useState(false) const [monitorData, setMonitorData] = useState(null) useEffect(() => { fetchStatus() fetchBalance() fetchPositions() fetchMonitorData() const interval = setInterval(() => { fetchStatus() fetchBalance() fetchPositions() fetchMonitorData() }, 300000) // 5 minutes instead of 30 seconds return () => clearInterval(interval) }, []) const toggleTimeframe = (timeframe) => { setConfig(prev => ({ ...prev, selectedTimeframes: prev.selectedTimeframes.includes(timeframe) ? prev.selectedTimeframes.filter(tf => tf !== timeframe) : [...prev.selectedTimeframes, timeframe] })) } const fetchStatus = async () => { try { console.log('๐ fetchStatus called at:', new Date().toISOString()) const response = await fetch('/api/automation/status') const data = await response.json() console.log('๐ Status response:', data) // Debug log if (response.ok && !data.error) { // If no lastDecision exists, get real analysis data if (!data.lastDecision) { console.log('๐ No lastDecision found, fetching analysis details...') try { const analysisResponse = await fetch('/api/automation/analysis-details') const analysisData = await analysisResponse.json() console.log('๐ง Analysis response:', { success: analysisData.success, hasAnalysis: !!analysisData.data?.analysis }) if (analysisData.success && analysisData.data.analysis) { const analysis = analysisData.data.analysis const recentTrade = analysisData.data.recentTrades?.[0] console.log('โ Creating lastDecision from analysis:', { decision: analysis.decision, confidence: analysis.confidence, hasRecentTrade: !!recentTrade }) data.lastDecision = { recommendation: analysis.decision || 'HOLD', confidence: analysis.confidence || 84, minConfidenceRequired: 70, executed: recentTrade ? true : false, timestamp: analysis.timestamp || Date.now(), reasoning: analysis.reasoning || `Recent multi-timeframe analysis shows ${analysis.decision} signal with ${analysis.confidence}% confidence. Based on comprehensive technical analysis across multiple timeframes: โข **Multi-timeframe consensus**: ${analysis.multiTimeframeResults?.length || 3} timeframes analyzed โข **Current signal**: ${analysis.decision} with ${analysis.confidence}% confidence โข **Entry level**: $${analysis.entry?.price || '187.25'} ${analysis.entry?.buffer || 'ยฑ0.25'} โข **Risk management**: Stop at $${analysis.stopLoss?.price || '185.50'}, Target $${analysis.takeProfits?.tp1?.price || '193.00'} โข **Analysis timestamp**: ${new Date(analysis.timestamp).toLocaleString()}`, executionDetails: recentTrade ? { leverage: recentTrade.leverage || 3, entryPrice: recentTrade.entryPrice || recentTrade.price, stopLoss: analysis.stopLoss?.price || 185.50, takeProfit: analysis.takeProfits?.tp1?.price || 193.00, positionSize: recentTrade.positionSize || recentTrade.amount || 15.2, side: recentTrade.side || 'BUY', amount: recentTrade.realTradingAmount || recentTrade.tradingAmount || recentTrade.actualInvestment } : null, isRetrospective: false } } } catch (analysisError) { console.warn('โ Could not fetch analysis details:', analysisError) } } console.log('๐ฏ Setting status with lastDecision:', !!data.lastDecision) setStatus(data) // Status data is returned directly, not wrapped in 'success' } else { console.error('โ Status API error:', data.error || 'Unknown error') } } 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 fetchMonitorData = async () => { try { const response = await fetch('/api/automation/position-monitor') const data = await response.json() if (data.success) { setMonitorData(data.monitor) } } catch (error) { console.error('Failed to fetch monitor data:', 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 automation...') setLoading(true) try { if (config.selectedTimeframes.length === 0) { console.error('No timeframes selected') setLoading(false) return } const automationConfig = { symbol: config.symbol, selectedTimeframes: config.selectedTimeframes, mode: config.mode, tradingAmount: config.tradingAmount, leverage: config.leverage, stopLoss: config.stopLoss, takeProfit: config.takeProfit } const response = await fetch('/api/automation/start', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(automationConfig) }) const data = await response.json() if (data.success) { console.log('โ Automation started successfully') if (data.learningSystem?.integrated) { console.log('๐ง AI Learning System: Activated') } fetchStatus() } else { console.error('Failed to start automation:', data.error) } } catch (error) { console.error('Failed to start automation:', error) } finally { setLoading(false) } } const handleStop = async () => { console.log('๐ Stopping automation...') setLoading(true) try { const response = await fetch('/api/automation/stop', { method: 'POST', headers: { 'Content-Type': 'application/json' } }) const data = await response.json() if (data.success) { console.log('โ Automation stopped successfully') fetchStatus() } else { console.error('Failed to stop automation:', data.error) } } catch (error) { console.error('Failed to stop automation:', error) } finally { setLoading(false) } } const handleEmergencyStop = async () => { console.log('๐จ Emergency stop triggered!') setLoading(true) try { const response = await fetch('/api/automation/emergency-stop', { method: 'POST', headers: { 'Content-Type': 'application/json' } }) const data = await response.json() if (data.success) { console.log('โ Emergency stop completed successfully') fetchStatus() fetchPositions() fetchMonitorData() fetchMonitorData() } else { console.error('Emergency stop failed:', data.error) } } catch (error) { console.error('Emergency stop error:', error) } finally { setLoading(false) } } const generateTestDecision = async () => { console.log('๐งช Generating test AI decision...') setLoading(true) try { const response = await fetch('/api/automation/test-decision', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'generate_test_decision', analysis: { recommendation: 'STRONG BUY', confidence: 89, reasoning: `๐ฏ BULLISH CONVERGENCE DETECTED: ๐ Technical Analysis: โข RSI bounced from oversold (28โ54) showing strong recovery momentum โข MACD histogram turning positive with bullish crossover confirmed โข Price broke above key resistance at $185.40 with 3x normal volume โข 20 EMA (184.92) providing strong support, price trending above all major EMAs ๐ Market Structure: โข Higher lows pattern intact since yesterday's session โข Volume profile shows accumulation at current levels โข Order book depth favoring buyers (67% buy-side liquidity) โก Entry Trigger: โข Breakout candle closed above $186.00 resistance with conviction โข Next resistance target: $189.75 (2.1% upside potential) โข Risk/Reward ratio: 1:2.3 (excellent risk management setup) ๐ก๏ธ Risk Management: โข Stop loss at $184.20 (1.0% below entry) protects against false breakout โข Position sizing optimized for 2% account risk tolerance`, stopLoss: 184.20, takeProfit: 189.75, currentPrice: 186.12, stopLossPercent: '1.0% protective stop' }, config: { selectedTimeframes: config.selectedTimeframes, symbol: config.symbol, mode: config.mode, enableTrading: config.enableTrading, tradingAmount: 62 } }) }) const data = await response.json() if (data.success) { console.log('โ Test decision generated successfully') fetchStatus() // Refresh to show the decision } else { console.error('Failed to generate test decision:', data.error) } } catch (error) { console.error('Test decision error:', error) } finally { setLoading(false) } } const analyzeExistingPosition = async () => { console.log('๐ Analyzing existing position...') setLoading(true) try { // First get the current position data const positionResponse = await fetch('/api/automation/position-monitor') const positionData = await positionResponse.json() if (positionData.success && positionData.monitor.hasPosition) { // Analyze the existing position const response = await fetch('/api/automation/analyze-position', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'analyze_existing_position', positionData: positionData.monitor.position }) }) const data = await response.json() if (data.success) { console.log('โ Position analysis generated successfully') fetchStatus() // Refresh to show the analysis } else { console.error('Failed to analyze position:', data.error) } } else { console.log('โน๏ธ No position found to analyze') alert('No active position found to analyze') } } catch (error) { console.error('Position analysis error:', error) } finally { setLoading(false) } } return (
Advanced AI-powered trading with real-time analysis and risk management
Configure and manage your AI trading bot
Status โข Positions โข Risk Monitor
{status.rateLimitMessage}
)}Automation stopped. Recharge OpenAI account to continue.
Live Drift Protocol data
Real-time market intelligence and decision reasoning
The AI will analyze market conditions using advanced technical indicators across multiple timeframes and provide detailed reasoning for all trading decisions.