'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) // 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)) } }, []) // Save to localStorage whenever data changes useEffect(() => { localStorage.setItem('safePaperTrades', JSON.stringify(paperTrades)) localStorage.setItem('safePaperBalance', paperBalance.toString()) }, [paperTrades, paperBalance]) const runSafeAnalysis = async () => { setLoading(true) setError(null) try { console.log('šŸ“„ SAFE PAPER TRADING: Starting isolated analysis...') // 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 }) }) if (!response.ok) { throw new Error(`Analysis failed: ${response.status}`) } const result = await response.json() 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) setError(error.message) } finally { setLoading(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) setPaperBalance(current => current + pnl) return { ...trade, status: 'CLOSED', exitPrice, exitTime: new Date().toISOString(), pnl, exitReason: 'Manual close' } } return trade })) } 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}
            
)} {/* 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)}
{new Date(trade.timestamp).toLocaleDateString()} | Confidence: {trade.confidence}%
))}
)}
) }