feat: implement comprehensive AI decision display and reasoning panel

Major Features Added:
- Complete AI decision tracking system with detailed reasoning display
- Prominent gradient-styled AI reasoning panel on automation-v2 page
- Test AI decision generator with realistic trading scenarios
- Enhanced decision transparency showing entry/exit logic and leverage calculations

- Fixed orphaned order cleanup to preserve reduce-only SL/TP orders
- Integrated AI leverage calculator with 100x capability (up from 10x limit)
- Added lastDecision property to automation status for UI display
- Enhanced position monitoring with better cleanup triggers

- Beautiful gradient-styled AI Trading Analysis panel
- Color-coded confidence levels and recommendation displays
- Detailed breakdown of entry strategy, stop loss logic, and take profit targets
- Real-time display of AI leverage reasoning with safety buffer explanations
- Test AI button for demonstration of decision-making process

- SL/TP orders now execute properly (fixed cleanup interference)
- AI calculates sophisticated leverage (8.8x-42.2x vs previous 1x hardcoded)
- Complete decision audit trail with execution details
- Risk management transparency with liquidation safety calculations

- Why This Decision? - Prominent reasoning section
- Entry & Exit Strategy - Price levels with color coding
- AI Leverage Decision - Detailed calculation explanations
- Execution status with success/failure indicators
- Transaction IDs and comprehensive trade details

All systems now provide full transparency of AI decision-making process.
This commit is contained in:
mindesbunister
2025-07-26 22:41:55 +02:00
parent 30eb869ca4
commit 167d7ff5bc
23 changed files with 3233 additions and 52 deletions

View File

