'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 { 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) { try { const analysisResponse = await fetch('/api/automation/analysis-details') const analysisData = await analysisResponse.json() if (analysisData.success && analysisData.data.analysis) { const analysis = analysisData.data.analysis const recentTrade = analysisData.data.recentTrades?.[0] 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.amount || 15.2 } : null, isRetrospective: false } } } catch (analysisError) { console.warn('Could not fetch analysis details:', analysisError) } } 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 (
{/* Page Header */}

🤖 AI Trading Automation

Advanced AI-powered trading with real-time analysis and risk management

{/* Main Grid Layout */}
{/* Automation Control Panel - Main Column */}
{/* Control Header with Enhanced Buttons */}
🤖

Automation Control

Configure and manage your AI trading bot

{status?.isActive ? ( <> ) : ( )} {/* Test & Analysis Buttons */}
{/* Trading Mode Selection - Enhanced Cards */}
{/* Symbol and Balance Configuration */}
{ const percentage = parseFloat(e.target.value); const newAmount = balance ? (parseFloat(balance.availableBalance) * percentage / 100) : 100; setConfig({ ...config, balancePercentage: percentage, tradingAmount: Math.round(newAmount) }); }} disabled={status?.isActive} />
Conservative (10%) Balanced (50%) Aggressive (100%)
{/* Enhanced Multi-Timeframe Selection */}
{/* Timeframe Selection Grid */}
{timeframes.map(tf => ( ))}
{/* Selected Timeframes Display */} {config.selectedTimeframes.length > 0 && (
Selected Timeframes: {config.selectedTimeframes.map(tf => timeframes.find(t => t.value === tf)?.label || tf).filter(Boolean).join(', ')}
💡 Multi-timeframe analysis
)} {/* Trading Style Presets - Enhanced Cards */}
{/* Enhanced Sidebar */}
{/* Unified Trading Dashboard Card */}
{status?.isActive ? '🟢' : '⚪'}

Trading Dashboard

Status • Positions • Risk Monitor

{/* Bot Status Section */}

🤖Bot Status

Status: {status?.isActive ? 'RUNNING' : 'STOPPED'}
{status?.isActive && ( <>
Symbol: {status.symbol}
Mode: {status.mode}
Timeframes:
{status.timeframes?.map((tf, index) => ( {timeframes.find(t => t.value === tf)?.label || tf} ))}
)} {/* Rate Limit Warning */} {status?.rateLimitHit && (
⚠️ Rate Limit Reached
{status.rateLimitMessage && (

{status.rateLimitMessage}

)}

Automation stopped. Recharge OpenAI account to continue.

)}
{/* Position Monitor Section */} {monitorData && (

📊Position Monitor

Has Position: {monitorData.hasPosition ? '✅ YES' : '❌ NO'}
Risk Level: {monitorData.riskLevel}
Next Action:
{monitorData.nextAction}
{monitorData.orphanedOrderCleanup && (
{monitorData.orphanedOrderCleanup.success ? '✅ Cleanup Success' : '❌ Cleanup Failed'}
{monitorData.orphanedOrderCleanup.message}
)}
)} {/* Open Positions Section */} {positions.length > 0 && (

📈Open Positions {positions.length}

{positions.map((position, index) => (
{position.symbol} {position.side}
Size: {position.symbol?.includes('SOL') ? `${parseFloat(position.size).toFixed(2)} SOL` : `$${parseFloat(position.size).toFixed(2)}` }
Value: ${((parseFloat(position.size) || 0) * (parseFloat(position.markPrice) || parseFloat(position.entryPrice) || 0)).toFixed(2)}
{position.entryPrice && (
Entry: ${parseFloat(position.entryPrice).toFixed(2)}
)} {position.markPrice && (
Mark: ${parseFloat(position.markPrice).toFixed(2)}
)} {position.pnl !== undefined && (
PnL: = 0 ? 'text-green-400' : 'text-red-400' }`}> ${position.pnl >= 0 ? '+' : ''}${parseFloat(position.pnl).toFixed(2)}
)}
))}
)}
{/* Account Balance Card */} {balance && (
💰

Account Balance

Live Drift Protocol data

Available Balance
${parseFloat(balance.availableBalance).toFixed(2)}
Total Collateral
${parseFloat(balance.totalCollateral).toFixed(2)}
Total Positions
{balance.positions || 0}
)}
{/* Enhanced AI Learning System Panel */} {/* Enhanced AI Trading Analysis Panel */}
🧠

AI Trading Analysis

Real-time market intelligence and decision reasoning

{status?.lastDecision ? '🟢 Analysis Active' : '⚪ Waiting for Analysis'}
{status?.lastDecision ? (
{/* Quick Summary Cards */}
Recommendation
{status.lastDecision.recommendation || 'HOLD'}
{status.lastDecision.isRetrospective && (
📊 Retrospective Analysis
)}
Confidence
= 80 ? 'text-green-300' : status.lastDecision.confidence >= 70 ? 'text-yellow-300' : 'text-red-300' }`}> {status.lastDecision.confidence}%
Min Required: {status.lastDecision.minConfidenceRequired}%
Execution
{status.lastDecision.executed ? '✅ EXECUTED' : '❌ NOT EXECUTED'}
{new Date(status.lastDecision.timestamp).toLocaleTimeString()}
{status.lastDecision.executed && status.lastDecision.executionDetails && (
Leverage
{status.lastDecision.executionDetails.leverage}x
AI Calculated
)}
{/* Main Analysis Content */}
{/* AI Reasoning */}

🎯 Market Analysis & Reasoning

{status.lastDecision.reasoning}
{/* Execution Error */} {!status.lastDecision.executed && status.lastDecision.executionError && (

Execution Failed

{status.lastDecision.executionError}
)}
{/* Trade Execution Details */} {status.lastDecision.executed && status.lastDecision.executionDetails && (

📈 Trade Execution Details

Entry Price
${status.lastDecision.executionDetails.currentPrice?.toFixed(4)}
Position Size
${status.lastDecision.executionDetails.amount}
Direction
{status.lastDecision.executionDetails.side}
Leverage
{status.lastDecision.executionDetails.leverage}x
{/* Risk Management */}
🛡️ Risk Management
Stop Loss: ${status.lastDecision.executionDetails.stopLoss?.toFixed(4)}
Take Profit: ${status.lastDecision.executionDetails.takeProfit?.toFixed(4)}
{status.lastDecision.executionDetails.txId && (
Transaction ID: {status.lastDecision.executionDetails.txId.substring(0, 12)}...
)}
{/* AI Leverage Reasoning */}

AI Leverage Analysis

{status.lastDecision.executionDetails.aiReasoning}
)}
) : (
🤖

AI Analysis Standby

The AI will analyze market conditions using advanced technical indicators across multiple timeframes and provide detailed reasoning for all trading decisions.

What you'll see when analysis starts:
🎯
Entry Strategy
Why AI chose this entry point
🛡️
Risk Management
Stop loss and take profit logic
📊
Technical Analysis
Multi-timeframe indicator consensus
Leverage Calculation
AI's dynamic risk assessment
🎲
Confidence Scoring
Probability-based decision making
Execution Status
Real-time trade confirmation
)}
) }