'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 (
ā 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
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}
ā Error: {error}
Recommendation
{currentAnalysis.recommendation}
Confidence
{currentAnalysis.confidence}%
Entry Price
${currentAnalysis.entry?.price?.toFixed(2)}
{currentAnalysis.reasoning}
{currentAnalysis.marketSentiment || 'NEUTRAL'}
{currentAnalysis.recommendation}
{currentAnalysis.confidence}% confidence
{currentAnalysis.resistance || `$${(currentAnalysis.entry?.price * 1.02 || 164).toFixed(2)}, $${(currentAnalysis.entry?.price * 1.05 || 168).toFixed(2)}`}
{currentAnalysis.support || `$${(currentAnalysis.entry?.price * 0.98 || 160).toFixed(2)}, $${(currentAnalysis.entry?.price * 0.95 || 156).toFixed(2)}`}
${currentAnalysis.entry?.price?.toFixed(2) || '159.20'}
{currentAnalysis.entryReason || 'Rejection from 15 EMA + VWAP confluence near intraday supply'}
${currentAnalysis.stopLoss?.price?.toFixed(2) || '157.80'}
{currentAnalysis.stopReason || 'Above VWAP + failed breakout zone'}
Immediate structure target with RSI/OBV expectations
{currentAnalysis.confirmationTrigger || 'Specific signal: Bullish engulfing candle on rejection from VWAP zone with RSI above 50'}
No trades yet
)}Analyzing patterns...
)}{point.insight}