'use client' import { useState, useEffect } from 'react' export default function SafePaperTradingPage() { const [symbol, setSymbol] = useState('SOLUSD') const [timeframe, setTimeframe] = useState('60') const [loading, setLoading] = useState(false) const [currentAnalysis, setCurrentAnalysis] = useState(null) const [paperBalance, setPaperBalance] = useState(1000) const [paperTrades, setPaperTrades] = useState([]) const [error, setError] = useState(null) const [learningInsights, setLearningInsights] = useState(null) const [showDetailedAnalysis, setShowDetailedAnalysis] = useState(false) // SAFETY: Only these timeframes allowed in paper trading const safeTimeframes = [ { label: '5m', value: '5', riskLevel: 'EXTREME' }, { label: '30m', value: '30', riskLevel: 'HIGH' }, { label: '1h', value: '60', riskLevel: 'MEDIUM' }, { label: '4h', value: '240', riskLevel: 'LOW' } ] const settings = { riskPerTrade: 1.0, paperMode: true, // ALWAYS true - cannot be changed isolatedMode: true // ALWAYS true - completely isolated } 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() }, []) // Save to localStorage whenever data changes useEffect(() => { localStorage.setItem('safePaperTrades', JSON.stringify(paperTrades)) localStorage.setItem('safePaperBalance', paperBalance.toString()) }, [paperTrades, paperBalance]) const runSafeAnalysis = async () => { console.log('šŸ”„ BUTTON CLICKED: Starting safe analysis...') setLoading(true) setError(null) try { console.log('šŸ“„ SAFE PAPER TRADING: Starting isolated analysis...') console.log('šŸ“‹ Request data:', { symbol, timeframe, mode: 'PAPER_ONLY', paperTrading: true, isolatedMode: true }) // 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, timeframe, mode: 'PAPER_ONLY', // REQUIRED for safety paperTrading: true, isolatedMode: true }) }) 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) setCurrentAnalysis(result.analysis) } 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 { // Simulate fetching AI learning status const mockLearningStatus = { totalDecisions: Math.floor(Math.random() * 50) + 10, recentDecisions: Math.floor(Math.random() * 10) + 2, successRate: 0.65 + (Math.random() * 0.25), // 65-90% currentThresholds: { emergency: 0.5, risk: 1.5, confidence: 75 }, nextTradeAdjustments: [ 'Increasing position size confidence for SOL/USD setups', 'Tightening stop losses on 1h timeframe trades', 'Looking for momentum exhaustion signals before entry' ] } setLearningInsights(prev => ({ ...prev, status: mockLearningStatus })) } catch (error) { console.error('āŒ Error fetching learning status:', error) } } 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

šŸ“Š Mock analysis for practice

šŸŽÆ Perfect for confidence building

{/* Header with Balance */}

šŸ“„ Safe Paper Trading

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

āœ… Isolated mock analysis • No real APIs • Zero trading risk
{/* Error Display */} {error && (

āŒ Error: {error}

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

šŸ“Š Safe Analysis Results

Recommendation

{currentAnalysis.recommendation}

Confidence

{currentAnalysis.confidence}%

Entry Price

${currentAnalysis.entry?.price?.toFixed(2)}

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

Analysis Reasoning:

              {currentAnalysis.reasoning}
            
{/* Toggle Detailed Analysis */}
)} {/* Detailed Market Analysis Panel */} {currentAnalysis && showDetailedAnalysis && (

🧠 Market Summary

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.resistance || `$${(currentAnalysis.entry?.price * 1.02 || 164).toFixed(2)}, $${(currentAnalysis.entry?.price * 1.05 || 168).toFixed(2)}`}

{/* Support Levels */}

Support Levels

{currentAnalysis.support || `$${(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) || '159.20'}

{currentAnalysis.entryReason || 'Rejection from 15 EMA + VWAP confluence near intraday supply'}

{/* Stop Loss */}
ā­• Stop Loss

${currentAnalysis.stopLoss?.price?.toFixed(2) || '157.80'}

{currentAnalysis.stopReason || 'Above VWAP + failed breakout zone'}

{/* Take Profit Targets */}
šŸ’Ž Take Profit Targets
TP1: ${currentAnalysis.takeProfits?.tp1?.price?.toFixed(2) || '160.50'}
TP2: ${currentAnalysis.takeProfits?.tp2?.price?.toFixed(2) || '162.00'}

Immediate structure target with RSI/OBV expectations

{/* Risk Management */}

Risk Management

Risk/Reward Ratio {currentAnalysis.riskRewardRatio || '1:3'}
āš ļø Confirmation Trigger

{currentAnalysis.confirmationTrigger || 'Specific signal: Bullish engulfing candle on rejection from VWAP zone with RSI above 50'}

RSI: RSI should reach 60-65 zone
OBV: OBV confirming momentum
Extended target: If momentum continues
Structure: RSI approaching 70+ overbought
)} {/* 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} {timeframe}m setups: {Math.floor(Math.random() * 8) + 3} previous analyses
• Success rate this timeframe: {(65 + Math.random() * 25).toFixed(1)}%
• Learned stop-loss distance: {(1.2 + Math.random() * 0.8).toFixed(1)}%
• Best entry signals: RSI + VWAP 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}%
))}
)}
) }