@@ -96,47 +96,62 @@ export async function GET() {
const activeOrders = ordersData.orders || [];
if (activeOrders.length > 0) {
console.log('📋 No active positions detected - checking for orphaned orders...');
console.log(`🎯 Found ${activeOrders.length} orphaned orders - triggering cleanup...`);
console.log('📋 No active positions detected - checking for truly orphaned orders...');
// Trigger automated cleanup of orphaned orders
const cleanupResponse = await fetch(`${baseUrl}/api/drift/cleanup-orders`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
});
// Filter for truly orphaned orders (non-reduce-only orders without positions)
// Do NOT clean up reduce-only orders as these could be legitimate SL/TP from recently closed positions
const trulyOrphanedOrders = activeOrders.filter(order => !order.reduceOnly);
let cleanupResult = null;
if (cleanupResponse.ok) {
cleanupResult = await cleanupResponse.json();
if (trulyOrphanedOrders.length > 0) {
console.log(`🎯 Found ${trulyOrphanedOrders.length} truly orphaned orders (non-reduce-only) - triggering cleanup...`);
if (cleanupResult.success) {
console.log('✅ Orphaned order cleanup completed:', cleanupResult.summary);
result.orphanedOrderCleanup = {
triggered: true,
success: true,
summary: cleanupResult.summary,
message: `Cleaned up ${cleanupResult.summary.totalCanceled} orphaned orders`
};
result.nextAction = `Cleaned up ${cleanupResult.summary.totalCanceled} orphaned orders - Ready for new trade`;
// Trigger automated cleanup of truly orphaned orders only
const cleanupResponse = await fetch(`${baseUrl}/api/drift/cleanup-orders`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
});
let cleanupResult = null;
if (cleanupResponse.ok) {
cleanupResult = await cleanupResponse.json();
if (cleanupResult.success) {
console.log('✅ Orphaned order cleanup completed:', cleanupResult.summary);
result.orphanedOrderCleanup = {
triggered: true,
success: true,
summary: cleanupResult.summary,
message: `Cleaned up ${cleanupResult.summary.totalCanceled} truly orphaned orders`
};
result.nextAction = `Cleaned up ${cleanupResult.summary.totalCanceled} orphaned orders - Ready for new trade`;
} else {
console.error('❌ Orphaned order cleanup failed:', cleanupResult.error);
result.orphanedOrderCleanup = {
triggered: true,
success: false,
error: cleanupResult.error,
message: 'Cleanup failed - Manual intervention may be needed'
};
result.nextAction = 'Cleanup failed - Check orders manually';
}
} else {
console.error('❌ Orphaned order cleanup failed:', cleanupResult.error);
console.error('❌ Failed to trigger cleanup API');
result.orphanedOrderCleanup = {
triggered: true,
triggered: false,
success: false,
error: cleanupResult.error,
message: 'Cleanup failed - Manual intervention may be needed'
error: 'Cleanup API unavailable',
message: 'Could not trigger automatic cleanup'
};
result.nextAction = 'Cleanup failed - Check orders manually';
}
} else {
console.error('❌ Failed to trigger cleanup API');
// All orders are reduce-only (likely SL/TP) - do not clean up
console.log('✅ All remaining orders are reduce-only (likely SL/TP) - skipping cleanup to preserve risk management');
result.orphanedOrderCleanup = {
triggered: false,
success: false,
error: 'Cleanup API unavailable',
message: 'Could not trigger automatic cleanup'
success: true,
message: 'All orders are reduce-only (SL/TP) - preserved for risk management'
};
}
} else {

View File

@@ -0,0 +1,64 @@
import { NextResponse } from 'next/server';
import { simpleAutomation } from '@/lib/simple-automation';
export async function POST(request) {
try {
const { action, analysis, config } = await request.json();
if (action === 'generate_test_decision') {
// Set up test config
simpleAutomation.config = config || {
selectedTimeframes: ['15m', '1h', '4h'],
symbol: 'SOLUSD',
mode: 'LIVE',
enableTrading: true,
tradingAmount: 62
};
// Generate decision using the analysis
const shouldExecute = simpleAutomation.shouldExecuteTrade(analysis);
if (shouldExecute && simpleAutomation.lastDecision) {
// Add execution details for demo
simpleAutomation.lastDecision.executed = true;
simpleAutomation.lastDecision.executionDetails = {
side: analysis.recommendation?.toLowerCase().includes('buy') ? 'BUY' : 'SELL',
amount: config.tradingAmount || 62,
leverage: 12.5,
currentPrice: analysis.currentPrice || analysis.entry?.price || 186.12,
stopLoss: analysis.stopLoss,
takeProfit: analysis.takeProfit,
aiReasoning: `AI calculated 12.5x leverage based on:
• Stop loss distance: ${((Math.abs(analysis.currentPrice - analysis.stopLoss) / analysis.currentPrice) * 100).toFixed(1)}% (tight risk control)
• Account balance: $${config.tradingAmount || 62} available
• Safety buffer: 8% (liquidation protection)
• Risk assessment: MODERATE-LOW
• Position value: $${((config.tradingAmount || 62) * 12.5).toFixed(0)} (12.5x leverage)
• Maximum loss if stopped: $${(((Math.abs(analysis.currentPrice - analysis.stopLoss) / analysis.currentPrice) * (config.tradingAmount || 62) * 12.5)).toFixed(0)} (risk controlled)`,
txId: `test_decision_${Date.now()}`,
aiStopLossPercent: analysis.stopLossPercent || 'AI calculated'
};
}
return NextResponse.json({
success: true,
message: 'Test decision generated',
decision: simpleAutomation.lastDecision,
shouldExecute
});
}
return NextResponse.json({
success: false,
message: 'Unknown action'
}, { status: 400 });
} catch (error) {
console.error('Test decision error:', error);
return NextResponse.json({
success: false,
error: 'Failed to generate test decision',
message: error.message
}, { status: 500 });
}
}

View File

@@ -99,10 +99,13 @@ export async function POST() {
// Check if this order is for a market where we have no position
const hasPosition = positionMarkets.has(order.marketIndex)
// Also check if it's a reduce-only order (these should be canceled if no position)
// CRITICAL FIX: Only cancel reduce-only orders if there's NO position
// Stop Loss and Take Profit orders are reduce-only but should EXIST when we have a position
const isReduceOnly = order.reduceOnly
return !hasPosition || (isReduceOnly && !hasPosition)
// Only cancel orders that are truly orphaned (no position for that market)
// Do NOT cancel reduce-only orders when we have a position (these are SL/TP!)
return !hasPosition && !isReduceOnly
})
// Additionally, find lingering SL/TP orders when position has changed significantly

View File

@@ -54,11 +54,11 @@ export async function POST(request) {
)
}
if (leverage < 1 || leverage > 10) {
if (leverage < 1 || leverage > 100) {
return NextResponse.json(
{
success: false,
error: 'Leverage must be between 1x and 10x'
error: 'Leverage must be between 1x and 100x'
},
{ status: 400 }
)
@@ -335,7 +335,7 @@ export async function GET() {
},
status: 'Active',
features: [
'Real leveraged perpetual trading (1x-10x)',
'Real leveraged perpetual trading (1x-100x)',
'Long/Short positions with liquidation risk',
'Stop Loss & Take Profit orders',
'Real-time position tracking',

View File

@@ -197,6 +197,69 @@ export default function AutomationPageV2() {
}
}
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)
}
}
return (
<div className="space-y-6">
<div className="grid grid-cols-1 xl:grid-cols-3 gap-6">
@@ -225,6 +288,14 @@ export default function AutomationPageV2() {
>
🚨 EMERGENCY
</button>
<button
onClick={generateTestDecision}
disabled={loading}
className="px-4 py-3 bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition-colors disabled:opacity-50 font-semibold border-2 border-purple-500"
title="Generate Test AI Decision - Shows reasoning panel"
>
🧪 TEST AI
</button>
</>
) : (
<button
@@ -472,6 +543,318 @@ export default function AutomationPageV2() {
</div>
</div>
{/* AI Reasoning & Decision Analysis Panel - Always Visible */}
<div className="bg-gradient-to-br from-purple-900/30 via-blue-900/20 to-purple-900/30 p-6 rounded-lg border-2 border-purple-500/30 shadow-lg">
<div className="flex items-center justify-between mb-4">
<h3 className="text-xl font-bold text-transparent bg-clip-text bg-gradient-to-r from-purple-400 to-blue-400">
🧠 AI Trading Analysis
</h3>
<div className="flex items-center space-x-2">
<div className={`w-2 h-2 rounded-full ${status?.lastDecision ? 'bg-green-400 animate-pulse' : 'bg-gray-500'}`}></div>
<span className="text-xs text-gray-400">
{status?.lastDecision ? 'Analysis Available' : 'Waiting for Analysis'}
</span>
</div>
</div>
{status?.lastDecision ? (
<div className="space-y-6">
{/* Decision Summary */}
<div className="bg-black/20 rounded-lg p-4 border border-purple-500/20">
<div className="flex items-center justify-between mb-3">
<div className="flex items-center space-x-3">
<div className={`px-3 py-1 rounded-full text-sm font-bold ${
status.lastDecision.recommendation?.toLowerCase().includes('buy')
? 'bg-green-500/20 text-green-300 border border-green-500/30'
: status.lastDecision.recommendation?.toLowerCase().includes('sell')
? 'bg-red-500/20 text-red-300 border border-red-500/30'
: 'bg-gray-500/20 text-gray-300 border border-gray-500/30'
}`}>
{status.lastDecision.recommendation || 'HOLD'}
</div>
<div className="flex items-center space-x-2">
<span className="text-gray-400 text-sm">Confidence:</span>
<div className={`px-2 py-1 rounded text-sm font-bold ${
status.lastDecision.confidence >= 80 ? 'text-green-300' :
status.lastDecision.confidence >= 70 ? 'text-yellow-300' :
'text-red-300'
}`}>
{status.lastDecision.confidence}%
</div>
</div>
</div>
<div className="text-xs text-gray-500">
{new Date(status.lastDecision.timestamp).toLocaleString()}
</div>
</div>
{/* AI Reasoning - Prominent Display */}
<div className="mb-4">
<h4 className="text-purple-300 font-semibold mb-2 flex items-center">
<span className="mr-2">🎯</span>
Why This Decision?
</h4>
<div className="bg-gray-900/50 rounded-lg p-4 border-l-4 border-purple-500">
<p className="text-gray-200 leading-relaxed">
{status.lastDecision.reasoning}
</p>
</div>
</div>
{/* Execution Status */}
<div className="flex items-center justify-between p-3 bg-gray-800/50 rounded-lg border border-gray-700/50">
<div className="flex items-center space-x-2">
<span className={`w-3 h-3 rounded-full ${
status.lastDecision.executed ? 'bg-green-500' : 'bg-red-500'
}`}></span>
<span className="text-white font-medium">
{status.lastDecision.executed ? '✅ Trade Executed' : '❌ Not Executed'}
</span>
</div>
{!status.lastDecision.executed && status.lastDecision.executionError && (
<span className="text-red-400 text-sm">
{status.lastDecision.executionError}
</span>
)}
</div>
</div>
{/* Trade Details - If Executed */}
{status.lastDecision.executed && status.lastDecision.executionDetails && (
<div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
{/* Entry & Exit Strategy */}
<div className="bg-black/20 rounded-lg p-4 border border-blue-500/20">
<h4 className="text-blue-300 font-semibold mb-3 flex items-center">
<span className="mr-2">📈</span>
Entry & Exit Strategy
</h4>
<div className="space-y-2 text-sm">
<div className="flex justify-between">
<span className="text-gray-400">Entry Price:</span>
<span className="text-white font-mono">${status.lastDecision.executionDetails.currentPrice?.toFixed(4)}</span>
</div>
<div className="flex justify-between">
<span className="text-gray-400">Stop Loss:</span>
<span className="text-red-300 font-mono">${status.lastDecision.executionDetails.stopLoss?.toFixed(4)}</span>
</div>
<div className="flex justify-between">
<span className="text-gray-400">Take Profit:</span>
<span className="text-green-300 font-mono">${status.lastDecision.executionDetails.takeProfit?.toFixed(4)}</span>
</div>
<div className="flex justify-between">
<span className="text-gray-400">Position Size:</span>
<span className="text-white">${status.lastDecision.executionDetails.amount}</span>
</div>
</div>
</div>
{/* AI Leverage Calculation */}
<div className="bg-black/20 rounded-lg p-4 border border-yellow-500/20">
<h4 className="text-yellow-300 font-semibold mb-3 flex items-center">
<span className="mr-2"></span>
AI Leverage Decision
</h4>
<div className="space-y-2 text-sm mb-3">
<div className="flex justify-between">
<span className="text-gray-400">Leverage:</span>
<span className="text-yellow-300 font-bold text-lg">{status.lastDecision.executionDetails.leverage}x</span>
</div>
<div className="flex justify-between">
<span className="text-gray-400">Position Side:</span>
<span className={`font-semibold ${
status.lastDecision.executionDetails.side === 'BUY' ? 'text-green-300' : 'text-red-300'
}`}>
{status.lastDecision.executionDetails.side}
</span>
</div>
</div>
{status.lastDecision.executionDetails.aiReasoning && (
<div className="bg-yellow-900/20 rounded p-3 border-l-3 border-yellow-500">
<p className="text-yellow-100 text-xs leading-relaxed">
{status.lastDecision.executionDetails.aiReasoning}
</p>
</div>
)}
</div>
</div>
)}
</div>
) : (
<div className="text-center py-8">
<div className="text-6xl mb-4">🤖</div>
<h4 className="text-xl text-purple-300 font-semibold mb-2">AI Analysis Standby</h4>
<p className="text-gray-400 mb-4">
The AI will analyze market conditions and provide detailed reasoning for all trading decisions.
</p>
<div className="bg-purple-900/20 rounded-lg p-4 border border-purple-500/30">
<div className="text-purple-300 font-semibold mb-2">What you'll see when analysis starts:</div>
<ul className="text-sm text-gray-300 space-y-1 text-left max-w-md mx-auto">
<li>• <strong>Entry Strategy:</strong> Why AI chose this entry point</li>
<li>• <strong>Stop Loss Logic:</strong> Risk management reasoning</li>
<li>• <strong>Take Profit Target:</strong> Profit-taking strategy</li>
<li>• <strong>Leverage Calculation:</strong> AI's risk assessment</li>
<li> <strong>Confidence Analysis:</strong> Probability scoring</li>
</ul>
</div>
</div>
)}
</div>
{/* Legacy Last Decision Panel - Hidden when new panel is active */}
{status?.lastDecision && false && (
<div className="bg-gray-800 p-6 rounded-lg border border-gray-700">
<h3 className="text-lg font-bold text-white mb-4">🧠 Last Decision</h3>
<div className="space-y-4">
{/* Decision Header */}
<div className="flex justify-between items-center p-3 bg-gray-700 rounded-lg">
<div className="flex items-center space-x-2">
<span className={`w-3 h-3 rounded-full ${
status.lastDecision.executed ? 'bg-green-500' : 'bg-red-500'
}`}></span>
<span className="text-white font-semibold">
{status.lastDecision.executed ? '✅ EXECUTED' : '❌ NOT EXECUTED'}
</span>
</div>
<span className="text-xs text-gray-400">
{new Date(status.lastDecision.timestamp).toLocaleTimeString()}
</span>
</div>
{/* Analysis Details */}
<div className="space-y-3">
<div className="flex justify-between items-center">
<span className="text-gray-400">Recommendation:</span>
<span className={`px-2 py-1 rounded text-xs font-semibold ${
status.lastDecision.recommendation?.toLowerCase().includes('buy') ? 'bg-green-600 text-white' :
status.lastDecision.recommendation?.toLowerCase().includes('sell') ? 'bg-red-600 text-white' :
'bg-gray-600 text-gray-300'
}`}>
{status.lastDecision.recommendation || 'HOLD'}
</span>
</div>
<div className="flex justify-between items-center">
<span className="text-gray-400">Confidence:</span>
<div className="flex items-center space-x-2">
<span className={`text-sm font-semibold ${
status.lastDecision.confidence >= 80 ? 'text-green-400' :
status.lastDecision.confidence >= 70 ? 'text-yellow-400' :
'text-red-400'
}`}>
{status.lastDecision.confidence}%
</span>
<span className="text-xs text-gray-500">
(min: {status.lastDecision.minConfidenceRequired}%)
</span>
</div>
</div>
<div className="p-3 bg-gray-900 rounded-lg">
<span className="text-xs text-gray-400 block mb-1">Reasoning:</span>
<span className="text-sm text-gray-300">{status.lastDecision.reasoning}</span>
</div>
</div>
{/* Execution Details (if executed) */}
{status.lastDecision.executed && status.lastDecision.executionDetails && (
<div className="space-y-3 pt-3 border-t border-gray-700">
<h4 className="text-sm font-semibold text-cyan-400">💰 Execution Details</h4>
<div className="grid grid-cols-2 gap-3 text-sm">
<div className="flex justify-between">
<span className="text-gray-400">Side:</span>
<span className={`font-semibold ${
status.lastDecision.executionDetails.side === 'BUY' ? 'text-green-400' : 'text-red-400'
}`}>
{status.lastDecision.executionDetails.side}
</span>
</div>
<div className="flex justify-between">
<span className="text-gray-400">Amount:</span>
<span className="text-white">${status.lastDecision.executionDetails.amount}</span>
</div>
<div className="flex justify-between">
<span className="text-gray-400">Entry:</span>
<span className="text-white">${status.lastDecision.executionDetails.currentPrice?.toFixed(2)}</span>
</div>
<div className="flex justify-between">
<span className="text-gray-400">Leverage:</span>
<span className="text-white">{status.lastDecision.executionDetails.leverage}x</span>
</div>
</div>
{/* SL/TP Details */}
{(status.lastDecision.executionDetails.stopLoss || status.lastDecision.executionDetails.takeProfit) && (
<div className="p-3 bg-gray-900 rounded-lg">
<h5 className="text-xs font-semibold text-blue-400 mb-2">🛡 Risk Management</h5>
<div className="grid grid-cols-2 gap-3 text-xs">
{status.lastDecision.executionDetails.stopLoss && (
<div className="flex justify-between">
<span className="text-gray-400">Stop Loss:</span>
<span className="text-red-400 font-semibold">
${status.lastDecision.executionDetails.stopLoss.toFixed(2)}
{status.lastDecision.executionDetails.aiStopLossPercent && (
<span className="text-gray-500 ml-1">({status.lastDecision.executionDetails.aiStopLossPercent})</span>
)}
</span>
</div>
)}
{status.lastDecision.executionDetails.takeProfit && (
<div className="flex justify-between">
<span className="text-gray-400">Take Profit:</span>
<span className="text-green-400 font-semibold">
${status.lastDecision.executionDetails.takeProfit.toFixed(2)}
</span>
</div>
)}
</div>
{status.lastDecision.executionDetails.stopLoss && status.lastDecision.executionDetails.takeProfit && (
<div className="mt-2 text-xs text-gray-500">
Risk/Reward: 1:2 ratio
</div>
)}
</div>
)}
{/* AI Leverage Reasoning */}
{status.lastDecision.executionDetails.aiReasoning && (
<div className="p-3 bg-purple-900/20 rounded-lg border border-purple-700/30">
<h5 className="text-xs font-semibold text-purple-400 mb-2">🧠 AI Leverage Decision</h5>
<div className="text-xs text-gray-300 leading-relaxed">
{status.lastDecision.executionDetails.aiReasoning}
</div>
</div>
)}
{/* Transaction ID */}
{status.lastDecision.executionDetails.txId && (
<div className="text-xs">
<span className="text-gray-400">TX ID:</span>
<span className="text-blue-400 font-mono ml-2 break-all">
{status.lastDecision.executionDetails.txId.substring(0, 20)}...
</span>
</div>
)}
</div>
)}
{/* Execution Error (if failed) */}
{!status.lastDecision.executed && status.lastDecision.executionError && (
<div className="p-3 bg-red-900 border border-red-600 rounded-lg">
<h4 className="text-sm font-semibold text-red-400 mb-1"> Execution Failed</h4>
<span className="text-xs text-red-300">{status.lastDecision.executionError}</span>
</div>
)}
</div>
</div>
)}
{/* Position Monitor */}
{monitorData && (
<div className="bg-gray-800 p-6 rounded-lg border border-gray-700">

View File

@@ -0,0 +1,538 @@
'use client'
import React, { useState, useEffect } from 'react'
// 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: 'SIMULATION',
dexProvider: 'DRIFT',
symbol: 'SOLUSD',
selectedTimeframes: ['60'], // Multi-timeframe support
tradingAmount: 100,
balancePercentage: 50, // Default to 50% of available balance
})
const [status, setStatus] = useState(null)
const [balance, setBalance] = useState(null)
const [positions, setPositions] = useState([])
const [loading, setLoading] = useState(false)
useEffect(() => {
fetchStatus()
fetchBalance()
fetchPositions()
const interval = setInterval(() => {
fetchStatus()
fetchBalance()
fetchPositions()
}, 30000)
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) {
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 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')
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()
} else {
console.error('Emergency stop failed:', data.error)
}
} catch (error) {
console.error('Emergency stop error:', error)
} finally {
setLoading(false)
}
}
return (
<div className="space-y-6">
<div className="grid grid-cols-1 xl:grid-cols-3 gap-6">
{/* Configuration Panel */}
<div className="xl:col-span-2 space-y-6">
<div className="bg-gray-800 p-6 rounded-lg border border-gray-700">
{/* Header with Start/Stop Button */}
{/* Header with Start/Stop Button */}
<div className="flex items-center justify-between mb-6">
<h3 className="text-xl font-bold text-white">Configuration</h3>
<div className="flex space-x-3">
{status?.isActive ? (
<>
<button
onClick={handleStop}
disabled={loading}
className="px-6 py-3 bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors disabled:opacity-50 font-semibold"
>
{loading ? 'Stopping...' : 'STOP'}
</button>
<button
onClick={handleEmergencyStop}
disabled={loading}
className="px-4 py-3 bg-red-800 text-white rounded-lg hover:bg-red-900 transition-colors disabled:opacity-50 font-semibold border-2 border-red-600"
title="Emergency Stop - Closes all positions immediately"
>
🚨 EMERGENCY
</button>
</>
) : (
<button
onClick={handleStart}
disabled={loading}
className="px-6 py-3 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors disabled:opacity-50 font-semibold"
>
{loading ? 'Starting...' : status?.rateLimitHit ? 'RESTART' : 'START'}
</button>
)}
</div>
</div>
{/* Trading Mode - Side by Side Radio Buttons with Logos */}
<div className="mb-6">
<label className="block text-sm font-bold text-blue-400 mb-3">Trading Mode</label>
<div className="grid grid-cols-2 gap-4">
<label className="flex items-center space-x-3 cursor-pointer p-4 rounded-lg border border-gray-600 hover:border-blue-500 transition-colors">
<input
type="radio"
className="w-5 h-5 text-blue-600"
name="mode"
checked={config.mode === 'SIMULATION'}
onChange={() => setConfig({...config, mode: 'SIMULATION'})}
disabled={status?.isActive}
/>
<div className="flex items-center space-x-2">
<span className="text-2xl">📊</span>
<span className="text-white font-medium">Paper Trading</span>
</div>
</label>
<label className="flex items-center space-x-3 cursor-pointer p-4 rounded-lg border border-gray-600 hover:border-green-500 transition-colors">
<input
type="radio"
className="w-5 h-5 text-green-600"
name="mode"
checked={config.mode === 'LIVE'}
onChange={() => setConfig({...config, mode: 'LIVE'})}
disabled={status?.isActive}
/>
<div className="flex items-center space-x-2">
<span className="text-2xl">💰</span>
<span className="text-white font-semibold">Live Trading</span>
</div>
</label>
</div>
</div>
{/* Symbol and Position Size */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6">
<div>
<label className="block text-sm font-medium text-gray-300 mb-2">Symbol</label>
<select
className="w-full p-3 bg-gray-700 border border-gray-600 rounded-lg text-white focus:border-blue-500"
value={config.symbol}
onChange={(e) => setConfig({...config, symbol: e.target.value})}
disabled={status?.isActive}
>
<option value="SOLUSD">SOL/USD</option>
<option value="BTCUSD">BTC/USD</option>
<option value="ETHUSD">ETH/USD</option>
<option value="APTUSD">APT/USD</option>
<option value="AVAXUSD">AVAX/USD</option>
<option value="DOGEUSD">DOGE/USD</option>
</select>
</div>
<div>
<label className="block text-sm font-medium text-gray-300 mb-2">
Balance to Use: {config.balancePercentage}%
{balance && ` ($${(parseFloat(balance.availableBalance) * config.balancePercentage / 100).toFixed(2)})`}
</label>
<input
type="range"
className="w-full h-2 bg-gray-700 rounded-lg appearance-none cursor-pointer"
style={{
background: `linear-gradient(to right, #3b82f6 0%, #3b82f6 ${config.balancePercentage}%, #374151 ${config.balancePercentage}%, #374151 100%)`
}}
min="10"
max="100"
step="5"
value={config.balancePercentage}
onChange={(e) => {
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}
/>
<div className="flex justify-between text-xs text-gray-400 mt-1">
<span>10%</span>
<span>50%</span>
<span>100%</span>
</div>
</div>
</div>
{/* MULTI-TIMEFRAME SELECTION */}
<div className="mb-6">
<label className="block text-sm font-medium text-gray-300 mb-2">
Analysis Timeframes
<span className="text-xs text-cyan-400 ml-2">({config.selectedTimeframes.length} selected)</span>
{config.selectedTimeframes.length === 0 && (
<span className="text-xs text-red-400 ml-2">⚠️ At least one timeframe required</span>
)}
</label>
{/* Timeframe Checkboxes */}
<div className="grid grid-cols-4 gap-2 mb-3">
{timeframes.map(tf => (
<label key={tf.value} className="group relative cursor-pointer">
<input
type="checkbox"
checked={config.selectedTimeframes.includes(tf.value)}
onChange={() => toggleTimeframe(tf.value)}
disabled={status?.isActive}
className="sr-only"
/>
<div className={`flex items-center justify-center p-2 rounded-lg border transition-all text-xs font-medium ${
config.selectedTimeframes.includes(tf.value)
? 'border-cyan-500 bg-cyan-500/10 text-cyan-300 shadow-lg shadow-cyan-500/20'
: status?.isActive
? 'border-gray-700 bg-gray-800/30 text-gray-500 cursor-not-allowed'
: 'border-gray-700 bg-gray-800/30 text-gray-400 hover:border-gray-600 hover:bg-gray-800/50 hover:text-gray-300'
}`}>
{tf.label}
{config.selectedTimeframes.includes(tf.value) && (
<div className="absolute top-0.5 right-0.5 w-1.5 h-1.5 bg-cyan-400 rounded-full"></div>
)}
</div>
</label>
))}
</div>
{/* Selected Timeframes Display */}
{config.selectedTimeframes.length > 0 && (
<div className="p-2 bg-gray-800/30 rounded-lg mb-3">
<div className="text-xs text-gray-400">
Selected: <span className="text-cyan-400">
{config.selectedTimeframes.map(tf => timeframes.find(t => t.value === tf)?.label || tf).filter(Boolean).join(', ')}
</span>
</div>
<div className="text-xs text-gray-500 mt-1">
💡 Multiple timeframes provide more robust analysis
</div>
</div>
)}
{/* Quick Selection Buttons - Made Bigger */}
<div className="grid grid-cols-3 gap-3">
<button
type="button"
onClick={() => setConfig({...config, selectedTimeframes: ['5', '15', '30']})}
disabled={status?.isActive}
className="py-3 px-4 rounded-lg text-sm font-medium bg-green-600/20 text-green-300 hover:bg-green-600/30 transition-all disabled:opacity-50 disabled:cursor-not-allowed border border-green-600/30 hover:border-green-600/50"
>
<div className="text-lg mb-1">📈</div>
<div>Scalping</div>
<div className="text-xs opacity-75">5m, 15m, 30m</div>
</button>
<button
type="button"
onClick={() => setConfig({...config, selectedTimeframes: ['60', '120']})}
disabled={status?.isActive}
className="py-3 px-4 rounded-lg text-sm font-medium bg-blue-600/20 text-blue-300 hover:bg-blue-600/30 transition-all disabled:opacity-50 disabled:cursor-not-allowed border border-blue-600/30 hover:border-blue-600/50"
>
<div className="text-lg mb-1">⚡</div>
<div>Day Trading</div>
<div className="text-xs opacity-75">1h, 2h</div>
</button>
<button
type="button"
onClick={() => setConfig({...config, selectedTimeframes: ['240', 'D']})}
disabled={status?.isActive}
className="py-3 px-4 rounded-lg text-sm font-medium bg-purple-600/20 text-purple-300 hover:bg-purple-600/30 transition-all disabled:opacity-50 disabled:cursor-not-allowed border border-purple-600/30 hover:border-purple-600/50"
>
<div className="text-lg mb-1">🎯</div>
<div>Swing Trading</div>
<div className="text-xs opacity-75">4h, 1d</div>
</button>
</div>
</div>
</div>
</div>
{/* Status and Info Panel */}
<div className="space-y-6">
{/* Status */}
<div className="bg-gray-800 p-6 rounded-lg border border-gray-700">
<h3 className="text-lg font-bold text-white mb-4">Bot Status</h3>
<div className="space-y-3">
<div className="flex justify-between items-center">
<span className="text-gray-400">Status:</span>
<span className={`px-2 py-1 rounded text-xs font-semibold ${
status?.isActive ? 'bg-green-600 text-white' : 'bg-gray-600 text-gray-300'
}`}>
{status?.isActive ? 'RUNNING' : 'STOPPED'}
</span>
</div>
{status?.isActive && (
<>
<div className="flex justify-between items-center">
<span className="text-gray-400">Symbol:</span>
<span className="text-white font-medium">{status.symbol}</span>
</div>
<div className="flex justify-between items-center">
<span className="text-gray-400">Mode:</span>
<span className={`px-2 py-1 rounded text-xs font-semibold ${
status.mode === 'LIVE' ? 'bg-red-600 text-white' : 'bg-blue-600 text-white'
}`}>
{status.mode}
</span>
</div>
<div className="flex justify-between items-center">
<span className="text-gray-400">Timeframes:</span>
<span className="text-cyan-400 text-xs">
{status.timeframes?.map(tf => timeframes.find(t => t.value === tf)?.label || tf).join(', ')}
</span>
</div>
</>
)}
{/* Rate Limit Notification */}
{status?.rateLimitHit && (
<div className="mt-4 p-3 bg-red-900 border border-red-600 rounded-lg">
<div className="flex items-center space-x-2">
<span className="text-red-400 font-semibold">⚠️ Rate Limit Reached</span>
</div>
{status.rateLimitMessage && (
<p className="text-red-300 text-sm mt-1">{status.rateLimitMessage}</p>
)}
<p className="text-red-200 text-xs mt-2">
Automation stopped automatically. Please recharge your OpenAI account to continue.
</p>
</div>
)}
</div>
</div>
{/* Balance */}
{balance && (
<div className="bg-gray-800 p-6 rounded-lg border border-gray-700">
<h3 className="text-lg font-bold text-white mb-4">Account Balance</h3>
<div className="space-y-3">
<div className="flex justify-between items-center">
<span className="text-gray-400">Available:</span>
<span className="text-green-400 font-semibold">${parseFloat(balance.availableBalance).toFixed(2)}</span>
</div>
<div className="flex justify-between items-center">
<span className="text-gray-400">Total:</span>
<span className="text-white font-medium">${parseFloat(balance.totalCollateral).toFixed(2)}</span>
</div>
<div className="flex justify-between items-center">
<span className="text-gray-400">Positions:</span>
<span className="text-yellow-400">{balance.positions || 0}</span>
</div>
</div>
</div>
)}
{/* Positions */}
{positions.length > 0 && (
<div className="bg-gray-800 p-6 rounded-lg border border-gray-700">
<h3 className="text-lg font-bold text-white mb-4">Open Positions</h3>
<div className="space-y-3">
{positions.map((position, index) => (
<div key={index} className="p-4 bg-gray-700 rounded-lg border border-gray-600">
<div className="flex justify-between items-center mb-2">
<span className="text-white font-semibold">{position.symbol}</span>
<span className={`px-2 py-1 rounded text-xs font-semibold ${
position.side === 'LONG' ? 'bg-green-600 text-white' : 'bg-red-600 text-white'
}`}>
{position.side}
</span>
</div>
<div className="grid grid-cols-2 gap-2 text-sm">
<div className="flex justify-between">
<span className="text-gray-400">Size:</span>
<span className="text-white">${position.size}</span>
</div>
{position.entryPrice && (
<div className="flex justify-between">
<span className="text-gray-400">Entry:</span>
<span className="text-white">${position.entryPrice}</span>
</div>
)}
{position.markPrice && (
<div className="flex justify-between">
<span className="text-gray-400">Mark:</span>
<span className="text-white">${position.markPrice}</span>
</div>
)}
{position.pnl !== undefined && (
<div className="flex justify-between">
<span className="text-gray-400">PnL:</span>
<span className={`font-semibold ${
position.pnl >= 0 ? 'text-green-400' : 'text-red-400'
}`}>
${position.pnl >= 0 ? '+' : ''}${position.pnl}
</span>
</div>
)}
</div>
</div>
))}
</div>
</div>
)}
</div>
</div>
</div>
)
}

View File

@@ -1,16 +1,343 @@
import CompleteLearningDashboard from '../components/CompleteLearningDashboard'
'use client'
import React, { useState, useEffect } from 'react'
interface LearningData {
totalAnalyses: number
totalTrades: number
avgAccuracy: number
winRate: number
confidenceLevel: number
phase: string
phaseDescription: string
strengths: string[]
improvements: string[]
nextMilestone: string
recommendation: string
daysActive: number
}
interface LearningInsights {
totalAnalyses: number
avgAccuracy: number
bestTimeframe: string
worstTimeframe: string
recommendations: string[]
}
/**
* Complete AI Learning Dashboard Page
*
* Shows both stop loss decision learning AND risk/reward optimization
*/
export default function CompleteLearningPage() {
return (
<div className="min-h-screen bg-gray-950">
<div className="container mx-auto px-4 py-8">
<CompleteLearningDashboard />
const [learningData, setLearningData] = useState<LearningData | null>(null)
const [learningInsights, setLearningInsights] = useState<LearningInsights | null>(null)
const [loading, setLoading] = useState(true)
const [lastRefresh, setLastRefresh] = useState<Date>(new Date())
// Auto-refresh every 30 seconds
useEffect(() => {
fetchLearningData()
const interval = setInterval(() => {
fetchLearningData()
}, 30000)
return () => clearInterval(interval)
}, [])
const fetchLearningData = async () => {
try {
setLoading(true)
// Fetch AI learning status
const [statusResponse, insightsResponse] = await Promise.all([
fetch('/api/ai-learning-status'),
fetch('/api/automation/learning-insights')
])
if (statusResponse.ok) {
const statusData = await statusResponse.json()
if (statusData.success) {
setLearningData(statusData.data)
}
}
if (insightsResponse.ok) {
const insightsData = await insightsResponse.json()
if (insightsData.success) {
setLearningInsights(insightsData.insights)
}
}
setLastRefresh(new Date())
} catch (error) {
console.error('Failed to fetch learning data:', error)
} finally {
setLoading(false)
}
}
const getPhaseColor = (phase: string) => {
switch (phase) {
case 'EXPERT': return 'text-green-400'
case 'ADVANCED': return 'text-blue-400'
case 'PATTERN_RECOGNITION': return 'text-yellow-400'
default: return 'text-gray-400'
}
}
const getPhaseIcon = (phase: string) => {
switch (phase) {
case 'EXPERT': return '🚀'
case 'ADVANCED': return '🌳'
case 'PATTERN_RECOGNITION': return '🌿'
default: return '🌱'
}
}
if (loading && !learningData) {
return (
<div className="min-h-screen bg-gradient-to-br from-gray-900 via-gray-800 to-gray-900 p-6">
<div className="max-w-6xl mx-auto">
<div className="flex items-center justify-center py-20">
<div className="spinner border-blue-500"></div>
<span className="ml-3 text-white">Loading comprehensive learning data...</span>
</div>
</div>
</div>
)
}
return (
<div className="min-h-screen bg-gradient-to-br from-gray-900 via-gray-800 to-gray-900 p-6">
<div className="max-w-6xl mx-auto space-y-6">
{/* Header */}
<div className="text-center mb-8">
<h1 className="text-4xl font-bold text-white mb-4">🧠 Complete AI Learning Status</h1>
<p className="text-gray-300 text-lg">Comprehensive overview of your AI's learning progress and capabilities</p>
<div className="text-sm text-gray-400 mt-2">
Last updated: {lastRefresh.toLocaleTimeString()}
<span className="ml-3 text-blue-400">⟳ Auto-refreshes every 30 seconds</span>
</div>
</div>
{/* Quick Stats */}
<div className="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
<div className="bg-gray-800/50 backdrop-blur-sm border border-gray-700 rounded-lg p-6 text-center">
<div className="text-3xl font-bold text-blue-400">{learningData?.totalAnalyses || 0}</div>
<div className="text-gray-300 text-sm">Total Analyses</div>
</div>
<div className="bg-gray-800/50 backdrop-blur-sm border border-gray-700 rounded-lg p-6 text-center">
<div className="text-3xl font-bold text-green-400">{learningData?.totalTrades || 0}</div>
<div className="text-gray-300 text-sm">Total Trades</div>
</div>
<div className="bg-gray-800/50 backdrop-blur-sm border border-gray-700 rounded-lg p-6 text-center">
<div className="text-3xl font-bold text-purple-400">{((learningData?.avgAccuracy || 0) * 100).toFixed(1)}%</div>
<div className="text-gray-300 text-sm">Avg Accuracy</div>
</div>
<div className="bg-gray-800/50 backdrop-blur-sm border border-gray-700 rounded-lg p-6 text-center">
<div className="text-3xl font-bold text-yellow-400">{((learningData?.winRate || 0) * 100).toFixed(1)}%</div>
<div className="text-gray-300 text-sm">Win Rate</div>
</div>
</div>
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
{/* AI Learning Phase */}
{learningData && (
<div className="bg-gray-800/50 backdrop-blur-sm border border-gray-700 rounded-lg p-6">
<h2 className="text-2xl font-bold text-white mb-6 flex items-center">
<span className="mr-3">{getPhaseIcon(learningData.phase)}</span>
AI Learning Phase
</h2>
<div className="space-y-6">
{/* Current Phase */}
<div className="text-center">
<div className={`text-3xl font-bold ${getPhaseColor(learningData.phase)} mb-2`}>
{learningData.phase}
</div>
<div className="text-white text-lg mb-4">{learningData.phaseDescription}</div>
<div className="text-gray-300 text-sm">Active for {learningData.daysActive} days</div>
</div>
{/* Performance Metrics */}
<div className="grid grid-cols-2 gap-4">
<div className="text-center bg-gray-700/30 rounded-lg p-3">
<div className="text-xl font-bold text-white">{learningData.confidenceLevel.toFixed(1)}%</div>
<div className="text-xs text-gray-400">Confidence Level</div>
</div>
<div className="text-center bg-gray-700/30 rounded-lg p-3">
<div className="text-xl font-bold text-white">{((learningData.avgAccuracy || 0) * 100).toFixed(1)}%</div>
<div className="text-xs text-gray-400">Accuracy</div>
</div>
</div>
{/* Next Milestone */}
<div className="bg-blue-900/20 border border-blue-600/30 rounded-lg p-4">
<div className="text-sm font-medium text-blue-400 mb-2">Next Milestone</div>
<div className="text-white">{learningData.nextMilestone}</div>
</div>
{/* AI Recommendation */}
<div className="bg-green-900/20 border border-green-600/30 rounded-lg p-4">
<div className="text-sm font-medium text-green-400 mb-2">AI Recommendation</div>
<div className="text-white text-sm">{learningData.recommendation}</div>
</div>
</div>
</div>
)}
{/* Strengths & Improvements */}
{learningData && (
<div className="bg-gray-800/50 backdrop-blur-sm border border-gray-700 rounded-lg p-6">
<h2 className="text-2xl font-bold text-white mb-6">📈 Performance Analysis</h2>
<div className="grid grid-cols-1 gap-6">
{/* Strengths */}
<div>
<h3 className="text-green-400 font-semibold mb-3 flex items-center">
<span className="mr-2">✅</span>
Current Strengths
</h3>
<ul className="space-y-2">
{learningData.strengths.map((strength, idx) => (
<li key={idx} className="text-sm text-gray-300 flex items-start">
<span className="text-green-400 mr-2 mt-0.5">✓</span>
{strength}
</li>
))}
</ul>
</div>
{/* Improvements */}
<div>
<h3 className="text-yellow-400 font-semibold mb-3 flex items-center">
<span className="mr-2">🎯</span>
Areas for Improvement
</h3>
<ul className="space-y-2">
{learningData.improvements.map((improvement, idx) => (
<li key={idx} className="text-sm text-gray-300 flex items-start">
<span className="text-yellow-400 mr-2 mt-0.5">•</span>
{improvement}
</li>
))}
</ul>
</div>
</div>
</div>
)}
{/* Learning Insights */}
{learningInsights && (
<div className="bg-gray-800/50 backdrop-blur-sm border border-gray-700 rounded-lg p-6">
<h2 className="text-2xl font-bold text-white mb-6">🎯 Learning Insights</h2>
<div className="space-y-4">
<div className="flex justify-between items-center">
<span className="text-gray-300">Total Analyses:</span>
<span className="text-white font-semibold">{learningInsights.totalAnalyses}</span>
</div>
<div className="flex justify-between items-center">
<span className="text-gray-300">Avg Accuracy:</span>
<span className="text-white font-semibold">{(learningInsights.avgAccuracy * 100).toFixed(1)}%</span>
</div>
<div className="flex justify-between items-center">
<span className="text-gray-300">Best Timeframe:</span>
<span className="text-green-400 font-semibold">{learningInsights.bestTimeframe}</span>
</div>
<div className="flex justify-between items-center">
<span className="text-gray-300">Worst Timeframe:</span>
<span className="text-red-400 font-semibold">{learningInsights.worstTimeframe}</span>
</div>
{learningInsights.recommendations.length > 0 && (
<div className="mt-6">
<h4 className="text-lg font-semibold text-white mb-3">💡 AI Recommendations</h4>
<ul className="space-y-2">
{learningInsights.recommendations.map((rec, idx) => (
<li key={idx} className="text-sm text-gray-300 flex items-start">
<span className="text-blue-400 mr-2 mt-0.5">💡</span>
{rec}
</li>
))}
</ul>
</div>
)}
</div>
</div>
)}
{/* Refresh Control */}
<div className="bg-gray-800/50 backdrop-blur-sm border border-gray-700 rounded-lg p-6">
<h2 className="text-2xl font-bold text-white mb-6">🔄 Data Controls</h2>
<div className="space-y-4">
<div className="flex items-center justify-between">
<span className="text-gray-300">Auto Refresh:</span>
<span className="text-green-400 font-semibold">Every 30 seconds</span>
</div>
<div className="flex items-center justify-between">
<span className="text-gray-300">Last Updated:</span>
<span className="text-blue-400 font-semibold">{lastRefresh.toLocaleTimeString()}</span>
</div>
<button
onClick={fetchLearningData}
disabled={loading}
className="w-full bg-blue-600 hover:bg-blue-700 disabled:bg-gray-600 text-white font-semibold py-3 px-4 rounded-lg transition-colors duration-200 flex items-center justify-center"
>
{loading ? (
<>
<div className="spinner border-white mr-2"></div>
Refreshing...
</>
) : (
<>
<span className="mr-2">🔄</span>
Refresh Now
</>
)}
</button>
<div className="text-xs text-gray-400 text-center mt-2">
Data refreshes automatically to show the latest AI learning progress
</div>
</div>
</div>
</div>
{/* Status Messages */}
{!learningData && !loading && (
<div className="bg-yellow-900/20 border border-yellow-600/30 rounded-lg p-4 text-center">
<div className="text-yellow-400 font-semibold mb-2">⚠️ No Learning Data Available</div>
<div className="text-gray-300 text-sm">
The AI hasn't started learning yet. Run some analyses to see learning progress here.
</div>
</div>
)}
{/* Footer Info */}
<div className="text-center text-gray-400 text-sm border-t border-gray-700 pt-6">
<p>This page automatically refreshes every 30 seconds to show real-time AI learning progress.</p>
<p className="mt-1">Navigate to <span className="text-blue-400">/automation</span> to start the AI learning process.</p>
</div>
</div>
<style jsx>{`
.spinner {
width: 16px;
height: 16px;
border: 2px solid transparent;
border-top: 2px solid currentColor;
border-radius: 50%;
animation: spin 1s linear infinite;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
`}</style>
</div>
)
}