import gradio as gr import pandas as pd import numpy as np import yfinance as yf import plotly.graph_objects as go from plotly.subplots import make_subplots from datetime import datetime, timedelta import time import warnings from config import Config warnings.filterwarnings('ignore') # Load configuration config = Config() class RealTimeCryptoData: def __init__(self, symbols=config.DEFAULT_SYMBOLS): self.symbols = symbols[:config.MAX_SYMBOLS] self.crypto_names = config.CRYPTO_NAMES self.crypto_colors = config.CRYPTO_COLORS self.base_prices = config.BASE_PRICES self.volatility_settings = config.VOLATILITY self.market_cap_multipliers = config.MARKET_CAP_MULTIPLIERS self.last_prices = {} self.data_history = {symbol: [] for symbol in self.symbols} self.confidence_history = {symbol: [] for symbol in self.symbols} self.timestamps = [] self.update_counter = 0 # Initialize prices with config base prices for symbol in self.symbols: base_price = self.base_prices.get(symbol, np.random.uniform(0.1, 50000)) self.last_prices[symbol] = base_price self.data_history[symbol] = [base_price] self.confidence_history[symbol] = [] self.timestamps = [datetime.now().strftime('%H:%M:%S')] def generate_live_data(self): """Generate realistic live crypto market data""" self.update_counter += 1 current_time = datetime.now() # Add new timestamp self.timestamps.append(current_time.strftime('%H:%M:%S')) if len(self.timestamps) > 20: self.timestamps.pop(0) live_data = {} for symbol in self.symbols: # Generate realistic crypto price movement with config volatility volatility = self.volatility_settings.get(symbol, 2.0) change_pct = np.random.normal(0, volatility) new_price = self.last_prices[symbol] * (1 + change_pct/100) self.last_prices[symbol] = max(new_price, 0.0001) # Prevent negative prices # Add to history self.data_history[symbol].append(new_price) if len(self.data_history[symbol]) > 20: self.data_history[symbol].pop(0) # Calculate metrics current_timestamps = self.timestamps[-len(self.data_history[symbol]):] change = ((new_price - self.data_history[symbol][0]) / self.data_history[symbol][0]) * 100 live_data[symbol] = { 'name': self.crypto_names.get(symbol, symbol), 'prices': self.data_history[symbol].copy(), 'timestamps': current_timestamps, 'current_price': new_price, 'change': change, 'volume': np.random.randint(10000000, 500000000), 'market_cap': new_price * self.market_cap_multipliers.get(symbol, 1000000), 'update_count': self.update_counter, 'last_updated': current_time.strftime('%H:%M:%S'), 'color': self.crypto_colors.get(symbol, '#666666') } return live_data class AI_CryptoAgents: def __init__(self): self.agents = { 'research': {'name': 'Research Agent', 'emoji': '📊'}, 'technical': {'name': 'Technical Agent', 'emoji': '📈'}, 'risk': {'name': 'Risk Agent', 'emoji': '🛡️'}, 'decision': {'name': 'Decision Engine', 'emoji': '🎯'} } def analyze_crypto(self, symbol, crypto_data): if symbol not in crypto_data: return self._get_error_analysis(symbol) data = crypto_data[symbol] current_price = data['current_price'] change = data['change'] volatility = abs(change) crypto_name = data['name'] analyses = {} # Research Agent - Fundamental Analysis for Crypto if change > 5: research_text = f"""**Fundamental Analysis - Strong Bullish Momentum** 🚀 • Adoption increasing rapidly • Institutional investment growing • Strong network activity • Positive regulatory developments **Recommendation: BUY** (82% confidence) **Price Target: ${current_price * 1.20:.2f}**""" research_conf = 82 elif change < -5: research_text = f"""**Fundamental Analysis - Market Correction** 📉 • Short-term selling pressure • Monitor support levels • Good accumulation zone • Long-term fundamentals intact **Recommendation: HOLD** (75% confidence)""" research_conf = 75 else: research_text = f"""**Fundamental Analysis - Consolidation Phase** ⚖️ • Steady network growth • Development activity strong • Market sentiment neutral • Accumulation opportunity **Recommendation: HOLD** (78% confidence)""" research_conf = 78 analyses['research'] = { 'emoji': '📊', 'title': 'Fundamental Analysis', 'analysis': research_text, 'confidence': research_conf } # Technical Agent - Crypto Technical Analysis rsi_level = "Overbought" if change > 5 else "Oversold" if change < -5 else "Neutral" trend = "Bullish" if change > 0 else "Bearish" # Crypto-specific support/resistance levels support_resistance_multipliers = { 'BTC-USD': (0.92, 1.08), 'ETH-USD': (0.90, 1.10), 'XRP-USD': (0.88, 1.12), 'ADA-USD': (0.85, 1.15), 'DOGE-USD': (0.80, 1.20), 'SOL-USD': (0.87, 1.13) } support_mult, resistance_mult = support_resistance_multipliers.get( symbol, (0.90, 1.10) ) support = current_price * support_mult resistance = current_price * resistance_mult analyses['technical'] = { 'emoji': '📈', 'title': 'Technical Analysis', 'analysis': f"""**{rsi_level} Conditions - {trend} Trend** • Current Price: ${current_price:.2f} • 24h Change: {change:+.2f}% • Key Levels: - Support: ${support:.2f} - Resistance: ${resistance:.2f} • RSI: {68 if change > 0 else 32} ({rsi_level}) • Volume: {data['volume']:,}""", 'confidence': 76 } # Risk Agent - Crypto Risk Management (higher volatility) if volatility > 8: risk_level = "VERY HIGH" position_size = "0.5-1%" stop_loss = "15%" elif volatility > 5: risk_level = "HIGH" position_size = "1-2%" stop_loss = "12%" elif volatility > 3: risk_level = "MEDIUM" position_size = "2-3%" stop_loss = "10%" else: risk_level = "LOW" position_size = "3-5%" stop_loss = "8%" analyses['risk'] = { 'emoji': '🛡️', 'title': 'Risk Assessment', 'analysis': f"""**{risk_level} RISK PROFILE** ⚠️ • Volatility: {volatility:.1f}% • Position Size: {position_size} • Stop-Loss: {stop_loss} • Risk-Reward: 1:{2 if risk_level in ['HIGH', 'VERY HIGH'] else 3} • 24h Range: ±{volatility:.1f}%""", 'confidence': 78 } # Decision Engine - Final Decision for Crypto if change > 4 and volatility < 7: decision = "BUY" confidence = 80 reason = "Strong uptrend with manageable volatility" elif change < -4: decision = "SELL" confidence = 75 reason = "Downtrend confirmed, wait for better entry" else: decision = "HOLD" confidence = 74 reason = "Market consolidating, wait for clear direction" analyses['decision'] = { 'emoji': '🎯', 'title': 'Trading Decision', 'analysis': f"""**FINAL DECISION: {decision}** 🎯 **Confidence:** {confidence}% **Price:** ${current_price:.2f} **24h Change:** {change:+.2f}% **Action:** {reason}""", 'confidence': confidence, 'decision': decision } return analyses def _get_error_analysis(self, symbol): error_msg = "Crypto data temporarily unavailable." return { 'research': {'emoji': '📊', 'title': 'Research', 'analysis': error_msg, 'confidence': 0}, 'technical': {'emoji': '📈', 'title': 'Technical', 'analysis': error_msg, 'confidence': 0}, 'risk': {'emoji': '🛡️', 'title': 'Risk', 'analysis': error_msg, 'confidence': 0}, 'decision': {'emoji': '🎯', 'title': 'Decision', 'analysis': error_msg, 'confidence': 0, 'decision': 'HOLD'} } # Initialize components crypto_data = RealTimeCryptoData() crypto_agents = AI_CryptoAgents() def create_live_crypto_chart(): """Create live crypto price movement chart""" live_data = crypto_data.generate_live_data() fig = go.Figure() for symbol, data in live_data.items(): fig.add_trace(go.Scatter( x=data['timestamps'], y=data['prices'], mode='lines+markers', name=data['name'], line=dict(color=data['color'], width=3), marker=dict(size=6), hovertemplate=f'{data["name"]}
%{{x}}
$%{{y:.2f}}' )) fig.update_layout( title=f"₿ Live Crypto Prices - Update #{crypto_data.update_counter}", template='plotly_dark', height=config.CHART_HEIGHT, xaxis_title="Time", yaxis_title="Price ($)", showlegend=True ) return fig def create_crypto_confidence_chart(symbol_input=""): """Create AI agents confidence comparison chart for crypto""" live_data = crypto_data.generate_live_data() if not symbol_input: symbol = 'BTC-USD' else: symbol = config.SYMBOL_MAPPING.get(symbol_input.upper(), 'BTC-USD') if symbol not in live_data: symbol = 'BTC-USD' analysis = crypto_agents.analyze_crypto(symbol, live_data) agents = list(analysis.keys()) confidences = [analysis[agent]['confidence'] for agent in agents] colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4'] fig = go.Figure() fig.add_trace(go.Bar( x=[analysis[agent]['title'] for agent in agents], y=confidences, marker_color=colors, text=[f"{c}%" for c in confidences], textposition='auto', hovertemplate='%{x}
Confidence: %{y}%' )) crypto_name = live_data[symbol]['name'] if symbol in live_data else 'Crypto' fig.update_layout( title=f"🤖 AI Agents Confidence - {crypto_name}", template='plotly_dark', height=config.CHART_HEIGHT, xaxis_title="AI Agents", yaxis_title="Confidence Level (%)", yaxis_range=[0, 100] ) return fig def create_crypto_sentiment_chart(): """Create crypto market sentiment pie chart""" live_data = crypto_data.generate_live_data() decisions = {'BUY': 0, 'SELL': 0, 'HOLD': 0} for symbol in live_data.keys(): analysis = crypto_agents.analyze_crypto(symbol, live_data) decision = analysis['decision']['decision'] decisions[decision] += 1 fig = go.Figure() fig.add_trace(go.Pie( labels=list(decisions.keys()), values=list(decisions.values()), hole=0.4, marker_colors=['#00CC96', '#EF553B', '#636EFA'], hovertemplate='%{label}
%{value} cryptocurrencies' )) fig.update_layout( title="🎯 Crypto Market Sentiment - AI Recommendations", template='plotly_dark', height=config.CHART_HEIGHT ) return fig def create_crypto_performance_chart(): """Create crypto performance comparison chart""" live_data = crypto_data.generate_live_data() names = [live_data[symbol]['name'] for symbol in live_data.keys()] changes = [live_data[symbol]['change'] for symbol in live_data.keys()] prices = [live_data[symbol]['current_price'] for symbol in live_data.keys()] colors = [live_data[symbol]['color'] for symbol in live_data.keys()] fig = make_subplots( rows=1, cols=2, subplot_titles=['24h Performance (%)', 'Current Prices ($)'], specs=[[{"type": "bar"}, {"type": "bar"}]] ) # Performance bars fig.add_trace(go.Bar( x=names, y=changes, name='24h Change', marker_color=['#00CC96' if c > 0 else '#EF553B' for c in changes], text=[f"{c:+.2f}%" for c in changes], textposition='auto' ), row=1, col=1) # Price bars fig.add_trace(go.Bar( x=names, y=prices, name='Current Price', marker_color=colors, text=[f"${p:.2f}" for p in prices], textposition='auto' ), row=1, col=2) fig.update_layout( title="📊 Crypto Performance Overview", template='plotly_dark', height=config.CHART_HEIGHT, showlegend=False ) return fig def get_crypto_ai_analysis(symbol_input=""): """Get detailed crypto analysis from all AI agents""" live_data = crypto_data.generate_live_data() if not symbol_input: supported_cryptos = ", ".join([f"{name} ({sym.replace('-USD', '')})" for sym, name in config.CRYPTO_NAMES.items()]) return f"""# 🤖 AI Crypto Analysis **Please enter a crypto symbol to see detailed analysis** **Supported Cryptocurrencies:** {supported_cryptos} **Examples:** BTC, ETH, XRP, ADA, DOGE, SOL""" symbol = config.SYMBOL_MAPPING.get(symbol_input.upper(), symbol_input.upper() + '-USD') if symbol not in live_data: supported = ", ".join(config.SYMBOL_MAPPING.keys()) return f"""# ❌ Crypto Not Found '{symbol_input}' not in tracked cryptocurrencies. **Supported symbols:** {supported}""" analysis = crypto_agents.analyze_crypto(symbol, live_data) crypto_name = live_data[symbol]['name'] data = live_data[symbol] detailed_report = f""" # 🤖 AI Crypto Analysis - {crypto_name} ({symbol.replace('-USD', '')}) **Current Price:** ${data['current_price']:.2f} **24h Change:** {data['change']:+.2f}% **Market Cap:** ${data['market_cap']:,.0f} **Volume (24h):** {data['volume']:,} **Last Update:** {datetime.now().strftime('%H:%M:%S')} --- ## {analysis['research']['emoji']} {analysis['research']['title']} **Confidence:** {analysis['research']['confidence']}% {analysis['research']['analysis']} --- ## {analysis['technical']['emoji']} {analysis['technical']['title']} **Confidence:** {analysis['technical']['confidence']}% {analysis['technical']['analysis']} --- ## {analysis['risk']['emoji']} {analysis['risk']['title']} **Confidence:** {analysis['risk']['confidence']}% {analysis['risk']['analysis']} --- ## {analysis['decision']['emoji']} {analysis['decision']['title']} **Confidence:** {analysis['decision']['confidence']}% {analysis['decision']['analysis']} """ return detailed_report # Create the crypto interface with gr.Blocks(theme=gr.themes.Soft(), title=config.TITLE) as demo: gr.Markdown(f""" # {config.TITLE} ## *{config.DESCRIPTION}* **Tracking:** {", ".join([config.CRYPTO_NAMES[sym] for sym in config.DEFAULT_SYMBOLS])} **Auto-Refresh:** Every {config.UPDATE_INTERVAL} seconds """) with gr.Row(): with gr.Column(scale=1): crypto_input = gr.Textbox( label="Crypto Symbol", placeholder="BTC, ETH, XRP, ADA, DOGE, SOL...", max_lines=1 ) gr.Markdown(f""" **Supported Cryptos:** {''.join([f"• {name} ({sym.replace('-USD', '')})
" for sym, name in config.CRYPTO_NAMES.items()])} **Features:** • Live price tracking • AI-powered analysis • Risk assessment • Trading signals • Real-time market sentiment """) with gr.Tabs(): with gr.TabItem("📈 Live Crypto Charts"): with gr.Row(): crypto_price_chart = gr.Plot( label="Live Crypto Prices", every=config.UPDATE_INTERVAL, value=create_live_crypto_chart ) with gr.Row(): crypto_confidence_chart = gr.Plot( label="AI Agents Confidence", every=config.UPDATE_INTERVAL, value=lambda: create_crypto_confidence_chart( crypto_input.value if crypto_input.value else "" ) ) with gr.Row(): crypto_sentiment_chart = gr.Plot( label="Crypto Market Sentiment", every=config.UPDATE_INTERVAL, value=create_crypto_sentiment_chart ) crypto_performance_chart = gr.Plot( label="Crypto Performance", every=config.UPDATE_INTERVAL, value=create_crypto_performance_chart ) with gr.TabItem("🤖 AI Crypto Analysis"): with gr.Row(): crypto_analysis = gr.Markdown( label="AI Crypto Analysis", every=config.UPDATE_INTERVAL, value=get_crypto_ai_analysis ) gr.Markdown(f""" --- **🔄 Live Crypto Dashboard Active** • **Last Update:** {datetime.now().strftime('%H:%M:%S')} *All charts and analysis update automatically every {config.UPDATE_INTERVAL} seconds* *Note: This is a simulation for demonstration purposes. Always do your own research before trading.* """) # Update confidence chart when crypto symbol changes crypto_input.change( fn=lambda s: create_crypto_confidence_chart(s), inputs=[crypto_input], outputs=[crypto_confidence_chart] ) crypto_input.change( fn=get_crypto_ai_analysis, inputs=[crypto_input], outputs=[crypto_analysis] ) # Launch the app if __name__ == "__main__": demo.launch(share=True)