'use client';
import { useState, useEffect } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { RefreshCw, TrendingUp, TrendingDown, Activity, Brain, DollarSign, Target } from 'lucide-react';
export default function AILearningDashboard() {
const [analytics, setAnalytics] = useState(null);
const [loading, setLoading] = useState(true);
const [refreshing, setRefreshing] = useState(false);
const [error, setError] = useState(null);
const fetchAnalytics = async () => {
try {
const response = await fetch('/api/ai-analytics');
if (!response.ok) throw new Error('Failed to fetch analytics');
const data = await response.json();
setAnalytics(data);
setError(null);
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
setRefreshing(false);
}
};
const handleRefresh = async () => {
setRefreshing(true);
await fetchAnalytics();
};
useEffect(() => {
fetchAnalytics();
const interval = setInterval(fetchAnalytics, 30000);
return () => clearInterval(interval);
}, []);
if (loading) {
return (
);
}
if (error) {
return (
Error loading analytics: {error}
);
}
if (!analytics) return null;
const { overview, improvements, pnl, currentPosition, realTimeMetrics, learningProof } = analytics;
const getTrendIcon = (trend) => {
switch (trend) {
case 'IMPROVING': return ;
case 'DECLINING': return ;
default: return ;
}
};
const getTrendColor = (trend) => {
switch (trend) {
case 'IMPROVING': return 'bg-green-100 text-green-800';
case 'DECLINING': return 'bg-red-100 text-red-800';
default: return 'bg-yellow-100 text-yellow-800';
}
};
const formatCurrency = (value) => {
return new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
minimumFractionDigits: 2,
maximumFractionDigits: 4
}).format(value);
};
const formatPercentage = (value) => {
return `${value > 0 ? '+' : ''}${value.toFixed(2)}%`;
};
return (
{/* Header */}
AI Learning Analytics
Proof of AI improvement and trading performance since {new Date(analytics.period.start).toLocaleDateString()}
{/* Overview Stats */}
Learning Records
{overview.totalLearningRecords.toLocaleString()}
{realTimeMetrics.learningRecordsPerDay}/day average
AI Trades
{overview.totalTrades}
{realTimeMetrics.tradesPerDay}/day average
Active Sessions
{overview.activeSessions}
of {overview.totalSessions} total sessions
Days Active
{realTimeMetrics.daysSinceAIStarted}
Since AI trading began
{/* Learning Improvements */}
AI Learning Improvements
Statistical proof of AI learning effectiveness over time
Confidence Trend
{getTrendIcon(improvements.trend)}
{improvements.trend}
{formatPercentage(improvements.confidenceImprovement)}
Early: {improvements.earlyPeriod.avgConfidence}% → Recent: {improvements.recentPeriod.avgConfidence}%
Sample Size
{learningProof.isStatisticallySignificant ? 'Significant' : 'Building'}
{learningProof.sampleSize}
{improvements.earlyPeriod.samples} early + {improvements.recentPeriod.samples} recent samples
{learningProof.isStatisticallySignificant && (
Learning Status:
{learningProof.hasImprovement ?
'AI is demonstrably improving over time!' :
'AI is learning and adapting to market conditions'}
)}
{/* PnL Analysis */}
Total PnL Since AI Started
Complete trading performance analysis since AI automation began
{formatCurrency(pnl.totalPnL)}
Total PnL
{formatPercentage(pnl.totalPnLPercent)} overall
{pnl.winRate.toFixed(1)}%
Win Rate
{pnl.winningTrades}W / {pnl.losingTrades}L / {pnl.breakEvenTrades}BE
{formatCurrency(pnl.avgTradeSize)}
Avg Trade Size
{pnl.totalTrades} total trades
{pnl.totalTrades > 0 && (
Average Win
{formatCurrency(pnl.avgWin)}
Average Loss
{formatCurrency(pnl.avgLoss)}
)}
{/* Current Position */}
{currentPosition && currentPosition.hasPosition && (
Current AI Position
Live position being managed by AI risk system
Symbol
{currentPosition.symbol}
{currentPosition.side.toUpperCase()}
Size
{currentPosition.size}
Unrealized PnL
= 0 ? 'text-green-600' : 'text-red-600'}`}>
{formatCurrency(currentPosition.unrealizedPnl)}
Risk Level
{currentPosition.riskLevel}
{currentPosition.distanceFromStopLoss}% from SL
)}
{/* Footer */}
Last updated: {new Date(analytics.generated).toLocaleString()}
• Auto-refreshes every 30 seconds
);
}