'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 (
{/* SAFETY NOTICE */}

๐Ÿ›ก๏ธ SAFE PAPER TRADING MODE

โœ… 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

{/* AI LEARNING SETUP NOTICE */} {!continuousLearning || !autoExecuteTrades ? (

๐Ÿค– Enable AI Learning from Virtual Trading

How AI Learning Works: The system must execute virtual trades and track outcomes to learn patterns and improve predictions.

Click "๐ŸŽ“ Start Learning" (Auto-enables trade execution)

{continuousLearning ? 'โœ… Learning Active โ†’ Auto-execute Enabled' : 'โŒ Click "๐ŸŽ“ Start Learning" button below'}

๐Ÿ’ก Auto-Execute: Automatically enabled with learning - AI needs trade outcomes to improve
Learning Process: AI analyzes โ†’ executes virtual trades โ†’ tracks outcomes โ†’ learns from results โ†’ improves predictions
) : (

โœ… AI Learning System Active

๐ŸŽ“ Continuous Learning: ON
๐Ÿค– Auto-Execute: ON
๐Ÿ“ˆ Virtual Trading: Active
๐Ÿง  AI will automatically execute virtual trades based on analysis and learn from outcomes to improve performance
)} {/* Header with Balance */}

๐Ÿ“„ Safe Paper Trading

{continuousLearning && (
๐ŸŽ“ Learning Active {timeRemaining > 0 && (
Next cycle: {formatCountdown(timeRemaining)}
)}
)}

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}%

{/* Stats */}

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}

{/* Trading Controls */}

๐ŸŽฏ Safe Analysis Controls

