'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 [aiLearningStatus, setAiLearningStatus] = useState(null)
const [recentTrades, setRecentTrades] = useState([])
const [analysisDetails, setAnalysisDetails] = useState(null)
useEffect(() => {
fetchStatus()
fetchLearningInsights()
fetchAiLearningStatus()
fetchRecentTrades()
fetchAnalysisDetails()
// Auto-refresh every 30 seconds
const interval = setInterval(() => {
fetchStatus()
fetchAnalysisDetails()
fetchAiLearningStatus()
}, 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 fetchAiLearningStatus = async () => {
try {
const response = await fetch('/api/ai-learning-status')
const data = await response.json()
if (data.success) {
setAiLearningStatus(data.data)
}
} catch (error) {
console.error('Failed to fetch AI learning status:', 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
{/* AI Learning Status */}
{aiLearningStatus && (
🧠 AI Learning Status
{/* Learning Phase */}
{aiLearningStatus.phaseDescription}
Phase: {aiLearningStatus.phase.replace('_', ' ')}
{aiLearningStatus.totalAnalyses}
Total Analyses
{aiLearningStatus.totalTrades}
Total Trades
{/* Performance Metrics */}
{(aiLearningStatus.avgAccuracy * 100).toFixed(1)}%
Avg Accuracy
{(aiLearningStatus.winRate * 100).toFixed(1)}%
Win Rate
{aiLearningStatus.confidenceLevel.toFixed(1)}%
Confidence Level
{/* Strengths and Improvements */}
Strengths
{aiLearningStatus.strengths.map((strength, idx) => (
- ✓ {strength}
))}
Areas for Improvement
{aiLearningStatus.improvements.map((improvement, idx) => (
- • {improvement}
))}
{/* Next Milestone */}
Next Milestone
{aiLearningStatus.nextMilestone}
{/* Recommendation */}
AI Recommendation
{aiLearningStatus.recommendation}
)}
{/* 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 Header */}
{trade.side}
{trade.amount}
{trade.leverage}x
{trade.isActive ? 'ACTIVE' : trade.result}
${trade.entryPrice.toFixed(2)}
{trade.confidence}% confidence
{/* Trading Details */}
Trading Amount:
${trade.tradingAmount}
Leverage:
{trade.leverage}x
Position Size:
${trade.positionSize}
Entry Price:
${trade.entryPrice.toFixed(2)}
{/* Analysis Context */}
{trade.triggerAnalysis && (
📊 Trigger Analysis
Decision:
{trade.triggerAnalysis.decision} ({trade.triggerAnalysis.confidence}%)
Market Condition:
{trade.triggerAnalysis.marketCondition}
Expected R/R:
{trade.triggerAnalysis.riskReward}
Key Signals:
{trade.triggerAnalysis.keySignals.map((signal, signalIdx) => (
- • {signal}
))}
)}
{/* Current Metrics (Active Trades) */}
{trade.isActive && trade.currentMetrics && (
📈 Current Status
Current Price:
${trade.currentMetrics.currentPrice.toFixed(2)}
Price Change:
0 ? 'text-green-400' : 'text-red-400'}`}>
{trade.currentMetrics.priceChange > 0 ? '+' : ''}${trade.currentMetrics.priceChange.toFixed(2)}
Unrealized P&L:
0 ? 'text-green-400' : 'text-red-400'}`}>
{trade.currentMetrics.unrealizedPnL > 0 ? '+' : ''}${trade.currentMetrics.unrealizedPnL.toFixed(2)}
Time in Trade:
{trade.currentMetrics.timeInTrade}
)}
{/* Exit Metrics (Completed Trades) */}
{!trade.isActive && trade.exitMetrics && (
📊 Exit Analysis
Exit Reason:
{trade.exitMetrics.exitReason}
Exit Price:
${trade.exitMetrics.exitPrice.toFixed(2)}
Analysis Accuracy:
{trade.exitMetrics.analysisAccuracy}
Actual R/R:
{trade.exitMetrics.actualRiskReward}
)}
{/* Trade Summary */}
{trade.duration} | ${trade.tradingAmount} @ {trade.leverage}x
SL: ${trade.stopLoss} | TP: ${trade.takeProfit}
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}`
}
))}
) : (
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
)}
)
}