'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) const [automationDisabled, setAutomationDisabled] = useState(false) // Track manual disable state const [actionFeedback, setActionFeedback] = useState(null) // Track button action feedback const [liveDecisions, setLiveDecisions] = useState([]) // Live trading decisions useEffect(() => { fetchStatus() fetchBalance() fetchPositions() fetchMonitorData() fetchLiveDecisions() const interval = setInterval(() => { fetchStatus() fetchBalance() fetchPositions() fetchMonitorData() fetchLiveDecisions() // Fetch live decisions frequently }, 30000) // 30 seconds for live data 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 fetchLiveDecisions = async () => { try { const response = await fetch('/api/automation/live-decisions') const data = await response.json() if (data.success) { setLiveDecisions(data.decisions || []) console.log('๐Ÿ“Š Live decisions fetched:', data.decisions?.length || 0) } } catch (error) { console.error('Failed to fetch live decisions:', 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 () => { const isCurrentlyDisabled = automationDisabled if (status?.isActive) { // If automation is running, stop it console.log('๐Ÿ›‘ Stopping active automation...') setActionFeedback({ type: 'info', message: 'Stopping automation...' }) } else if (!isCurrentlyDisabled) { // If automation not running but not disabled, disable it console.log('๐Ÿ›‘ Disabling automation triggers...') setActionFeedback({ type: 'warning', message: 'Disabling automation triggers...' }) } else { // If disabled, enable it console.log('โœ… Enabling automation triggers...') setAutomationDisabled(false) setActionFeedback({ type: 'success', message: 'โœ… Automation triggers ENABLED - System ready for automated trading' }) setLoading(false) // Clear feedback after 3 seconds setTimeout(() => setActionFeedback(null), 3000) return } 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) { if (status?.isActive) { console.log('โœ… Automation stopped successfully') setActionFeedback({ type: 'success', message: 'โœ… Automation STOPPED successfully' }) } else { console.log('โœ… Automation triggers disabled') setAutomationDisabled(true) setActionFeedback({ type: 'success', message: '๐Ÿšซ Automation triggers DISABLED - Safe to close positions manually' }) } fetchStatus() } else { console.error('Failed to stop automation:', data.error) setActionFeedback({ type: 'error', message: 'โŒ Failed to change automation state' }) } } catch (error) { console.error('Failed to stop automation:', error) setActionFeedback({ type: 'error', message: 'โŒ Network error - please try again' }) } finally { setLoading(false) // Clear feedback after 3 seconds setTimeout(() => setActionFeedback(null), 3000) } } 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 Section - Header removed to save space */}
{/* Action Feedback */} {actionFeedback && (
{actionFeedback.message}
)} {/* Automation Trigger Status Indicator */} {(positions.length > 0 && !status?.isActive) && (
โšก Automation Triggers:
{automationDisabled ? '๐Ÿšซ' : 'โœ…'} {automationDisabled ? 'DISABLED' : 'ENABLED'}
{automationDisabled ? 'Safe to close positions manually - no automation will trigger' : 'Automation can start when conditions are met (position close, signals, etc.)' }
)}
{(status?.isActive || positions.length > 0) ? ( <> ) : ( )} {/* 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'}
{/* Automation Trigger Status */}
Triggers: {automationDisabled ? '๐Ÿšซ DISABLED' : 'โœ… ENABLED'}
{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

0 ? 'bg-green-400 animate-pulse shadow-green-400/50' : 'bg-gray-500' }`}>
{liveDecisions?.length > 0 ? '๐ŸŸข Live Analysis Active' : 'โšช Waiting for Analysis'}
{liveDecisions?.length > 0 ? (
{/* Current Decision Summary */} {liveDecisions[0] && (
Latest Decision
{liveDecisions[0].action || 'UNKNOWN'}
{liveDecisions[0].blocked ? '๐Ÿšซ BLOCKED' : 'โœ… EXECUTED'}
Confidence
= 80 ? 'text-green-300' : liveDecisions[0].confidence >= 70 ? 'text-yellow-300' : 'text-red-300' }`}> {liveDecisions[0].confidence || 0}%
Entry: ${liveDecisions[0].entryPrice?.toFixed(2) || 'N/A'}
Risk Management
SL: ${liveDecisions[0].stopLoss?.toFixed(2) || 'N/A'}
TP: ${liveDecisions[0].takeProfit?.toFixed(2) || 'N/A'}
Leverage
{liveDecisions[0].leverage || 1}x
{new Date(liveDecisions[0].timestamp).toLocaleTimeString()}
)} {/* Main Analysis Content */}
{/* AI Reasoning */}

๐ŸŽฏ Market Analysis & Reasoning

{liveDecisions[0]?.reasoning || 'No reasoning available'}
{/* Block Reason */} {liveDecisions[0]?.blocked && liveDecisions[0]?.blockReason && (

๐Ÿšซ Risk Management Block

{liveDecisions[0].blockReason}
)}
{/* Recent Decisions History */}

๐Ÿ“Š Recent Decisions ({liveDecisions.length})

{liveDecisions.slice(0, 5).map((decision, index) => (
{decision.action} {decision.symbol}
{new Date(decision.timestamp).toLocaleTimeString()}
Entry: ${decision.entryPrice?.toFixed(2)} | {decision.leverage}x leverage | {decision.confidence}% confidence
{decision.blocked ? (
๐Ÿšซ Blocked: {decision.blockReason?.substring(0, 100)}...
) : (
โœ… Executed with SL: ${decision.stopLoss?.toFixed(2)} TP: ${decision.takeProfit?.toFixed(2)}
)}
))}
) : (
๐Ÿค–

๐Ÿ“ˆ Trade Execution Details

Entry Price
${latestDecision?.details?.entryPrice?.toFixed(4) || 'N/A'}
Position Size
${latestDecision?.details?.amount || 'N/A'}
Direction
{latestDecision?.details?.side || 'N/A'}
Leverage
{latestDecision?.details?.leverage || 'N/A'}x
{/* Risk Management */}
๐Ÿ›ก๏ธ Risk Management
Stop Loss: ${latestDecision?.details?.stopLoss?.toFixed(4) || 'N/A'}
Take Profit: ${latestDecision?.details?.takeProfit?.toFixed(4) || 'N/A'}
{latestDecision?.details?.txId && (
Transaction ID: {latestDecision.details.txId.substring(0, 12)}...
)}
{/* AI Leverage Reasoning */}

โšก AI Leverage Analysis

{latestDecision?.details?.aiReasoning || latestDecision?.blockReason || 'No AI analysis available'}
) : (
๐Ÿค–

Waiting for Live Analysis Data

Automation is running every 2 minutes. Live trading decisions and risk management details will appear here as soon as the AI analyzes market conditions and attempts trades.

{/* Real-time Status */}
๐Ÿ”„ System Status
โœ… Automation Active
Scanning every 2 minutes
๐Ÿ›ก๏ธ Risk Management
Mandatory protection active
What you'll see when analysis data arrives:
๐ŸŽฏ
Trade Decisions
BUY/SELL signals with confidence
๏ฟฝ
Risk Blocks
Why trades were blocked by safety
๐Ÿ“Š
AI Reasoning
Detailed market analysis
๐Ÿ’ฐ
Entry/SL/TP Details
Exact price levels and leverage
โœ…
Execution Status
Live trade confirmations
๐Ÿ“ˆ
Decision History
Recent analysis timeline
Leverage Calculation
AI's dynamic risk assessment
๐ŸŽฒ
Confidence Scoring
Probability-based decision making
โœ…
Execution Status
Real-time trade confirmation
)} ) }