import React, { useState, useEffect, useRef } from 'react'; import { MessageCircle, TrendingUp, TrendingDown, DollarSign, Activity, Settings, Bell, User, BarChart3, Zap, Shield, Target, Play, Pause, RefreshCw, Eye, EyeOff, Send, Mic, MicOff, Brain, BookOpen, Database, TrendingUp as TrendUp, ArrowUp, ArrowDown, RotateCcw, Layers, Star, Sparkles, AlertTriangle, CheckCircle, Shuffle, Cpu, TrendingUp as TrendingUpIcon, BarChart, Lightbulb, Gauge } from 'lucide-react'; // AI Helper Functions const explainTradeStrategy = (activeBot, marketData, userProfile, botCombos) => { // Find the active combo or determine which bot is being used const activeCombo = botCombos.find(combo => combo.active); const activeBotName = activeCombo ? activeCombo.name : getBotDisplayName(activeBot); // Analyze current market conditions const avgVolatility = marketData.reduce((sum, item) => { const vol = item.volatility === 'high' ? 3 : item.volatility === 'medium' ? 2 : 1; return sum + vol; }, 0) / marketData.length; const bullishPairs = marketData.filter(item => item.trend === 'bullish').length; const bearishPairs = marketData.filter(item => item.trend === 'bearish').length; const highVolPairs = marketData.filter(item => item.volatility === 'high').length; // Get strongest trending pair const strongestTrend = marketData.reduce((strongest, current) => Math.abs(current.changePercent) > Math.abs(strongest.changePercent) ? current : strongest ); // Get user's tier for personalization const userTier = userProfile.currentTier; const userWinRate = userProfile.lifetimeWins / userProfile.lifetimeTrades * 100; let explanation = ""; if (activeBot === 'digits' || (activeCombo && activeCombo.bots.includes('digits'))) { explanation = `I'm activating the Digits strategy because market volatility is ${avgVolatility > 2.5 ? 'elevated' : 'moderate'} (${avgVolatility.toFixed(1)}/3.0). ` + `${strongestTrend.symbol} is showing ${Math.abs(strongestTrend.changePercent).toFixed(2)}% movement, creating optimal conditions for last-digit predictions. ` + `With ${highVolPairs} high-volatility pairs active, the random number generation patterns favor our digit analysis algorithms. ` + `Your ${userTier} tier status and ${userWinRate.toFixed(1)}% win rate suggest this conservative approach aligns with your risk profile.`; } else if (activeBot === 'updown' || (activeCombo && activeCombo.bots.includes('updown'))) { const trendDirection = bullishPairs > bearishPairs ? 'bullish' : 'bearish'; explanation = `Deploying Up/Down strategy as market sentiment is ${trendDirection} with ${bullishPairs} bullish vs ${bearishPairs} bearish pairs. ` + `${strongestTrend.symbol} leading with ${strongestTrend.changePercent > 0 ? '+' : ''}${strongestTrend.changePercent.toFixed(2)}% indicates clear directional momentum. ` + `Current volatility levels (${avgVolatility.toFixed(1)}/3.0) provide sufficient price movement for profitable directional trades. ` + `This strategy matches your ${userProfile.totalTrades} trade experience and targets the ${trendDirection} bias I'm detecting.`; } else if (activeBot === 'touch' || (activeCombo && activeCombo.bots.includes('touch'))) { explanation = `Selecting Touch/No Touch strategy due to ${highVolPairs} high-volatility pairs creating strong barrier-testing conditions. ` + `${strongestTrend.symbol} at ${strongestTrend.price.toFixed(4)} with ${Math.abs(strongestTrend.changePercent).toFixed(2)}% movement suggests price will ${Math.abs(strongestTrend.changePercent) > 0.3 ? 'likely breach' : 'struggle to reach'} key levels. ` + `Market volatility index of ${avgVolatility.toFixed(1)} indicates ${avgVolatility > 2 ? 'high probability of barrier contact' : 'range-bound behavior'}. ` + `Your ${userTier} tier analytics show this approach has ${activeCombo ? activeCombo.winRate : '75'}% success rate in similar conditions.`; } else if (activeBot === 'multipliers' || (activeCombo && activeCombo.bots.includes('multipliers'))) { explanation = `Engaging Multipliers strategy as ${strongestTrend.symbol} shows ${strongestTrend.changePercent > 0 ? 'strong upward' : 'significant downward'} momentum (${strongestTrend.changePercent.toFixed(2)}%). ` + `With ${highVolPairs} volatile pairs and average volatility at ${avgVolatility.toFixed(1)}/3.0, leveraged positions can capitalize on extended moves. ` + `Market structure favors ${bullishPairs > bearishPairs ? 'long' : 'short'} bias across ${bullishPairs + bearishPairs} trending pairs. ` + `Your portfolio balance of $${userProfile.lifetimeVolume.toLocaleString()} and ${userWinRate.toFixed(1)}% win rate support this higher-risk, higher-reward approach.`; } else if (activeBot === 'accumulators' || (activeCombo && activeCombo.bots.includes('accumulators'))) { explanation = `Activating Accumulators strategy as market conditions show ${avgVolatility < 2 ? 'stable' : 'moderate'} volatility (${avgVolatility.toFixed(1)}/3.0), ideal for growth accumulation. ` + `${strongestTrend.symbol} trending ${strongestTrend.changePercent > 0 ? 'upward' : 'downward'} at ${strongestTrend.changePercent.toFixed(2)}% provides consistent directional bias. ` + `With ${marketData.length - highVolPairs} stable pairs maintaining steady movement, accumulation strategies can compound gains effectively. ` + `Your ${userProfile.totalTrades} completed trades and ${userTier} status indicate experience suitable for this patient, growth-focused approach.`; } else if (activeCombo) { // Handle combo-specific explanations if (activeCombo.name === 'Market Navigator') { explanation = `Deploying Market Navigator combo as current conditions match our trending market profile. ` + `${bullishPairs} bullish vs ${bearishPairs} bearish pairs with ${avgVolatility.toFixed(1)}/3.0 volatility creates optimal navigation conditions. ` + `${strongestTrend.symbol} leading at ${strongestTrend.changePercent.toFixed(2)}% confirms directional clarity. ` + `This combo's ${activeCombo.winRate}% win rate and ${activeCombo.expectedImprovement}% improvement potential align with your ${userTier} tier strategy.`; } else if (activeCombo.name === 'Trend Catcher') { explanation = `Launching Trend Catcher combo due to strong directional signals across ${bullishPairs + bearishPairs} trending pairs. ` + `${strongestTrend.symbol} showing ${Math.abs(strongestTrend.changePercent).toFixed(2)}% movement with ${strongestTrend.volatility} volatility indicates sustainable trend. ` + `High-volatility environment (${highVolPairs} pairs) provides the momentum this combo needs for ${activeCombo.expectedImprovement}% improvement. ` + `Your ${userWinRate.toFixed(1)}% win rate and ${userProfile.totalTrades} trades experience support this aggressive trend-following approach.`; } else if (activeCombo.name === 'Volatility Hunter') { explanation = `Engaging Volatility Hunter combo as ${highVolPairs} high-volatility pairs create ideal hunting conditions. ` + `Market volatility index at ${avgVolatility.toFixed(1)}/3.0 with ${strongestTrend.symbol} moving ${strongestTrend.changePercent.toFixed(2)}% indicates rich volatility opportunities. ` + `Range-bound behavior in ${marketData.length - (bullishPairs + bearishPairs)} pairs provides the oscillating patterns this combo exploits. ` + `Expected ${activeCombo.expectedImprovement}% improvement matches your ${userTier} tier risk tolerance and ${userProfile.lifetimeVolume.toLocaleString()} volume experience.`; } else if (activeCombo.name === 'Precision Striker') { explanation = `Activating Precision Striker combo for stable market conditions with ${avgVolatility.toFixed(1)}/3.0 volatility. ` + `${marketData.length - highVolPairs} stable pairs and controlled movement in ${strongestTrend.symbol} (${strongestTrend.changePercent.toFixed(2)}%) favor precision entries. ` + `This conservative approach targets ${activeCombo.winRate}% win rate, ideal for your ${userTier} tier and steady ${userWinRate.toFixed(1)}% performance history. ` + `Low-risk profile with ${activeCombo.expectedImprovement}% improvement potential protects your $${userProfile.lifetimeVolume.toLocaleString()} trading capital.`; } else if (activeCombo.name === 'Momentum Rider') { explanation = `Deploying Momentum Rider combo as momentum signals align across ${bullishPairs + bearishPairs} trending pairs. ` + `${strongestTrend.symbol} momentum at ${strongestTrend.changePercent.toFixed(2)}% with ${strongestTrend.volatility} volatility creates perfect riding conditions. ` + `High-energy market with ${highVolPairs} volatile pairs supports this combo's ${activeCombo.expectedImprovement}% improvement target. ` + `Your advanced ${userTier} tier and ${userProfile.totalTrades} trade experience enable this sophisticated momentum-capture strategy.`; } } else { // Fallback explanation explanation = `Executing ${getBotDisplayName(activeBot)} strategy based on current market analysis. ` + `${strongestTrend.symbol} showing ${strongestTrend.changePercent.toFixed(2)}% movement with ${avgVolatility.toFixed(1)}/3.0 volatility creates favorable conditions. ` + `Market structure with ${bullishPairs} bullish and ${bearishPairs} bearish pairs supports this approach. ` + `Your ${userTier} tier status and trading experience guide this strategic selection.`; } return explanation; }; const getBotDisplayName = (botKey) => { const botNames = { digits: 'Digits', updown: 'Up/Down', inout: 'In/Out', accumulators: 'Accumulators', multipliers: 'Multipliers', asians: 'Asians', reset: 'Reset Call/Put', highlowTicks: 'High/Low Ticks', onlyUps: 'Only Ups/Downs', vanillas: 'Vanillas', turbos: 'Turbos', touch: 'Touch/No Touch' }; return botNames[botKey] || 'Trading Bot'; }; const generateOptimisticExplanation = (activeBot, marketData, userProfile, botCombos) => { const activeCombo = botCombos.find(combo => combo.active); const strongestTrend = marketData.reduce((strongest, current) => Math.abs(current.changePercent) > Math.abs(strongest.changePercent) ? current : strongest ); if (activeCombo) { return `🤖 Analyzing ${activeCombo.name} combo deployment... ${strongestTrend.symbol} showing ${strongestTrend.changePercent.toFixed(2)}% movement. Calculating optimal entry based on your ${userProfile.currentTier} tier strategy...`; } else { return `🤖 Preparing ${getBotDisplayName(activeBot)} strategy... Market volatility detected in ${strongestTrend.symbol}. Running ${userProfile.currentTier}-tier analysis for optimal positioning...`; } }; // Simulated TensorFlow.js and Brain.js libraries const tf = { sequential: () => ({ add: () => {}, compile: () => {}, fit: () => Promise.resolve(), predict: (input) => ({ dataSync: () => [Math.random(), Math.random(), Math.random()] }) }), layers: { dense: (config) => config, dropout: (config) => config }, tensor2d: (data) => data, dispose: () => {} }; const brain = { NeuralNetwork: class { constructor() {} train(data) { return { error: Math.random() * 0.1 }; } run(input) { return { marketNavigator: Math.random(), trendCatcher: Math.random(), volatilityHunter: Math.random(), precisionStriker: Math.random(), momentumRider: Math.random() }; } } }; // Simulated Lottie-web library const lottie = { loadAnimation: (params) => { return { play: () => console.log('Playing animation:', params.name), stop: () => console.log('Stopping animation:', params.name), destroy: () => console.log('Destroying animation:', params.name), setSpeed: (speed) => console.log('Setting speed:', speed), goToAndStop: (frame) => console.log('Go to frame:', frame), addEventListener: (event, callback) => { if (event === 'complete') { setTimeout(callback, params.loop ? 0 : 2000); } } }; } }; // Simulated Lottie animation data const lottieAnimations = { idle: { name: 'idle', animationData: {}, loop: true, autoplay: true }, speaking: { name: 'speaking', animationData: {}, loop: true, autoplay: false }, winning: { name: 'winning', animationData: {}, loop: false, autoplay: false }, losing: { name: 'losing', animationData: {}, loop: false, autoplay: false }, comboActivated: { name: 'comboActivated', animationData: {}, loop: false, autoplay: false }, nervous: { name: 'nervous', animationData: {}, loop: true, autoplay: false } }; // Add Victory charting library simulation const Victory = { VictoryChart: ({ children, theme, padding, width, height, ...props }) => (
{children}
), VictoryLine: ({ data, style, animate }) => ( `L ${50 + i * 30},${250 - d.y * 2}`).join(' ')}`} stroke={style?.data?.stroke || '#0f3460'} strokeWidth="2" fill="none" /> ), VictoryArea: ({ data, style }) => ( `L ${50 + i * 30},${250 - d.y * 2}`).join(' ')} L ${50 + (data?.length - 1) * 30},250 Z`} fill={style?.data?.fill || 'rgba(15, 52, 96, 0.3)'} /> ), VictoryAxis: ({ dependentAxis, tickFormat, style }) => (
{dependentAxis ? 'Y-Axis' : 'X-Axis'}
), VictoryTooltip: ({ children }) =>
{children}
, VictoryTheme: { material: {} } }; const OmniTradeDashboard = () => { const [activeBot, setActiveBot] = useState('digits'); const [botStatuses, setBotStatuses] = useState({ digits: true, updown: false, inout: true, accumulators: false, multipliers: true, asians: false, reset: true, highlowTicks: false, onlyUps: true, vanillas: false, turbos: true, touch: false }); const [portfolioData, setPortfolioData] = useState({ balance: 25847.32, todayPnL: 1247.85, totalPnL: 8934.21, winRate: 73.2, activeTrades: 12, totalTrades: 1847, dailyReturnRate: 0.048 }); const [chatMessages, setChatMessages] = useState([ { id: 1, type: 'ai', content: 'Welcome to OmniTrade! I\'m SUCCESS, your AI trading assistant. Market conditions are favorable today with strong volatility in EUR/USD and GBP/USD pairs. Shall we review your trading strategy?', timestamp: new Date() } ]); const [chatInput, setChatInput] = useState(''); const [isChatOpen, setIsChatOpen] = useState(false); const [isListening, setIsListening] = useState(false); const [marketData, setMarketData] = useState([ { symbol: 'EUR/USD', price: 1.0847, change: 0.0023, changePercent: 0.21, volatility: 'high', trend: 'bullish' }, { symbol: 'GBP/USD', price: 1.2634, change: -0.0012, changePercent: -0.09, volatility: 'medium', trend: 'bearish' }, { symbol: 'USD/JPY', price: 149.82, change: 0.45, changePercent: 0.30, volatility: 'low', trend: 'bullish' }, { symbol: 'AUD/USD', price: 0.6721, change: 0.0034, changePercent: 0.51, volatility: 'high', trend: 'bullish' } ]); const [recentTrades, setRecentTrades] = useState([ { id: 1, type: 'Higher', symbol: 'EUR/USD', stake: 10, payout: 18.5, status: 'won', time: '14:32' }, { id: 2, type: 'Lower', symbol: 'GBP/USD', stake: 25, payout: 0, status: 'lost', time: '14:28' }, { id: 3, type: 'Touch', symbol: 'USD/JPY', stake: 15, payout: 27.3, status: 'won', time: '14:25' }, { id: 4, type: 'Accumulator', symbol: 'AUD/USD', stake: 50, payout: 89.2, status: 'won', time: '14:20' } ]); // Teach Bot Feature State const [isTeachMode, setIsTeachMode] = useState(false); const [teachBotData, setTeachBotData] = useState({ tradesRecorded: 0, modelAccuracy: 0, trainingStatus: 'idle', lastTraining: null, personalizedBotActive: false }); const [manualTradeForm, setManualTradeForm] = useState({ tradeType: 'rise', symbol: 'EUR/USD', stake: 10, duration: 5, prediction: null }); const [recordedTrades, setRecordedTrades] = useState([]); const [modelTrainingProgress, setModelTrainingProgress] = useState(0); // Bot Combos Feature State const [botCombos, setBotCombos] = useState([ { id: 'market-navigator', name: 'Market Navigator', description: 'Optimal for trending markets with medium volatility', bots: ['updown', 'multipliers', 'turbos'], expectedImprovement: 23.5, marketConditions: ['trending', 'medium_volatility'], winRate: 78.2, avgReturn: 15.3, riskLevel: 'medium', active: false }, { id: 'trend-catcher', name: 'Trend Catcher', description: 'Perfect for strong directional movements', bots: ['asians', 'vanillas', 'onlyUps'], expectedImprovement: 31.8, marketConditions: ['strong_trend', 'high_volatility'], winRate: 82.1, avgReturn: 22.7, riskLevel: 'high', active: false }, { id: 'volatility-hunter', name: 'Volatility Hunter', description: 'Excels in high-volatility, range-bound markets', bots: ['digits', 'inout', 'touch'], expectedImprovement: 18.9, marketConditions: ['range_bound', 'high_volatility'], winRate: 75.6, avgReturn: 12.4, riskLevel: 'low', active: false }, { id: 'precision-striker', name: 'Precision Striker', description: 'Conservative approach for stable returns', bots: ['accumulators', 'reset', 'highlowTicks'], expectedImprovement: 14.2, marketConditions: ['stable', 'low_volatility'], winRate: 85.3, avgReturn: 8.9, riskLevel: 'low', active: false }, { id: 'momentum-rider', name: 'Momentum Rider', description: 'Capitalizes on strong momentum shifts', bots: ['multipliers', 'turbos', 'updown', 'touch'], expectedImprovement: 27.4, marketConditions: ['momentum_shift', 'high_volatility'], winRate: 79.8, avgReturn: 19.6, riskLevel: 'high', active: false } ]); const [currentMarketCondition, setCurrentMarketCondition] = useState('trending'); const [autoModeActive, setAutoModeActive] = useState(false); const [performanceAlert, setPerformanceAlert] = useState(null); // SUCCESS AI Lottie Animation State const [successAnimationState, setSuccessAnimationState] = useState('idle'); const [currentLottieAnimation, setCurrentLottieAnimation] = useState(null); const [animationContainer, setAnimationContainer] = useState(null); const [isTrading, setIsTrading] = useState(false); const [lastTradeOutcome, setLastTradeOutcome] = useState(null); // Combo Performance Tracking State const [comboPerformanceData, setComboPerformanceData] = useState({}); const [performanceMetric, setPerformanceMetric] = useState('pnl'); const [performanceTimeRange, setPerformanceTimeRange] = useState('hours'); const [performanceHistory, setPerformanceHistory] = useState({}); // Real-time Market Analysis Engine State const [marketAnalysisEngine, setMarketAnalysisEngine] = useState({ volatilityIndex: 0, trendStrength: 0, newsSentiment: 0, rsiIndicator: 0, macdSignal: 0, volumeProfile: 0, supportResistance: 0, lastUpdate: new Date() }); const [aiPredictions, setAiPredictions] = useState([]); const [aiModel, setAiModel] = useState(null); const [isAnalyzing, setIsAnalyzing] = useState(false); const [analysisConfidence, setAnalysisConfidence] = useState(0); // Gamification & Rewards System State const [userProfile, setUserProfile] = useState({ totalPoints: 2847, currentTier: 'Gold', nextTier: 'Platinum', pointsToNextTier: 653, lifetimeVolume: 125847.32, lifetimeWins: 1342, lifetimeTrades: 1847, memberSince: new Date('2023-01-15'), achievements: ['First Trade', 'High Roller', 'Consistent Trader', 'Profit Master'] }); const [rewardsTiers, setRewardsTiers] = useState([ { name: 'Bronze', minPoints: 0, maxPoints: 999, color: '#CD7F32', icon: '🥉', benefits: ['Basic analytics', 'Email support'], rewards: [ { type: 'gift_card', value: 10, provider: 'Amazon', pointsCost: 500 }, { type: 'merchandise', value: 'OmniTrade Sticker Pack', pointsCost: 200 } ] }, { name: 'Silver', minPoints: 1000, maxPoints: 2499, color: '#C0C0C0', icon: '🥈', benefits: ['Advanced analytics', 'Priority support', '1 free bot combo'], rewards: [ { type: 'gift_card', value: 25, provider: 'Amazon', pointsCost: 1200 }, { type: 'cash_bonus', value: 15, pointsCost: 1500 }, { type: 'merchandise', value: 'OmniTrade T-Shirt', pointsCost: 800 } ] }, { name: 'Gold', minPoints: 2500, maxPoints: 4999, color: '#FFD700', icon: '🥇', benefits: ['Premium analytics', 'VIP support', '3 free bot combos', 'Custom strategies'], rewards: [ { type: 'gift_card', value: 50, provider: 'Amazon', pointsCost: 2000 }, { type: 'cash_bonus', value: 35, pointsCost: 2500 }, { type: 'merchandise', value: 'OmniTrade Hoodie', pointsCost: 1500 }, { type: 'trading_credit', value: 100, pointsCost: 3000 } ] }, { name: 'Platinum', minPoints: 5000, maxPoints: 9999, color: '#E5E4E2', icon: '💎', benefits: ['Elite analytics', 'Dedicated support', 'Unlimited bot combos', 'Personal AI tuning'], rewards: [ { type: 'gift_card', value: 100, provider: 'Amazon', pointsCost: 3500 }, { type: 'cash_bonus', value: 75, pointsCost: 4000 }, { type: 'merchandise', value: 'Premium Trading Setup', pointsCost: 6000 }, { type: 'trading_credit', value: 250, pointsCost: 5000 } ] }, { name: 'Diamond', minPoints: 10000, maxPoints: Infinity, color: '#B9F2FF', icon: '💠', benefits: ['Ultimate analytics', 'White-glove support', 'Custom bot development', 'Exclusive events'], rewards: [ { type: 'gift_card', value: 250, provider: 'Amazon', pointsCost: 7500 }, { type: 'cash_bonus', value: 200, pointsCost: 8000 }, { type: 'merchandise', value: 'VIP Trading Experience', pointsCost: 12000 }, { type: 'trading_credit', value: 500, pointsCost: 10000 }, { type: 'exclusive', value: 'Private Trading Masterclass', pointsCost: 15000 } ] } ]); const [pointsHistory, setPointsHistory] = useState([ { id: 1, action: 'Winning Trade', points: 25, timestamp: new Date(Date.now() - 3600000) }, { id: 2, action: 'High Volume Day', points: 50, timestamp: new Date(Date.now() - 7200000) }, { id: 3, action: 'Profit Milestone', points: 100, timestamp: new Date(Date.now() - 10800000) }, { id: 4, action: 'Combo Activation', points: 15, timestamp: new Date(Date.now() - 14400000) } ]); const [availableRewards, setAvailableRewards] = useState([]); const [redeemedRewards, setRedeemedRewards] = useState([]); const [showRewardsModal, setShowRewardsModal] = useState(false); const chatEndRef = useRef(null); const lottieContainerRef = useRef(null); const animationTimeoutRef = useRef(null); // Market Analysis Engine Functions const calculateVolatilityIndex = (marketData) => { const volatilityScores = marketData.map(item => { const vol = item.volatility === 'high' ? 3 : item.volatility === 'medium' ? 2 : 1; return vol * Math.abs(item.changePercent); }); return volatilityScores.reduce((sum, score) => sum + score, 0) / volatilityScores.length; }; const calculateTrendStrength = (marketData) => { const trendScores = marketData.map(item => { const direction = item.trend === 'bullish' ? 1 : -1; return direction * Math.abs(item.changePercent); }); return Math.abs(trendScores.reduce((sum, score) => sum + score, 0)) / trendScores.length; }; const simulateNewsSentiment = () => { const sentimentFactors = [ Math.random() * 2 - 1, Math.random() * 2 - 1, Math.random() * 2 - 1, Math.random() * 2 - 1 ]; return sentimentFactors.reduce((sum, factor) => sum + factor, 0) / sentimentFactors.length; }; const calculateTechnicalIndicators = (marketData) => { const rsi = 30 + Math.random() * 40; const macd = (Math.random() - 0.5) * 2; const volume = Math.random() * 100; const supportResistance = Math.random() * 100; return { rsi, macd, volume, supportResistance }; }; const initializeAIModel = () => { const model = tf.sequential(); model.add(tf.layers.dense({ units: 64, activation: 'relu', inputShape: [7] })); model.add(tf.layers.dropout({ rate: 0.2 })); model.add(tf.layers.dense({ units: 32, activation: 'relu' })); model.add(tf.layers.dense({ units: 5, activation: 'softmax' })); model.compile({ optimizer: 'adam', loss: 'categoricalCrossentropy', metrics: ['accuracy'] }); const brainNet = new brain.NeuralNetwork({ hiddenLayers: [10, 8], activation: 'sigmoid' }); setAiModel({ tfModel: model, brainModel: brainNet }); return { tfModel: model, brainModel: brainNet }; }; const trainAIModel = async (model) => { const trainingData = []; for (let i = 0; i < 1000; i++) { const input = [ Math.random() * 10, Math.random() * 10, Math.random() * 2 - 1, Math.random() * 100, Math.random() * 2 - 1, Math.random() * 100, Math.random() * 100 ]; const output = botCombos.map((combo, index) => { let score = 0; if (input[0] > 7 && combo.marketConditions.includes('high_volatility')) score += 0.3; if (input[1] > 7 && combo.marketConditions.includes('strong_trend')) score += 0.3; if (input[2] > 0.5 && combo.riskLevel === 'high') score += 0.2; if (input[3] > 70 && combo.riskLevel === 'low') score += 0.2; return score + Math.random() * 0.1; }); trainingData.push({ input, output }); } const brainTrainingData = trainingData.map(item => ({ input: item.input, output: { marketNavigator: item.output[0], trendCatcher: item.output[1], volatilityHunter: item.output[2], precisionStriker: item.output[3], momentumRider: item.output[4] } })); model.brainModel.train(brainTrainingData, { iterations: 100, errorThresh: 0.005 }); return model; }; const analyzeMarketConditions = () => { const volatilityIndex = calculateVolatilityIndex(marketData); const trendStrength = calculateTrendStrength(marketData); const newsSentiment = simulateNewsSentiment(); const technicalIndicators = calculateTechnicalIndicators(marketData); const analysis = { volatilityIndex: volatilityIndex * 10, trendStrength: trendStrength * 10, newsSentiment: (newsSentiment + 1) * 50, rsiIndicator: technicalIndicators.rsi, macdSignal: (technicalIndicators.macd + 1) * 50, volumeProfile: technicalIndicators.volume, supportResistance: technicalIndicators.supportResistance, lastUpdate: new Date() }; setMarketAnalysisEngine(analysis); return analysis; }; const generateAIPredictions = (analysis, model) => { if (!model) return []; setIsAnalyzing(true); const inputVector = [ analysis.volatilityIndex / 100, analysis.trendStrength / 100, (analysis.newsSentiment - 50) / 50, analysis.rsiIndicator / 100, (analysis.macdSignal - 50) / 50, analysis.volumeProfile / 100, analysis.supportResistance / 100 ]; const brainPredictions = model.brainModel.run(inputVector); const recommendations = Object.entries(brainPredictions).map(([comboKey, confidence]) => { const combo = botCombos.find(c => c.id.replace('-', '').toLowerCase().includes(comboKey.toLowerCase().replace(/([A-Z])/g, '').toLowerCase()) ) || botCombos[0]; let explanation = ''; const reasons = []; if (analysis.volatilityIndex > 70) { reasons.push(`High volatility (${analysis.volatilityIndex.toFixed(1)}%) favors ${combo.name}`); } if (analysis.trendStrength > 60) { reasons.push(`Strong trend momentum (${analysis.trendStrength.toFixed(1)}%) detected`); } if (analysis.newsSentiment > 60) { reasons.push(`Positive market sentiment (${analysis.newsSentiment.toFixed(1)}%)`); } else if (analysis.newsSentiment < 40) { reasons.push(`Negative sentiment (${analysis.newsSentiment.toFixed(1)}%) requires defensive approach`); } if (analysis.rsiIndicator > 70) { reasons.push(`Overbought RSI (${analysis.rsiIndicator.toFixed(1)}) suggests reversal`); } else if (analysis.rsiIndicator < 30) { reasons.push(`Oversold RSI (${analysis.rsiIndicator.toFixed(1)}) indicates buying opportunity`); } explanation = reasons.slice(0, 2).join('. ') + '.'; return { combo, confidence: Math.min(95, Math.max(65, confidence * 100 + Math.random() * 10)), explanation, marketFactors: { volatility: analysis.volatilityIndex, trend: analysis.trendStrength, sentiment: analysis.newsSentiment, rsi: analysis.rsiIndicator } }; }); const topRecommendations = recommendations .sort((a, b) => b.confidence - a.confidence) .slice(0, 3); setAiPredictions(topRecommendations); setAnalysisConfidence(topRecommendations[0]?.confidence || 0); setIsAnalyzing(false); return topRecommendations; }; const activateSuggestedCombo = (suggestion) => { activateCombo(suggestion.combo.id); const aiMessage = { id: Date.now(), type: 'ai', content: `🤖 Activated AI-recommended "${suggestion.combo.name}" combo with ${suggestion.confidence.toFixed(1)}% confidence! ${suggestion.explanation}`, timestamp: new Date() }; setChatMessages(prev => [...prev, aiMessage]); }; // Initialize AI model on component mount useEffect(() => { const initModel = async () => { const model = initializeAIModel(); await trainAIModel(model); setAiModel(model); }; initModel(); }, []); // Run market analysis and AI predictions every 10 seconds useEffect(() => { const analysisInterval = setInterval(() => { const analysis = analyzeMarketConditions(); if (aiModel) { generateAIPredictions(analysis, aiModel); } }, 10000); const analysis = analyzeMarketConditions(); if (aiModel) { generateAIPredictions(analysis, aiModel); } return () => clearInterval(analysisInterval); }, [aiModel, marketData]); // Lottie Animation Functions const initializeLottieAnimation = (animationType) => { if (!lottieContainerRef.current) return; if (currentLottieAnimation) { currentLottieAnimation.destroy(); } lottieContainerRef.current.innerHTML = ''; const animation = lottie.loadAnimation({ container: lottieContainerRef.current, renderer: 'svg', loop: lottieAnimations[animationType].loop, autoplay: lottieAnimations[animationType].autoplay, animationData: lottieAnimations[animationType].animationData, name: animationType }); setCurrentLottieAnimation(animation); return animation; }; const playSuccessAnimation = (animationType, duration = null) => { setSuccessAnimationState(animationType); const animation = initializeLottieAnimation(animationType); if (animation) { animation.play(); if (duration) { if (animationTimeoutRef.current) { clearTimeout(animationTimeoutRef.current); } animationTimeoutRef.current = setTimeout(() => { setSuccessAnimationState('idle'); initializeLottieAnimation('idle'); }, duration); } } }; const handleTradeOutcome = (outcome) => { setLastTradeOutcome(outcome); if (outcome === 'won') { playSuccessAnimation('winning', 2000); } else if (outcome === 'lost') { playSuccessAnimation('losing', 2000); } }; const handleComboActivation = () => { playSuccessAnimation('comboActivated', 2000); }; const handleAIMessage = () => { if (successAnimationState !== 'speaking') { playSuccessAnimation('speaking', 3000); } }; // Initialize idle animation on component mount useEffect(() => { if (lottieContainerRef.current) { initializeLottieAnimation('idle'); } return () => { if (currentLottieAnimation) { currentLottieAnimation.destroy(); } if (animationTimeoutRef.current) { clearTimeout(animationTimeoutRef.current); } }; }, []); // Monitor trading activity for nervous animation useEffect(() => { const hasActiveBots = Object.values(botStatuses).some(status => status); setIsTrading(hasActiveBots); if (hasActiveBots && successAnimationState === 'idle') { if (Math.random() < 0.3) { playSuccessAnimation('nervous', 5000); } } }, [botStatuses]); // Monitor for new AI messages to trigger speaking animation useEffect(() => { const lastMessage = chatMessages[chatMessages.length - 1]; if (lastMessage && lastMessage.type === 'ai' && lastMessage.id !== 1) { handleAIMessage(); } }, [chatMessages]); // Bot Combos Functions const analyzeMarketConditionsLegacy = () => { const avgVolatility = marketData.reduce((sum, item) => { const vol = item.volatility === 'high' ? 3 : item.volatility === 'medium' ? 2 : 1; return sum + vol; }, 0) / marketData.length; const trendStrength = marketData.filter(item => Math.abs(item.changePercent) > 0.2).length; if (avgVolatility > 2.5 && trendStrength >= 3) { return 'strong_trend'; } else if (avgVolatility > 2 && trendStrength >= 2) { return 'trending'; } else if (avgVolatility > 2) { return 'high_volatility'; } else if (trendStrength <= 1) { return 'range_bound'; } else { return 'stable'; } }; const getRecommendedCombo = () => { const condition = analyzeMarketConditionsLegacy(); return botCombos.find(combo => combo.marketConditions.includes(condition) || combo.marketConditions.includes(currentMarketCondition) ) || botCombos[0]; }; const activateCombo = (comboId) => { const combo = botCombos.find(c => c.id === comboId); if (!combo) return; const newBotStatuses = Object.keys(botStatuses).reduce((acc, key) => { acc[key] = false; return acc; }, {}); combo.bots.forEach(botKey => { newBotStatuses[botKey] = true; }); setBotStatuses(newBotStatuses); setBotCombos(prev => prev.map(c => ({ ...c, active: c.id === comboId }))); handleComboActivation(); const aiMessage = { id: Date.now(), type: 'ai', content: `✅ Activated "${combo.name}" combo! This combination is optimized for current market conditions and shows an expected ${combo.expectedImprovement}% improvement in returns. The bots are now working together to maximize your profits.`, timestamp: new Date() }; setChatMessages(prev => [...prev, aiMessage]); }; // UPDATED: Enhanced activateAutoMode with trade strategy explanation const activateAutoMode = () => { setAutoModeActive(true); const recommendedCombo = getRecommendedCombo(); // Step 1: Send optimistic explanation immediately const optimisticExplanation = generateOptimisticExplanation( recommendedCombo.bots[0], marketData, userProfile, botCombos ); const optimisticMessage = { id: Date.now(), type: 'ai', content: optimisticExplanation, timestamp: new Date() }; setChatMessages(prev => [...prev, optimisticMessage]); // Trigger nervous animation for analysis phase playSuccessAnimation('nervous', 3000); // Step 2: Activate the combo activateCombo(recommendedCombo.id); // Step 3: Generate detailed explanation after a short delay (simulating analysis) setTimeout(() => { const detailedExplanation = explainTradeStrategy( recommendedCombo.bots[0], marketData, userProfile, botCombos ); const strategyMessage = { id: Date.now() + 1, type: 'ai', content: `SUCCESS: ${detailedExplanation}`, timestamp: new Date() }; setChatMessages(prev => [...prev, strategyMessage]); // Trigger nervous animation again for strategy explanation playSuccessAnimation('nervous', 2000); }, 2000); // 2 second delay for analysis const autoModeMessage = { id: Date.now() + 2, type: 'ai', content: `🤖 Auto Mode activated! I've analyzed current market conditions and selected "${recommendedCombo.name}" as the optimal combination. I'll continuously monitor performance and suggest adjustments as market conditions change.`, timestamp: new Date() }; // Add auto mode message after strategy explanation setTimeout(() => { setChatMessages(prev => [...prev, autoModeMessage]); }, 4000); }; const checkPerformanceAndAlert = () => { const dailyReturnThreshold = 0.0001; const currentReturn = portfolioData.dailyReturnRate; if (currentReturn < dailyReturnThreshold && !performanceAlert) { setPerformanceAlert({ type: 'low_performance', message: 'Performance below optimal threshold detected', recommendation: getRecommendedCombo() }); const aiMessage = { id: Date.now(), type: 'ai', content: `⚠️ I've detected sub-optimal performance (${(currentReturn * 100).toFixed(3)}% daily return). Current market conditions suggest switching to "${getRecommendedCombo().name}" combo for better results. Would you like me to activate this combination?`, timestamp: new Date() }; setChatMessages(prev => [...prev, aiMessage]); } }; // Gamification Functions const calculatePointsFromTrade = (trade) => { let points = 0; points += 5; if (trade.status === 'won') { points += Math.floor(trade.stake * 0.5); points += Math.floor(trade.payout * 0.2); } if (trade.stake >= 50) points += 10; if (trade.stake >= 100) points += 20; return Math.min(points, 200); }; const calculateDailyBonusPoints = () => { const today = new Date().toDateString(); const todayTrades = recentTrades.filter(trade => new Date(trade.timestamp || Date.now()).toDateString() === today ); let bonusPoints = 0; const dailyVolume = todayTrades.reduce((sum, trade) => sum + trade.stake, 0); if (dailyVolume >= 500) bonusPoints += 50; if (dailyVolume >= 1000) bonusPoints += 100; const wins = todayTrades.filter(trade => trade.status === 'won').length; const winRate = todayTrades.length > 0 ? (wins / todayTrades.length) * 100 : 0; if (winRate >= 70) bonusPoints += 30; if (winRate >= 80) bonusPoints += 60; if (winRate >= 90) bonusPoints += 100; return bonusPoints; }; const updateUserPoints = (pointsToAdd, action) => { setUserProfile(prev => { const newTotalPoints = prev.totalPoints + pointsToAdd; const currentTierData = rewardsTiers.find(tier => newTotalPoints >= tier.minPoints && newTotalPoints <= tier.maxPoints ); const nextTierData = rewardsTiers.find(tier => tier.minPoints > newTotalPoints); return { ...prev, totalPoints: newTotalPoints, currentTier: currentTierData?.name || 'Diamond', nextTier: nextTierData?.name || 'Diamond', pointsToNextTier: nextTierData ? nextTierData.minPoints - newTotalPoints : 0 }; }); setPointsHistory(prev => [{ id: Date.now(), action, points: pointsToAdd, timestamp: new Date() }, ...prev.slice(0, 19)]); const aiMessage = { id: Date.now(), type: 'ai', content: `🎉 You earned ${pointsToAdd} points for "${action}"! Total: ${userProfile.totalPoints + pointsToAdd} points`, timestamp: new Date() }; setChatMessages(prev => [...prev, aiMessage]); }; const getCurrentTierData = () => { return rewardsTiers.find(tier => tier.name === userProfile.currentTier) || rewardsTiers[0]; }; const getAvailableRewardsForTier = () => { const currentTier = getCurrentTierData(); const tierIndex = rewardsTiers.findIndex(tier => tier.name === currentTier.name); const availableRewards = []; for (let i = 0; i <= tierIndex; i++) { availableRewards.push(...rewardsTiers[i].rewards); } return availableRewards.filter(reward => reward.pointsCost <= userProfile.totalPoints); }; const redeemReward = (reward) => { if (reward.pointsCost > userProfile.totalPoints) return; setUserProfile(prev => ({ ...prev, totalPoints: prev.totalPoints - reward.pointsCost })); setRedeemedRewards(prev => [{ ...reward, redeemedAt: new Date(), id: Date.now() }, ...prev]); const aiMessage = { id: Date.now(), type: 'ai', content: `🎁 Reward redeemed! You've claimed ${reward.type === 'gift_card' ? `$${reward.value} ${reward.provider} Gift Card` : reward.value} for ${reward.pointsCost} points. Check your email for details!`, timestamp: new Date() }; setChatMessages(prev => [...prev, aiMessage]); }; // Initialize combo performance data useEffect(() => { const initializeComboPerformance = () => { const initialData = {}; const initialHistory = {}; botCombos.forEach(combo => { const historyPoints = []; const now = new Date(); for (let i = 23; i >= 0; i--) { const timestamp = new Date(now.getTime() - i * 60 * 60 * 1000); const baseValue = combo.expectedImprovement * 10; const variance = (Math.random() - 0.5) * baseValue * 0.3; historyPoints.push({ x: timestamp, y: Math.max(0, baseValue + variance), pnl: baseValue + variance, winRate: Math.min(100, Math.max(0, combo.winRate + (Math.random() - 0.5) * 10)), trades: Math.floor(Math.random() * 20) + 5, timestamp: timestamp.toISOString() }); } initialHistory[combo.id] = historyPoints; initialData[combo.id] = { totalPnL: historyPoints.reduce((sum, point) => sum + point.pnl, 0), winRate: historyPoints[historyPoints.length - 1]?.winRate || combo.winRate, totalTrades: historyPoints.reduce((sum, point) => sum + point.trades, 0), currentStreak: Math.floor(Math.random() * 10) + 1, lastUpdate: new Date() }; }); setPerformanceHistory(initialHistory); setComboPerformanceData(initialData); }; initializeComboPerformance(); }, []); // Update combo performance data every 5 seconds const updateComboPerformance = () => { setComboPerformanceData(prev => { const updated = { ...prev }; botCombos.forEach(combo => { if (combo.active) { const currentData = updated[combo.id] || {}; const pnlChange = (Math.random() - 0.4) * 50; const winRateChange = (Math.random() - 0.5) * 2; const newTrades = Math.random() < 0.3 ? Math.floor(Math.random() * 3) + 1 : 0; updated[combo.id] = { ...currentData, totalPnL: (currentData.totalPnL || 0) + pnlChange, winRate: Math.min(100, Math.max(0, (currentData.winRate || combo.winRate) + winRateChange)), totalTrades: (currentData.totalTrades || 0) + newTrades, lastUpdate: new Date() }; } }); return updated; }); setPerformanceHistory(prev => { const updated = { ...prev }; const now = new Date(); botCombos.forEach(combo => { if (combo.active && updated[combo.id]) { const currentData = comboPerformanceData[combo.id]; if (currentData) { const newPoint = { x: now, y: currentData.totalPnL || 0, pnl: currentData.totalPnL || 0, winRate: currentData.winRate || combo.winRate, trades: currentData.totalTrades || 0, timestamp: now.toISOString() }; updated[combo.id] = [...(updated[combo.id] || []), newPoint].slice(-24); } } }); return updated; }); }; // UPDATED: Enhanced interval with trade strategy explanations for automated trades useEffect(() => { const interval = setInterval(() => { setMarketData(prev => prev.map(item => ({ ...item, price: item.price + (Math.random() - 0.5) * 0.01, change: (Math.random() - 0.5) * 0.01, changePercent: (Math.random() - 0.5) * 1 }))); setCurrentMarketCondition(analyzeMarketConditionsLegacy()); if (Math.random() < 0.1) { checkPerformanceAndAlert(); } updateComboPerformance(); // Check for daily bonus points if (Math.random() < 0.05) { const bonusPoints = calculateDailyBonusPoints(); if (bonusPoints > 0) { updateUserPoints(bonusPoints, 'Daily Performance Bonus'); } } // UPDATED: Enhanced automated trade simulation with strategy explanations if (Math.random() < 0.05 && isTrading && autoModeActive) { const outcome = Math.random() > 0.6 ? 'won' : 'lost'; // Get the active bot for strategy explanation const activeCombo = botCombos.find(combo => combo.active); const currentActiveBot = activeCombo ? activeCombo.bots[0] : Object.keys(botStatuses).find(key => botStatuses[key]) || 'digits'; // Generate strategy explanation before trade execution const strategyExplanation = explainTradeStrategy( currentActiveBot, marketData, userProfile, botCombos ); const strategyMessage = { id: Date.now(), type: 'ai', content: `SUCCESS: ${strategyExplanation}`, timestamp: new Date() }; setChatMessages(prev => [...prev, strategyMessage]); // Trigger nervous animation for strategy explanation playSuccessAnimation('nervous', 2000); // Execute trade after explanation setTimeout(() => { handleTradeOutcome(outcome); if (Math.random() < 0.3) { const simulatedTrade = { stake: Math.floor(Math.random() * 50) + 10, status: outcome, payout: outcome === 'won' ? (Math.floor(Math.random() * 50) + 10) * 1.8 : 0 }; const points = calculatePointsFromTrade(simulatedTrade); updateUserPoints(points, 'Automated Trade'); } }, 1500); } }, 3000); return () => clearInterval(interval); }, [isTrading, comboPerformanceData, autoModeActive, botStatuses, marketData, userProfile, botCombos]); useEffect(() => { chatEndRef.current?.scrollIntoView({ behavior: 'smooth' }); }, [chatMessages]); // Helper function to get chart data based on selected metric and time range const getChartData = (comboId) => { const history = performanceHistory[comboId] || []; const now = new Date(); let filteredHistory = history; switch (performanceTimeRange) { case 'hours': filteredHistory = history.filter(point => new Date(point.timestamp).getTime() > now.getTime() - 24 * 60 * 60 * 1000 ); break; case 'days': filteredHistory = history.filter(point => new Date(point.timestamp).getTime() > now.getTime() - 7 * 24 * 60 * 60 * 1000 ); break; case 'weeks': filteredHistory = history.filter(point => new Date(point.timestamp).getTime() > now.getTime() - 30 * 24 * 60 * 60 * 1000 ); break; } return filteredHistory.map((point, index) => ({ x: index, y: performanceMetric === 'pnl' ? point.pnl : performanceMetric === 'winRate' ? point.winRate : point.trades, label: `${performanceMetric === 'pnl' ? '$' : performanceMetric === 'winRate' ? '%' : ''}${point[performanceMetric]?.toFixed(2) || 0}` })); }; const toggleBot = (botName) => { setBotStatuses(prev => ({ ...prev, [botName]: !prev[botName] })); setBotCombos(prev => prev.map(c => ({ ...c, active: false }))); setAutoModeActive(false); }; const toggleTeachMode = () => { setIsTeachMode(!isTeachMode); if (!isTeachMode) { console.log('Entering Teach Mode - Recording trades for personalized AI'); } }; // UPDATED: Enhanced manual trade execution with strategy explanation const executeManualTrade = async () => { const tradeData = { id: Date.now(), ...manualTradeForm, timestamp: new Date(), marketConditions: { price: marketData.find(m => m.symbol === manualTradeForm.symbol)?.price, volatility: Math.random() * 100, trend: Math.random() > 0.5 ? 'bullish' : 'bearish', rsi: Math.random() * 100, macd: (Math.random() - 0.5) * 2 }, outcome: null }; // Generate strategy explanation before trade execution const strategyExplanation = explainTradeStrategy( manualTradeForm.tradeType, marketData, userProfile, botCombos ); const strategyMessage = { id: Date.now(), type: 'ai', content: `SUCCESS: ${strategyExplanation}`, timestamp: new Date() }; setChatMessages(prev => [...prev, strategyMessage]); // Trigger nervous animation for strategy explanation playSuccessAnimation('nervous', 2000); setRecordedTrades(prev => [...prev, tradeData]); setTeachBotData(prev => ({ ...prev, tradesRecorded: prev.tradesRecorded + 1 })); setTimeout(() => { const outcome = Math.random() > 0.4 ? 'win' : 'loss'; const payout = outcome === 'win' ? manualTradeForm.stake * 1.8 : 0; const completedTrade = { ...tradeData, outcome, payout, status: outcome === 'win' ? 'won' : 'lost' }; setRecordedTrades(prev => prev.map(trade => trade.id === tradeData.id ? completedTrade : trade ) ); setRecentTrades(prev => [{ id: tradeData.id, type: manualTradeForm.tradeType, symbol: manualTradeForm.symbol, stake: manualTradeForm.stake, payout: payout, status: outcome === 'win' ? 'won' : 'lost', time: new Date().toLocaleTimeString().slice(0, 5) }, ...prev.slice(0, 3)]); const pointsEarned = calculatePointsFromTrade(completedTrade); updateUserPoints(pointsEarned, `${outcome === 'win' ? 'Winning' : 'Completed'} Trade`); handleTradeOutcome(outcome === 'win' ? 'won' : 'lost'); if (teachBotData.tradesRecorded >= 10 && teachBotData.trainingStatus === 'idle') { trainPersonalizedModel(); } }, 5000); setManualTradeForm(prev => ({ ...prev, stake: 10 })); }; const trainPersonalizedModel = async () => { setTeachBotData(prev => ({ ...prev, trainingStatus: 'training' })); setModelTrainingProgress(0); const trainingInterval = setInterval(() => { setModelTrainingProgress(prev => { if (prev >= 100) { clearInterval(trainingInterval); setTeachBotData(prevData => ({ ...prevData, trainingStatus: 'ready', modelAccuracy: 75 + Math.random() * 20, lastTraining: new Date() })); return 100; } return prev + 10; }); }, 500); }; const deployPersonalizedBot = () => { setTeachBotData(prev => ({ ...prev, trainingStatus: 'deployed', personalizedBotActive: true })); }; const togglePersonalizedBot = () => { setTeachBotData(prev => ({ ...prev, personalizedBotActive: !prev.personalizedBotActive })); }; const sendMessage = async () => { if (!chatInput.trim()) return; const userMessage = { id: Date.now(), type: 'user', content: chatInput, timestamp: new Date() }; setChatMessages(prev => [...prev, userMessage]); setChatInput(''); setTimeout(() => { let aiResponse = ''; if (chatInput.toLowerCase().includes('combo') || chatInput.toLowerCase().includes('combination')) { const recommended = getRecommendedCombo(); aiResponse = `Based on current market analysis, I recommend the "${recommended.name}" combo. It's showing ${recommended.expectedImprovement}% expected improvement with a ${recommended.winRate}% win rate. This combination works best in ${recommended.marketConditions.join(' and ')} conditions. Would you like me to activate it?`; } else if (chatInput.toLowerCase().includes('performance') || chatInput.toLowerCase().includes('return')) { aiResponse = `Your current daily return rate is ${(portfolioData.dailyReturnRate * 100).toFixed(3)}%. For optimal performance, I suggest maintaining above 0.01% daily returns. Current market conditions favor trend-following strategies.`; } else if (chatInput.toLowerCase().includes('analysis') || chatInput.toLowerCase().includes('market')) { aiResponse = `Current market analysis shows: Volatility at ${marketAnalysisEngine.volatilityIndex.toFixed(1)}%, Trend strength at ${marketAnalysisEngine.trendStrength.toFixed(1)}%, and News sentiment at ${marketAnalysisEngine.newsSentiment.toFixed(1)}%. My AI model recommends ${aiPredictions[0]?.combo.name || 'Market Navigator'} with ${aiPredictions[0]?.confidence.toFixed(1) || '85'}% confidence.`; } else { aiResponse = 'I understand your query. Based on current market analysis, I recommend focusing on EUR/USD volatility trades. The RSI indicates oversold conditions with potential for reversal. Would you like me to adjust your bot parameters accordingly?'; } const aiMessage = { id: Date.now() + 1, type: 'ai', content: aiResponse, timestamp: new Date() }; setChatMessages(prev => [...prev, aiMessage]); }, 1500); }; const botTypes = [ { key: 'digits', name: 'Digits', description: 'Predict last digit' }, { key: 'updown', name: 'Up/Down', description: 'Price direction' }, { key: 'inout', name: 'In/Out', description: 'Barrier trading' }, { key: 'accumulators', name: 'Accumulators', description: 'Growth potential' }, { key: 'multipliers', name: 'Multipliers', description: 'Leveraged trading' }, { key: 'asians', name: 'Asians', description: 'Average pricing' }, { key: 'reset', name: 'Reset Call/Put', description: 'Reset barriers' }, { key: 'highlowTicks', name: 'High/Low Ticks', description: 'Tick analysis' }, { key: 'onlyUps', name: 'Only Ups/Downs', description: 'Directional only' }, { key: 'vanillas', name: 'Vanillas', description: 'Standard options' }, { key: 'turbos', name: 'Turbos', description: 'Fast execution' }, { key: 'touch', name: 'Touch/No Touch', description: 'Barrier touch' } ]; const hasActiveBots = Object.values(botStatuses).some(status => status); const hasActiveCombo = botCombos.some(combo => combo.active); // Add Rewards Modal Component const RewardsModal = () => { const currentTierData = getCurrentTierData(); const availableRewards = getAvailableRewardsForTier(); return (

Rewards Store

{availableRewards.map((reward, index) => (
{reward.type === 'gift_card' && '🎁'} {reward.type === 'cash_bonus' && '💰'} {reward.type === 'merchandise' && '👕'} {reward.type === 'trading_credit' && '💳'} {reward.type === 'exclusive' && '⭐'}
Cost
{reward.pointsCost} pts

{reward.type === 'gift_card' && `$${reward.value} ${reward.provider} Gift Card`} {reward.type === 'cash_bonus' && `$${reward.value} Cash Bonus`} {reward.type === 'trading_credit' && `$${reward.value} Trading Credit`} {reward.type !== 'gift_card' && reward.type !== 'cash_bonus' && reward.type !== 'trading_credit' && reward.value}

))}
); }; return (
{/* Top Navigation Bar - 10% height */}
OmniTrade Logo
Live Trading Active {autoModeActive && ( AUTO MODE )} {isAnalyzing && ( AI ANALYZING )}
Portfolio Balance
${portfolioData.balance.toLocaleString()}
{getCurrentTierData().icon} {userProfile.currentTier} Tier
{userProfile.totalPoints.toLocaleString()} pts
{userProfile.pointsToNextTier > 0 ? `${userProfile.pointsToNextTier} to ${userProfile.nextTier}` : 'Max Tier'}
{performanceAlert && (
Performance Alert
)}
{/* Left Sidebar - Bot Controls - 20% width */}
); }; // UI STARTS HERE return (
OmniTrade Logo
Live Trading Active {autoModeActive && ( AUTO MODE )} {isAnalyzing && ( AI ANALYZING )}
Portfolio Balance
${portfolioData.balance.toLocaleString()}
{getCurrentTierData().icon} {userProfile.currentTier} Tier
{userProfile.totalPoints.toLocaleString()} pts
{userProfile.pointsToNextTier > 0 ? `${userProfile.pointsToNextTier} to ${userProfile.nextTier}` : 'Max Tier'}
{performanceAlert && (
Performance Alert
)}
{/* LEFT SIDEBAR, MAIN DASHBOARD, ETC. */} {/* Left Sidebar - placeholder for the left nav content */} {/* Main Content - placeholder for central dashboard/chart/etc. */}
{/* Could add charts, trade forms, AI, etc. */}

OmniTrade Dashboard

Welcome back! Monitor your active bots, manage combos, execute trades, and track points to unlock exclusive rewards.

{/* Right Panel - Trade History and Performance - 20% width */}
{/* Place RewardsModal at the end of the component */} {showRewardsModal && }
); }; export default OmniTradeDashboard;