'use client' import React, { useState, useEffect } from 'react' export default function AutomationPage() { const [config, setConfig] = useState({ mode: 'SIMULATION', symbol: 'SOLUSD', timeframe: '1h', tradingAmount: 100, maxLeverage: 3, stopLossPercent: 2, takeProfitPercent: 6, maxDailyTrades: 5, riskPercentage: 2 }) const [status, setStatus] = useState(null) const [isLoading, setIsLoading] = useState(false) const [learningInsights, setLearningInsights] = useState(null) const [recentTrades, setRecentTrades] = useState([]) const [analysisDetails, setAnalysisDetails] = useState(null) useEffect(() => { fetchStatus() fetchLearningInsights() fetchRecentTrades() fetchAnalysisDetails() // Auto-refresh every 30 seconds const interval = setInterval(() => { fetchStatus() fetchAnalysisDetails() }, 30000) return () => clearInterval(interval) }, []) const fetchAnalysisDetails = async () => { try { const response = await fetch('/api/automation/analysis-details') const data = await response.json() if (data.success) { setAnalysisDetails(data.data) // Also update recent trades from the same endpoint if (data.data.recentTrades) { setRecentTrades(data.data.recentTrades) } } } catch (error) { console.error('Failed to fetch analysis details:', error) } } const fetchStatus = async () => { try { const response = await fetch('/api/automation/status') const data = await response.json() if (data.success) { setStatus(data.status) } } catch (error) { console.error('Failed to fetch status:', error) } } const fetchLearningInsights = async () => { try { const response = await fetch('/api/automation/learning-insights') const data = await response.json() if (data.success) { setLearningInsights(data.insights) } } catch (error) { console.error('Failed to fetch learning insights:', error) } } const fetchRecentTrades = async () => { try { // Get enhanced trade data from analysis-details instead of recent-trades const response = await fetch('/api/automation/analysis-details') const data = await response.json() if (data.success && data.data.recentTrades) { setRecentTrades(data.data.recentTrades) } } catch (error) { console.error('Failed to fetch recent trades:', error) } } const handleStart = async () => { setIsLoading(true) try { const response = await fetch('/api/automation/start', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(config) }) const data = await response.json() if (data.success) { fetchStatus() } else { alert('Failed to start automation: ' + data.error) } } catch (error) { console.error('Failed to start automation:', error) alert('Failed to start automation') } finally { setIsLoading(false) } } const handleStop = async () => { setIsLoading(true) try { const response = await fetch('/api/automation/stop', { method: 'POST' }) const data = await response.json() 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 { setIsLoading(false) } } const handlePause = async () => { setIsLoading(true) try { const response = await fetch('/api/automation/pause', { method: 'POST' }) const data = await response.json() if (data.success) { fetchStatus() } else { alert('Failed to pause automation: ' + data.error) } } catch (error) { console.error('Failed to pause automation:', error) alert('Failed to pause automation') } finally { setIsLoading(false) } } const handleResume = async () => { setIsLoading(true) try { const response = await fetch('/api/automation/resume', { method: 'POST' }) const data = await response.json() if (data.success) { fetchStatus() } else { alert('Failed to resume automation: ' + data.error) } } catch (error) { console.error('Failed to resume automation:', error) alert('Failed to resume automation') } finally { setIsLoading(false) } } return (

Automation Mode

AI-powered automated trading on 1H timeframe with learning capabilities

{status?.isActive ? ( <> ) : ( <> {status?.status === 'PAUSED' && ( )} )}
{/* Configuration Panel */}

Configuration

setConfig({...config, tradingAmount: parseFloat(e.target.value)})} className="w-full p-3 bg-gray-800 border border-gray-700 rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-blue-500" disabled={status?.isActive} min="10" step="10" />
setConfig({...config, stopLossPercent: parseFloat(e.target.value)})} className="w-full p-3 bg-gray-800 border border-gray-700 rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-blue-500" disabled={status?.isActive} min="1" max="10" step="0.5" />
setConfig({...config, takeProfitPercent: parseFloat(e.target.value)})} className="w-full p-3 bg-gray-800 border border-gray-700 rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-blue-500" disabled={status?.isActive} min="2" max="20" step="1" />
setConfig({...config, maxDailyTrades: parseInt(e.target.value)})} className="w-full p-3 bg-gray-800 border border-gray-700 rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-blue-500" disabled={status?.isActive} min="1" max="20" />
{/* Learning Insights */} {learningInsights && (

AI Learning Insights

Total Analyses: {learningInsights.totalAnalyses}
Avg Accuracy: {(learningInsights.avgAccuracy * 100).toFixed(1)}%
Best Timeframe: {learningInsights.bestTimeframe}
Worst Timeframe: {learningInsights.worstTimeframe}

Recommendations

    {learningInsights.recommendations.map((rec, idx) => (
  • • {rec}
  • ))}
)}
{/* Status and Performance */}
{/* Status Panel */}