{continuousLearning && ( )}
{/* Auto-Execute Status - Auto-managed when learning is enabled */}
Auto-Execute Trades {continuousLearning ? "๐Ÿค– Auto-managed with learning - executes trades โ‰ฅ60% confidence for AI feedback" : "โš ๏ธ Enable Continuous Learning to activate auto-execute (required for AI learning)" }
{continuousLearning && autoExecuteTrades ? '๐Ÿค– AUTO-ON' : continuousLearning ? '๐ŸŸก READY' : '๏ฟฝ LOCKED'}
{autoExecuteTrades && continuousLearning && (
โšก Paper trades will be executed automatically when AI recommends BUY/SELL with โ‰ฅ60% confidence
)} {!continuousLearning && (
๐Ÿ’ก For AI Learning: Enable "Continuous Learning" + "Auto-Execute" so the AI can learn from virtual trade outcomes
)}
{/* Multi-Timeframe Selection */}
{/* Trading Style Presets */}
{/* Individual Timeframe Toggles */}
{timeframes.map(tf => ( ))}
Selected: {selectedTimeframes.length > 0 ? selectedTimeframes.map(tf => timeframes.find(t => t.value === tf)?.label || tf ).join(', ') : 'None'} {selectedTimeframes.length > 0 && ( (Analysis delay: {Math.ceil(calculateOptimalDelay() / 60000)}m) )}
{/* Force Analysis Button for Testing */} {continuousLearning && ( )}
โœ… Real market analysis โ€ข Paper trading only โ€ข Zero trading risk {continuousLearning && ( ๐ŸŽ“ Continuous learning active - System automatically analyzes every {Math.ceil(calculateOptimalDelay() / 60000)} minutes {timeRemaining > 0 && ( (Next: {formatCountdown(timeRemaining)}) )} )}
{/* Clear Data Controls */} {(currentAnalysis || paperTrades.length > 0 || analysisHistory.length > 0) && (

Analysis History: {analysisHistory.length} entries

Paper Trades: {paperTrades.length} trades

)}
{/* Error Display */} {error && (

โŒ Error: {error}

)} {/* Current Analysis Results */} {currentAnalysis && (

๐Ÿ“Š Safe Analysis Results

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'}

{/* Action Buttons */} {currentAnalysis.recommendation !== 'HOLD' && currentAnalysis.tradeDecision?.allowed && (
)} {/* Analysis Details */}

Analysis Reasoning:

              {typeof currentAnalysis.reasoning === 'string' 
                ? currentAnalysis.reasoning 
                : typeof currentAnalysis.reasoning === 'object' 
                ? JSON.stringify(currentAnalysis.reasoning, null, 2)
                : 'Analysis reasoning not available'}
            
{/* Toggle Detailed Analysis */}
)} {/* Detailed Market Analysis Panel */} {currentAnalysis && showDetailedAnalysis && (

๐Ÿง  Market Summary {currentAnalysis.timeframes && currentAnalysis.timeframes.length > 1 && ( {currentAnalysis.timeframes.length} Timeframes )}

{currentAnalysis.analysisMode === 'CONTINUOUS_LEARNING' ? 'Continuous learning analysis with multi-timeframe insights' : 'Comprehensive multi-layout analysis with timeframe risk assessment and cross-layout insights' }
{/* Market Sentiment */}

Market Sentiment

{currentAnalysis.marketSentiment || 'NEUTRAL'}

{/* Recommendation */}

Recommendation

{currentAnalysis.recommendation}

{currentAnalysis.confidence}% confidence

{/* Resistance Levels */}

Resistance Levels

{currentAnalysis.keyLevels?.resistance?.join(', ') || `$${(currentAnalysis.entry?.price * 1.02 || 164).toFixed(2)}, $${(currentAnalysis.entry?.price * 1.05 || 168).toFixed(2)}`}

{/* Support Levels */}

Support Levels

{currentAnalysis.keyLevels?.support?.join(', ') || `$${(currentAnalysis.entry?.price * 0.98 || 160).toFixed(2)}, $${(currentAnalysis.entry?.price * 0.95 || 156).toFixed(2)}`}

{/* Trading Setup */}

Trading Setup

{/* Entry Point */}
๐ŸŽฏ Entry Point

${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'}

{/* Stop Loss */}
โญ• Stop Loss

${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'}

{/* Take Profit Targets */}
๐Ÿ’Ž Take Profit Targets
TP1: ${currentAnalysis.takeProfits?.tp1?.price?.toFixed(2) || 'N/A'}
{currentAnalysis.takeProfits?.tp2 && (
TP2: ${currentAnalysis.takeProfits.tp2.price?.toFixed(2)}
)}

{typeof currentAnalysis.takeProfits?.reasoning === 'string' ? currentAnalysis.takeProfits.reasoning : typeof currentAnalysis.takeProfits?.reasoning === 'object' ? JSON.stringify(currentAnalysis.takeProfits.reasoning) : 'Real market analysis target levels'}

{/* Risk Management */}

Risk Management

Risk/Reward Ratio {currentAnalysis.riskToReward || 'N/A'}
โš ๏ธ Confirmation Trigger

{typeof currentAnalysis.confirmationTrigger === 'string' ? currentAnalysis.confirmationTrigger : typeof currentAnalysis.confirmationTrigger === 'object' ? JSON.stringify(currentAnalysis.confirmationTrigger) : 'Real market confirmation signals from analysis'}

Trend: {typeof currentAnalysis.trendAnalysis === 'object' ? (currentAnalysis.trendAnalysis?.direction || 'Analyzing...') : currentAnalysis.trendAnalysis || 'Analyzing...'}
Momentum: {typeof currentAnalysis.momentumAnalysis === 'object' ? (currentAnalysis.momentumAnalysis?.status || 'Analyzing...') : currentAnalysis.momentumAnalysis || 'Analyzing...'}
Volume: {typeof currentAnalysis.volumeAnalysis === 'object' ? (currentAnalysis.volumeAnalysis?.trend || 'Analyzing...') : currentAnalysis.volumeAnalysis || 'Analyzing...'}
Timeframe Risk: {typeof currentAnalysis.timeframeRisk === 'object' ? (currentAnalysis.timeframeRisk?.assessment || 'Medium') : currentAnalysis.timeframeRisk || 'Medium'}
)} {/* AI Learning Insights Panel */} {learningInsights && (

๐Ÿง  AI Learning Insights Real-time learning from trade outcomes

{/* Learning Status */}

Learning Status

Total Decisions: {learningInsights.status?.totalDecisions || 0}
Success Rate: {((learningInsights.status?.successRate || 0) * 100).toFixed(1)}%
Paper Trades: {learningInsights.totalTrades || 0}
{/* Win/Loss Analysis */}

Trade Outcome

{learningInsights.lastTrade ? (
{learningInsights.lastTrade.isWinner ? 'โœ…' : 'โŒ'} {learningInsights.lastTrade.isWinner ? 'WINNER' : 'LOSER'}
Last: {learningInsights.lastTrade.symbol} ${learningInsights.lastTrade.pnl?.toFixed(2)}
Confidence: {learningInsights.lastTrade.confidence}%
) : (

No trades yet

)}
{/* Current Adjustments */}

AI Adjustments

{learningInsights.status?.nextTradeAdjustments?.slice(0, 3).map((adjustment, index) => (
โ€ข {adjustment}
)) || (

Analyzing patterns...

)}
{/* Learning Reflection */} {learningInsights.learningPoints && learningInsights.learningPoints.length > 0 && (

AI Reflection & Learning

{learningInsights.learningPoints.slice(-3).map((point, index) => (
{point.impact === 'POSITIVE' ? '๐Ÿ“ˆ Positive Learning' : '๐Ÿ“‰ Learning from Loss'} {new Date(point.timestamp).toLocaleTimeString()}

{point.insight}

))}
)} {/* What AI is Using for Next Trade */}

๐Ÿ”ฎ AI Database for Next Trade

Current Thresholds:
Emergency Distance: {learningInsights.status?.currentThresholds?.emergency || 0.5}%
Risk Distance: {learningInsights.status?.currentThresholds?.risk || 1.5}%
Min Confidence: {learningInsights.status?.currentThresholds?.confidence || 75}%
Pattern Recognition:
โ€ข {symbol} multi-timeframe: {learningInsights.status?.totalDecisions || 0} total decisions in database
โ€ข Success rate: {((learningInsights.status?.successRate || 0) * 100).toFixed(1)}%
โ€ข Learning phase: {learningInsights.status?.phase || 'INITIALIZATION'}
โ€ข Days active: {learningInsights.status?.daysActive || 0} days
{currentAnalysis?.timeframes && currentAnalysis.timeframes.length > 1 && (
โ€ข Current analysis: {currentAnalysis.timeframes.map(tf => timeframes.find(t => t.value === tf)?.label || tf ).join(' + ')} confluence
)}
)} {/* Open Trades */} {openTrades.length > 0 && (

๐Ÿ“ˆ Open Paper Positions

{openTrades.map(trade => (
{trade.side} {trade.symbol} ${trade.entryPrice} Size: ${trade.positionSize?.toFixed(2)}
Entry: {new Date(trade.timestamp).toLocaleString()} | Confidence: {trade.confidence}%
))}
)} {/* Trade History */} {closedTrades.length > 0 && (

๐Ÿ“ˆ Safe Paper Trade History

{closedTrades.slice(0, 20).map(trade => (
= 0 ? 'bg-green-900/20 border-green-500' : 'bg-red-900/20 border-red-500' }`}>
{trade.side} {trade.symbol} ${trade.entryPrice} โ†’ ${trade.exitPrice} = 0 ? 'text-green-400' : 'text-red-400' }`}> ${(trade.pnl || 0).toFixed(2)} {trade.isWinner ? 'WIN' : 'LOSS'}
{new Date(trade.timestamp).toLocaleDateString()} | Confidence: {trade.confidence}%
))}
)} {/* Analysis History Panel */} {analysisHistory.length > 0 && (

๐Ÿ“Š Analysis History {analysisHistory.length} entries

Recent analyses are automatically saved
{analysisHistory.map((analysis, index) => (
{analysis.recommendation} {analysis.confidence}% {analysis.symbol} โ€ข {analysis.timeframes?.join(', ')}
{new Date(analysis.timestamp).toLocaleString()}
Entry: ${analysis.entry?.price?.toFixed(2) || 'N/A'}
Stop: ${analysis.stopLoss?.price?.toFixed(2) || 'N/A'}
Target: ${analysis.takeProfits?.tp1?.price?.toFixed(2) || 'N/A'}
{analysis.analysisType === 'CONTINUOUS_LEARNING' && (
๐ŸŽ“ Continuous learning analysis
)}
))}
)}
) }