'use client' import { useState, useEffect } from 'react' // Available timeframes for analysis (matching automation-v2 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' }, ] // Intelligent delay mapping based on timeframe (optimize ChatGPT budget) const ANALYSIS_DELAYS = { '5': 5 * 60 * 1000, // 5m chart: analyze every 5 minutes '15': 15 * 60 * 1000, // 15m chart: analyze every 15 minutes '30': 30 * 60 * 1000, // 30m chart: analyze every 30 minutes '60': 60 * 60 * 1000, // 1h chart: analyze every 1 hour '120': 2 * 60 * 60 * 1000, // 2h chart: analyze every 2 hours '240': 4 * 60 * 60 * 1000, // 4h chart: analyze every 4 hours 'D': 24 * 60 * 60 * 1000, // 1d chart: analyze once per day } export default function SafePaperTradingPage() { const [symbol, setSymbol] = useState('SOLUSD') const [selectedTimeframes, setSelectedTimeframes] = useState(['60']) // Default to 1h const [loading, setLoading] = useState(false) const [currentAnalysis, setCurrentAnalysis] = useState(null) const [paperBalance, setPaperBalance] = useState(1000) const [paperTrades, setPaperTrades] = useState([]) const [analysisHistory, setAnalysisHistory] = useState([]) const [error, setError] = useState(null) const [learningInsights, setLearningInsights] = useState(null) const [showDetailedAnalysis, setShowDetailedAnalysis] = useState(false) const [continuousLearning, setContinuousLearning] = useState(false) const [autoExecuteTrades, setAutoExecuteTrades] = useState(false) // New: Auto-execute trades based on AI recommendations const [learningInterval, setLearningInterval] = useState(null) const [lastAnalysisTime, setLastAnalysisTime] = useState(null) const [nextAnalysisTime, setNextAnalysisTime] = useState(null) const [countdownTimer, setCountdownTimer] = useState(null) const [timeRemaining, setTimeRemaining] = useState(0) // Load persisted analysis data on component mount useEffect(() => { const loadPersistedData = () => { try { const savedAnalysis = localStorage.getItem('safePaperTrading_currentAnalysis') const savedTrades = localStorage.getItem('safePaperTrading_paperTrades') const savedBalance = localStorage.getItem('safePaperTrading_paperBalance') const savedHistory = localStorage.getItem('safePaperTrading_analysisHistory') const savedLearningInsights = localStorage.getItem('safePaperTrading_learningInsights') const savedContinuousLearning = localStorage.getItem('safePaperTrading_continuousLearning') const savedAutoExecute = localStorage.getItem('safePaperTrading_autoExecute') if (savedAnalysis) { const parsedAnalysis = JSON.parse(savedAnalysis) // Check if the saved analysis is stale (older than 2 hours) const analysisAge = Date.now() - new Date(parsedAnalysis.timestamp).getTime() const twoHours = 2 * 60 * 60 * 1000 if (analysisAge > twoHours) { console.log('๐ Found stale analysis data (>2 hours old), will fetch fresh data') localStorage.removeItem('safePaperTrading_currentAnalysis') // Trigger fresh analysis after component loads setTimeout(() => { console.log('๐ Fetching fresh analysis to replace stale data') runSafeAnalysis(false) }, 5000) } else { setCurrentAnalysis(parsedAnalysis) console.log('๐ Restored recent analysis from localStorage') } } else { // No saved analysis, fetch fresh data setTimeout(() => { console.log('๐ No saved analysis found, fetching fresh data') runSafeAnalysis(false) }, 3000) } if (savedTrades) { const parsedTrades = JSON.parse(savedTrades) setPaperTrades(parsedTrades) console.log(`๐ Restored ${parsedTrades.length} paper trades`) } if (savedBalance) { const parsedBalance = parseFloat(savedBalance) setPaperBalance(parsedBalance) console.log(`๐ Restored paper balance: $${parsedBalance}`) } if (savedHistory) { const parsedHistory = JSON.parse(savedHistory) setAnalysisHistory(parsedHistory) console.log(`๐ Restored ${parsedHistory.length} analysis history entries`) } if (savedLearningInsights) { const parsedInsights = JSON.parse(savedLearningInsights) setLearningInsights(parsedInsights) console.log('๐ Restored learning insights from localStorage') } if (savedContinuousLearning === 'true') { console.log('๐ Found continuous learning was active - restarting...') setContinuousLearning(true) // Restart continuous learning after a short delay to ensure component is ready setTimeout(() => { console.log('๏ฟฝ Restarting continuous learning from localStorage') startContinuousLearning() }, 3000) // Increased delay to ensure everything is loaded } } catch (error) { console.error('โ ๏ธ Error loading persisted data:', error) // Clear corrupted data localStorage.removeItem('safePaperTrading_currentAnalysis') localStorage.removeItem('safePaperTrading_paperTrades') localStorage.removeItem('safePaperTrading_paperBalance') localStorage.removeItem('safePaperTrading_analysisHistory') localStorage.removeItem('safePaperTrading_learningInsights') localStorage.removeItem('safePaperTrading_continuousLearning') } } loadPersistedData() // Load auto-execute setting try { const savedAutoExecute = localStorage.getItem('safePaperTrading_autoExecute') if (savedAutoExecute === 'true') { console.log('๐ Found auto-execute was enabled - restoring...') setAutoExecuteTrades(true) } } catch (error) { console.error('โ ๏ธ Error loading auto-execute setting:', error) } // Check if continuous learning should be active const checkContinuousLearningState = () => { try { const savedContinuousLearning = localStorage.getItem('safePaperTrading_continuousLearning') console.log('๐ Checking continuous learning state:', savedContinuousLearning) if (savedContinuousLearning === 'true') { console.log('๐ Restoring continuous learning state...') setContinuousLearning(true) setTimeout(() => { console.log('๐ Starting continuous learning from restored state') startContinuousLearning() }, 2000) } } catch (error) { console.error('โ ๏ธ Error checking continuous learning state:', error) } } // Check state after a short delay to ensure everything is loaded setTimeout(checkContinuousLearningState, 1000) }, []) // Persist analysis data whenever it changes useEffect(() => { if (currentAnalysis) { try { localStorage.setItem('safePaperTrading_currentAnalysis', JSON.stringify(currentAnalysis)) console.log('๐พ Persisted current analysis to localStorage') } catch (error) { console.error('โ ๏ธ Error persisting current analysis:', error) } } }, [currentAnalysis]) useEffect(() => { if (paperTrades.length >= 0) { // Always persist, even empty array try { localStorage.setItem('safePaperTrading_paperTrades', JSON.stringify(paperTrades)) console.log(`๐พ Persisted ${paperTrades.length} paper trades`) } catch (error) { console.error('โ ๏ธ Error persisting paper trades:', error) } } }, [paperTrades]) useEffect(() => { try { localStorage.setItem('safePaperTrading_paperBalance', paperBalance.toString()) console.log(`๐พ Persisted paper balance: $${paperBalance}`) } catch (error) { console.error('โ ๏ธ Error persisting paper balance:', error) } }, [paperBalance]) useEffect(() => { if (learningInsights) { try { localStorage.setItem('safePaperTrading_learningInsights', JSON.stringify(learningInsights)) console.log('๐พ Persisted learning insights to localStorage') } catch (error) { console.error('โ ๏ธ Error persisting learning insights:', error) } } }, [learningInsights]) // Persist continuous learning state useEffect(() => { try { localStorage.setItem('safePaperTrading_continuousLearning', continuousLearning.toString()) console.log(`๐พ Persisted continuous learning state: ${continuousLearning}`) } catch (error) { console.error('โ ๏ธ Error persisting continuous learning state:', error) } }, [continuousLearning]) // Persist auto-execute setting useEffect(() => { try { localStorage.setItem('safePaperTrading_autoExecute', autoExecuteTrades.toString()) console.log(`๐พ Persisted auto-execute setting: ${autoExecuteTrades}`) } catch (error) { console.error('โ ๏ธ Error persisting auto-execute setting:', error) } }, [autoExecuteTrades]) // Live countdown timer for continuous learning useEffect(() => { if (continuousLearning && nextAnalysisTime) { // Clear any existing countdown timer if (countdownTimer) { clearInterval(countdownTimer) } // Create new countdown timer that updates every second const countdown = setInterval(() => { const remaining = nextAnalysisTime - Date.now() if (remaining <= 0) { setTimeRemaining(0) } else { setTimeRemaining(remaining) } }, 1000) setCountdownTimer(countdown) // Initial calculation const remaining = nextAnalysisTime - Date.now() setTimeRemaining(remaining > 0 ? remaining : 0) return () => { if (countdown) { clearInterval(countdown) } } } else { // Clear countdown when not in continuous learning if (countdownTimer) { clearInterval(countdownTimer) setCountdownTimer(null) } setTimeRemaining(0) } }, [continuousLearning, nextAnalysisTime]) // Clean up countdown on unmount useEffect(() => { return () => { if (countdownTimer) { clearInterval(countdownTimer) } } }, []) // Health check for continuous learning - ensure it's actually running useEffect(() => { if (continuousLearning) { const healthCheck = setInterval(() => { if (!learningInterval) { console.warn('โ ๏ธ HEALTH CHECK: Continuous learning is ON but interval is missing - restarting...') restartContinuousLearning() } else { console.log('โ HEALTH CHECK: Continuous learning interval is active') } }, 5 * 60 * 1000) // Check every 5 minutes return () => clearInterval(healthCheck) } }, [continuousLearning, learningInterval]) // SAFETY: Only these timeframes allowed in paper trading const safeTimeframes = timeframes.map(tf => ({ ...tf, riskLevel: tf.value === '5' || tf.value === '15' ? 'HIGH' : tf.value === '30' || tf.value === '60' ? 'MEDIUM' : 'LOW' })) const settings = { riskPerTrade: 1.0, paperMode: true, // ALWAYS true - cannot be changed isolatedMode: true // ALWAYS true - completely isolated } const toggleTimeframe = (timeframe) => { setSelectedTimeframes(prev => prev.includes(timeframe) ? prev.filter(tf => tf !== timeframe) : [...prev, timeframe] ) } const calculateOptimalDelay = () => { if (selectedTimeframes.length === 0) return 60 * 60 * 1000 // Default 1 hour // Use the shortest timeframe as base, but not too frequent for budget optimization const shortestTf = selectedTimeframes.reduce((shortest, current) => { const currentDelay = ANALYSIS_DELAYS[current] || 60 * 60 * 1000 const shortestDelay = ANALYSIS_DELAYS[shortest] || 60 * 60 * 1000 return currentDelay < shortestDelay ? current : shortest }) // Minimum 10 minutes delay to protect ChatGPT budget return Math.max(ANALYSIS_DELAYS[shortestTf] || 60 * 60 * 1000, 10 * 60 * 1000) } // Format countdown time for display const formatCountdown = (milliseconds) => { if (milliseconds <= 0) return 'Running soon...' const totalSeconds = Math.ceil(milliseconds / 1000) const hours = Math.floor(totalSeconds / 3600) const minutes = Math.floor((totalSeconds % 3600) / 60) const seconds = totalSeconds % 60 if (hours > 0) { return `${hours}h ${minutes}m ${seconds}s` } else if (minutes > 0) { return `${minutes}m ${seconds}s` } else { return `${seconds}s` } } const startContinuousLearning = () => { if (learningInterval) { clearInterval(learningInterval) } const delay = calculateOptimalDelay() console.log(`๐ Starting continuous learning with ${delay / 60000} minute intervals`) // Run first analysis immediately for faster feedback setTimeout(async () => { console.log('๐ IMMEDIATE: Running first continuous learning analysis') console.log('๐ Running immediate learning analysis (paper trading mode)') try { await runSafeAnalysis(true) // Mark as continuous learning } catch (error) { console.error('โ Error in immediate analysis:', error) } }, 5000) // 5 seconds delay for immediate feedback const interval = setInterval(async () => { console.log('๐ Continuous learning cycle triggered') console.log(`๐ Current time: ${new Date().toLocaleTimeString()}`) // For safe paper trading, always run analysis regardless of positions // (since it's completely isolated and for learning purposes) console.log('๐ Running scheduled learning analysis (paper trading mode)') try { await runSafeAnalysis(true) // Mark as continuous learning } catch (error) { console.error('โ Error in continuous learning cycle:', error) // Set next time even if there's an error to prevent stopping setNextAnalysisTime(Date.now() + delay) } }, delay) setLearningInterval(interval) setNextAnalysisTime(Date.now() + 5000) // Show immediate next time (5 seconds) console.log(`๐ Continuous learning started - next analysis in 5 seconds, then every ${delay / 60000} minutes`) } const stopContinuousLearning = () => { if (learningInterval) { clearInterval(learningInterval) setLearningInterval(null) setNextAnalysisTime(null) console.log('๐ Continuous learning stopped') } } const restartContinuousLearning = () => { console.log('๐ Restarting continuous learning...') stopContinuousLearning() // Small delay to ensure cleanup setTimeout(() => { startContinuousLearning() console.log('โ Continuous learning restarted successfully') }, 1000) } useEffect(() => { // Load paper trading data from localStorage const savedTrades = localStorage.getItem('safePaperTrades') const savedBalance = localStorage.getItem('safePaperBalance') if (savedTrades) { setPaperTrades(JSON.parse(savedTrades)) } if (savedBalance) { setPaperBalance(parseFloat(savedBalance)) } // Fetch AI learning status fetchLearningStatus() // Cleanup continuous learning on unmount return () => { if (learningInterval) { clearInterval(learningInterval) } } }, []) // Update continuous learning when timeframes change useEffect(() => { if (continuousLearning) { stopContinuousLearning() startContinuousLearning() } }, [selectedTimeframes]) // Save to localStorage whenever data changes useEffect(() => { localStorage.setItem('safePaperTrades', JSON.stringify(paperTrades)) localStorage.setItem('safePaperBalance', paperBalance.toString()) }, [paperTrades, paperBalance]) const runSafeAnalysis = async (isContinuous = false) => { console.log(`๐ ${isContinuous ? 'CONTINUOUS LEARNING' : 'BUTTON CLICKED'}: Starting safe analysis...`) console.log(`๐ฏ Analysis Type: ${isContinuous ? 'CONTINUOUS LEARNING' : 'MANUAL'} for ${symbol}`) console.log(`โฐ Current time: ${new Date().toLocaleString()}`) console.log(`๐ Selected timeframes: ${selectedTimeframes.join(', ')}`) if (isContinuous) { console.log(`๐ This is a CONTINUOUS LEARNING cycle - automatic analysis`) } console.log(`๐ Selected timeframes: ${selectedTimeframes.join(', ')}`) setLoading(true) setError(null) setLastAnalysisTime(Date.now()) try { console.log('๐ SAFE PAPER TRADING: Starting isolated analysis...') console.log('๐ Request data:', { symbol, selectedTimeframes, mode: 'PAPER_ONLY', paperTrading: true, isolatedMode: true, isContinuous }) console.log(`๐ Making API call to /api/paper-trading-safe...`) // SAFETY: Only call the isolated paper trading API const response = await fetch('/api/paper-trading-safe', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ symbol, selectedTimeframes, mode: 'PAPER_ONLY', // REQUIRED for safety paperTrading: true, isolatedMode: true, isContinuous }) }) console.log('๐ก Response status:', response.status) console.log('๐ก Response ok:', response.ok) if (!response.ok) { const errorText = await response.text() console.error('โ Response error:', errorText) throw new Error(`Analysis failed: ${response.status} - ${errorText}`) } const result = await response.json() console.log('๐ Full API result:', result) if (!result.success) { throw new Error(result.error || 'Analysis failed') } console.log('โ SAFE ANALYSIS COMPLETE:', result.analysis.recommendation) const analysisData = { ...result.analysis, timeframes: selectedTimeframes, analysisType: isContinuous ? 'CONTINUOUS_LEARNING' : 'MANUAL' } setCurrentAnalysis(analysisData) // Add to analysis history with timestamp const historyEntry = { ...analysisData, timestamp: new Date().toISOString(), symbol: symbol, timeframes: selectedTimeframes, analysisId: `analysis_${Date.now()}_${Math.random().toString(36).substr(2, 9)}` } // Keep only last 10 analyses in history setAnalysisHistory(prev => { const updated = [historyEntry, ...prev].slice(0, 10) try { localStorage.setItem('safePaperTrading_analysisHistory', JSON.stringify(updated)) console.log(`๐พ Persisted ${updated.length} analysis history entries`) } catch (error) { console.error('โ ๏ธ Error persisting analysis history:', error) } return updated }) // Update next analysis time for both manual and continuous learning if (continuousLearning) { const delay = calculateOptimalDelay() const nextTime = Date.now() + delay setNextAnalysisTime(nextTime) console.log(`โฐ Next analysis scheduled for: ${new Date(nextTime).toLocaleString()}`) console.log(`โฑ๏ธ Delay: ${delay / 60000} minutes`) } // AUTO-EXECUTE TRADES: If auto-execute is enabled and we have a strong recommendation, execute the trade console.log('๐ Checking auto-execute conditions:', { autoExecuteTrades, recommendation: analysisData.recommendation, confidence: analysisData.confidence, hasAnalysisData: !!analysisData }) if (autoExecuteTrades && analysisData.recommendation && analysisData.confidence >= 60) { const recommendation = analysisData.recommendation.toUpperCase() if (recommendation === 'BUY' || recommendation === 'SELL') { console.log(`๐ค AUTO-EXECUTE: ${recommendation} signal with ${analysisData.confidence}% confidence`) // Wait a moment for the analysis to fully update, then execute setTimeout(() => { try { executeSafePaperTrade(recommendation) console.log(`โ AUTO-EXECUTED: ${recommendation} trade based on AI recommendation`) } catch (error) { console.error('โ Auto-execute error:', error) } }, 1000) } else { console.log(`๐ก AUTO-EXECUTE: HOLD signal (${recommendation}) - no trade executed`) } } else if (autoExecuteTrades) { console.log(`๐ก AUTO-EXECUTE: Recommendation ${analysisData.recommendation} with ${analysisData.confidence}% confidence does not meet execution criteria (need BUY/SELL with โฅ60% confidence)`) } else { console.log(`๐ AUTO-EXECUTE: Disabled or no valid recommendation`) } } catch (error) { console.error('โ Safe analysis error:', error) console.error('โ Error stack:', error.stack) setError(error.message) } finally { setLoading(false) console.log('๐ Analysis complete, loading set to false') } } const executeSafePaperTrade = (signal) => { if (!currentAnalysis) return const trade = { id: Date.now(), timestamp: new Date().toISOString(), symbol: currentAnalysis.symbol, timeframe: currentAnalysis.timeframe, side: signal, entryPrice: currentAnalysis.entry?.price || 100, stopLoss: currentAnalysis.stopLoss?.price, takeProfit: currentAnalysis.takeProfits?.tp1?.price, confidence: currentAnalysis.confidence, reasoning: currentAnalysis.reasoning, status: 'OPEN', momentumStatus: currentAnalysis.momentumStatus?.type, entryQuality: currentAnalysis.entryQuality?.score, paperMode: true, safeMode: true } // Calculate position size based on risk management const riskAmount = paperBalance * (settings.riskPerTrade / 100) const stopDistance = Math.abs(trade.entryPrice - (trade.stopLoss || trade.entryPrice * 0.95)) trade.positionSize = Math.min(riskAmount / stopDistance, paperBalance * 0.1) setPaperTrades(prev => [trade, ...prev]) console.log('๐ SAFE PAPER TRADE:', trade) alert(`โ Safe Paper Trade: ${signal} ${trade.symbol} at $${trade.entryPrice}\\n๐ก This is completely isolated - no real money at risk!`) } const closeSafePaperTrade = (tradeId, exitPrice) => { setPaperTrades(prev => prev.map(trade => { if (trade.id === tradeId && trade.status === 'OPEN') { const pnl = trade.side === 'BUY' ? (exitPrice - trade.entryPrice) * (trade.positionSize / trade.entryPrice) : (trade.entryPrice - exitPrice) * (trade.positionSize / trade.entryPrice) const isWinner = pnl > 0 setPaperBalance(current => current + pnl) // Update learning insights after closing trade updateLearningInsights(trade, pnl, isWinner) return { ...trade, status: 'CLOSED', exitPrice, exitTime: new Date().toISOString(), pnl, isWinner, exitReason: 'Manual close' } } return trade })) } const updateLearningInsights = async (trade, pnl, isWinner) => { try { // Simulate AI learning from trade outcome const learningData = { tradeId: trade.id, symbol: trade.symbol, timeframe: trade.timeframe, side: trade.side, entryPrice: trade.entryPrice, exitPrice: trade.exitPrice || null, pnl, isWinner, confidence: trade.confidence, reasoning: trade.reasoning, timestamp: new Date().toISOString() } console.log('๐ง AI Learning from trade outcome:', learningData) // Call learning API if available (simulated for paper trading) setLearningInsights(prev => ({ ...prev, lastTrade: learningData, totalTrades: (prev?.totalTrades || 0) + 1, winners: isWinner ? (prev?.winners || 0) + 1 : (prev?.winners || 0), learningPoints: [ ...(prev?.learningPoints || []).slice(-4), // Keep last 4 { timestamp: new Date().toISOString(), insight: generateLearningInsight(trade, pnl, isWinner), impact: isWinner ? 'POSITIVE' : 'NEGATIVE', confidence: trade.confidence } ] })) } catch (error) { console.error('โ Error updating learning insights:', error) } } const generateLearningInsight = (trade, pnl, isWinner) => { const winRate = trade.confidence if (isWinner) { if (winRate >= 80) { return `High confidence (${winRate}%) trade succeeded. Reinforcing pattern recognition for ${trade.symbol} ${trade.timeframe}m setups.` } else { return `Medium confidence (${winRate}%) trade worked out. Learning to trust similar setups more in future.` } } else { if (winRate >= 80) { return `High confidence (${winRate}%) trade failed. Reviewing analysis criteria to prevent overconfidence in similar setups.` } else { return `Medium confidence (${winRate}%) trade didn't work. Adjusting risk thresholds for ${trade.timeframe}m timeframe.` } } } const fetchLearningStatus = async () => { try { // Fetch real AI learning status from the learning system console.log('๐ง Fetching real AI learning status...') // Get real learning status from the AI learning system const response = await fetch('/api/ai-learning-status', { method: 'GET', headers: { 'Content-Type': 'application/json' } }) if (response.ok) { const result = await response.json() const realLearningData = result.data console.log('โ Real learning status received:', realLearningData) setLearningInsights(prev => ({ ...prev, status: { totalDecisions: realLearningData.totalDecisions || 0, recentDecisions: realLearningData.totalOutcomes || 0, successRate: (realLearningData.avgAccuracy || 0) / 100, currentThresholds: { emergency: 0.5, risk: 1.5, confidence: realLearningData.confidenceLevel || 75 }, nextTradeAdjustments: [ realLearningData.recommendation || 'Learning system initializing...', realLearningData.nextMilestone || 'Building pattern recognition', `Phase: ${realLearningData.phase || 'INITIALIZATION'}` ], phase: realLearningData.phase, winRate: realLearningData.winRate, daysActive: realLearningData.daysActive } })) } else { // If learning API not available, create basic structure without mock data console.log('โ ๏ธ Learning API not available, using basic structure') setLearningInsights(prev => ({ ...prev, status: { totalDecisions: 0, recentDecisions: 0, successRate: 0, currentThresholds: { emergency: 0.5, risk: 1.5, confidence: 75 }, nextTradeAdjustments: [ 'Learning system initializing...', 'Building pattern recognition database', 'Preparing adaptive decision making' ] } })) } } catch (error) { console.error('โ Error fetching learning status:', error) // Minimal structure without any mock data setLearningInsights(prev => ({ ...prev, status: { totalDecisions: 0, recentDecisions: 0, successRate: 0, currentThresholds: { emergency: 0.5, risk: 1.5, confidence: 75 }, nextTradeAdjustments: ['Learning system offline'] } })) } } const resetSafePaperTrading = () => { if (confirm('Reset all SAFE paper trading data? This cannot be undone.')) { setPaperBalance(1000) setPaperTrades([]) setCurrentAnalysis(null) localStorage.removeItem('safePaperTrades') localStorage.removeItem('safePaperBalance') } } const openTrades = paperTrades.filter(t => t.status === 'OPEN') const closedTrades = paperTrades.filter(t => t.status === 'CLOSED') const totalPnL = closedTrades.reduce((sum, trade) => sum + (trade.pnl || 0), 0) const winRate = closedTrades.length > 0 ? Math.round((closedTrades.filter(t => (t.pnl || 0) > 0).length / closedTrades.length) * 100) : 0 return (
โ Completely isolated from real trading
โ No connection to live trading APIs
โ Zero risk of real money execution
๐ง AI learning through safe simulation
๐ Real market analysis for practice
๐ฏ Perfect for confidence building
{continuousLearning ? 'โ Learning Active โ Auto-execute Enabled' : 'โ Click "๐ Start Learning" button below'}
Virtual Balance
= 1000 ? 'text-green-400' : 'text-red-400'}`}> ${paperBalance.toFixed(2)}
Total P&L
= 0 ? 'text-green-400' : 'text-red-400'}`}> ${totalPnL.toFixed(2)}
Win Rate
{winRate}%
Open Trades
{openTrades.length}
Closed Trades
{closedTrades.length}
Wins
{closedTrades.filter(t => (t.pnl || 0) > 0).length}
Losses
{closedTrades.filter(t => (t.pnl || 0) < 0).length}
Analysis History: {analysisHistory.length} entries
Paper Trades: {paperTrades.length} trades
โ Error: {error}
Recommendation
{currentAnalysis.recommendation}
Confidence
{currentAnalysis.confidence}%
Timeframes
{currentAnalysis.timeframes?.map(tf => timeframes.find(t => t.value === tf)?.label || tf ).join(', ') || 'Single'}
Entry Price
${currentAnalysis.entry?.price?.toFixed(2) || 'N/A'}
Analysis Mode
{currentAnalysis.analysisMode === 'CONTINUOUS_LEARNING' ? '๐ Learning' : '๐ค Manual'}
Primary Focus
{currentAnalysis.primaryTimeframe ? timeframes.find(t => t.value === currentAnalysis.primaryTimeframe)?.label || currentAnalysis.primaryTimeframe : 'N/A'}
{typeof currentAnalysis.reasoning === 'string'
? currentAnalysis.reasoning
: typeof currentAnalysis.reasoning === 'object'
? JSON.stringify(currentAnalysis.reasoning, null, 2)
: 'Analysis reasoning not available'}
{currentAnalysis.marketSentiment || 'NEUTRAL'}
{currentAnalysis.recommendation}
{currentAnalysis.confidence}% confidence
{currentAnalysis.keyLevels?.resistance?.join(', ') || `$${(currentAnalysis.entry?.price * 1.02 || 164).toFixed(2)}, $${(currentAnalysis.entry?.price * 1.05 || 168).toFixed(2)}`}
{currentAnalysis.keyLevels?.support?.join(', ') || `$${(currentAnalysis.entry?.price * 0.98 || 160).toFixed(2)}, $${(currentAnalysis.entry?.price * 0.95 || 156).toFixed(2)}`}
${currentAnalysis.entry?.price?.toFixed(2) || 'N/A'}
{typeof currentAnalysis.entry?.reasoning === 'string' ? currentAnalysis.entry.reasoning : typeof currentAnalysis.entry?.reasoning === 'object' ? JSON.stringify(currentAnalysis.entry.reasoning) : currentAnalysis.summary || 'Real market analysis entry point'}
${currentAnalysis.stopLoss?.price?.toFixed(2) || 'N/A'}
{typeof currentAnalysis.stopLoss?.reasoning === 'string' ? currentAnalysis.stopLoss.reasoning : typeof currentAnalysis.stopLoss?.reasoning === 'object' ? JSON.stringify(currentAnalysis.stopLoss.reasoning) : 'Real market analysis stop loss level'}
{typeof currentAnalysis.takeProfits?.reasoning === 'string' ? currentAnalysis.takeProfits.reasoning : typeof currentAnalysis.takeProfits?.reasoning === 'object' ? JSON.stringify(currentAnalysis.takeProfits.reasoning) : 'Real market analysis target levels'}
{typeof currentAnalysis.confirmationTrigger === 'string' ? currentAnalysis.confirmationTrigger : typeof currentAnalysis.confirmationTrigger === 'object' ? JSON.stringify(currentAnalysis.confirmationTrigger) : 'Real market confirmation signals from analysis'}
No trades yet
)}Analyzing patterns...
)}{point.insight}