Status

{status ? (
Status: {status.isActive ? 'ACTIVE' : 'STOPPED'}
Mode: {status.mode}
Symbol: {status.symbol}
Timeframe: {status.timeframe}
Total Trades: {status.totalTrades}
Win Rate: 0.6 ? 'text-green-400' : status.winRate > 0.4 ? 'text-yellow-400' : 'text-red-400' }`}> {(status.winRate * 100).toFixed(1)}%
Total P&L: 0 ? 'text-green-400' : status.totalPnL < 0 ? 'text-red-400' : 'text-gray-300' }`}> ${status.totalPnL.toFixed(2)}
{status.lastAnalysis && (
Last Analysis: {new Date(status.lastAnalysis).toLocaleTimeString()}
)} {status.errorCount > 0 && (
Errors: {status.errorCount}
)}
) : (

No active automation session

)}
{/* Recent Trades */}

Recent Automated Trades

{recentTrades.length > 0 ? (
{recentTrades.slice(0, 5).map((trade, idx) => (
{trade.side} {trade.amount} {trade.isActive ? 'ACTIVE' : trade.result}
${trade.entryPrice.toFixed(2)}
{trade.confidence}% confidence
{trade.reason}
{trade.duration}
0 ? 'text-green-400' : 'text-red-400') : (trade.pnl > 0 ? 'text-green-400' : 'text-red-400') }`}> {trade.isActive ? `P&L: ${trade.unrealizedPnl > 0 ? '+' : ''}${trade.unrealizedPnl}` : `P&L: ${trade.pnl > 0 ? '+' : ''}${trade.pnl}` }
{trade.isActive && (
SL: ${trade.stopLoss} Current: ${trade.currentPrice.toFixed(2)} TP: ${trade.takeProfit}
)}
))}
) : (

No recent trades

)}
{/* Detailed AI Analysis Section */} {analysisDetails?.analysis && (

Latest AI Analysis

{/* Main Decision */}

🎯 Trading Decision

Decision: {analysisDetails.analysis.decision}
Confidence: 80 ? 'text-green-400' : analysisDetails.analysis.confidence > 60 ? 'text-yellow-400' : 'text-red-400' }`}> {analysisDetails.analysis.confidence}%
Market Sentiment: {analysisDetails.analysis.sentiment}

Summary: {analysisDetails.analysis.summary}

{/* Key Levels */}

📊 Key Levels

{analysisDetails.analysis.keyLevels?.support?.length > 0 && (

Support Levels

{analysisDetails.analysis.keyLevels.support.map((level, idx) => (
S{idx + 1}: ${level.toFixed(2)}
))}
)} {analysisDetails.analysis.keyLevels?.resistance?.length > 0 && (

Resistance Levels

{analysisDetails.analysis.keyLevels.resistance.map((level, idx) => (
R{idx + 1}: ${level.toFixed(2)}
))}
)}
{/* Technical Indicators */}

📈 Technical Indicators

{analysisDetails.analysis.technicalIndicators && Object.entries(analysisDetails.analysis.technicalIndicators).map(([key, value]) => (
{key.replace(/([A-Z])/g, ' $1').trim()}: {typeof value === 'number' ? value.toFixed(2) : value}
))}
{/* AI Reasoning */} {analysisDetails.analysis.reasoning && (

🤖 AI Reasoning

{analysisDetails.analysis.reasoning}

{analysisDetails.analysis.executionPlan && (

Execution Plan:

{analysisDetails.analysis.executionPlan}

)}
)} {/* Risk Assessment */} {analysisDetails.analysis.riskAssessment && (

⚠️ Risk Assessment

{analysisDetails.analysis.riskAssessment}

{analysisDetails.analysis.marketConditions && (

Market Conditions:

{analysisDetails.analysis.marketConditions}

)}
)} {/* Layout Analysis */} {analysisDetails.analysis.layoutAnalysis && (

🔍 Multi-Layout Analysis

{Object.entries(analysisDetails.analysis.layoutAnalysis).map(([layout, analysis]) => (

{layout} Layout:

{analysis}

))}
)} {/* Performance Metrics */}

📊 Analysis Performance

{analysisDetails.analysis.timestamp ? new Date(analysisDetails.analysis.timestamp).toLocaleTimeString() : 'N/A' }
Last Analysis
{analysisDetails.analysis.processingTime ? `${analysisDetails.analysis.processingTime}ms` : 'N/A' }
Processing Time
{analysisDetails.session?.totalTrades || 0}
Total Trades
{analysisDetails.session?.errorCount || 0}
Errors
)} {/* No Analysis Available */} {!analysisDetails?.analysis && status?.isActive && (

🤖 AI Analysis

Waiting for first analysis...

The AI will analyze the market every hour

)}
) }