import gradio as gr import requests import pandas as pd import plotly.graph_objs as go from datetime import datetime, timedelta # Fallback data for demonstration purposes fallback_historical_data = { 'bitcoin': [ [1633046400000, 42000], [1633132800000, 42250], [1633219200000, 41500], [1633305600000, 43000], [1633392000000, 43500], [1633478400000, 44000] ] } fallback_current_prices = { 'bitcoin': 42000, 'ethereum': 3100, 'binancecoin': 380 } # Function to fetch current price from CoinGecko with fallback to CryptoCompare def fetch_current_price(coin_id): # Mapping between CoinGecko and CryptoCompare coin symbols compare_symbol_map = { 'bitcoin': 'BTC', 'ethereum': 'ETH', 'binancecoin': 'BNB', } # API URLs gecko_url = f"https://api.coingecko.com/api/v3/simple/price?ids={coin_id}&vs_currencies=usd" compare_url = f"https://min-api.cryptocompare.com/data/price?fsym={compare_symbol_map.get(coin_id, 'BTC')}&tsyms=USD" try: # Try fetching from CoinGecko first response = requests.get(gecko_url, timeout=10) response.raise_for_status() data = response.json() return f"${data[coin_id]['usd']:.2f} (from CoinGecko)" except requests.exceptions.RequestException as gecko_error: print(f"Error fetching price from CoinGecko: {gecko_error}") # Try CryptoCompare as fallback try: response = requests.get(compare_url, timeout=10) response.raise_for_status() data = response.json() return f"${data['USD']:.2f} (from CryptoCompare)" except requests.exceptions.RequestException as compare_error: print(f"Error fetching price from CryptoCompare: {compare_error}") return "Price data not available" # Function to fetch historical price data from CoinGecko def fetch_historical_data(coin_id, from_timestamp, to_timestamp): url = f"https://api.coingecko.com/api/v3/coins/{coin_id}/market_chart/range?vs_currency=usd&from={from_timestamp}&to={to_timestamp}" try: response = requests.get(url, timeout=10) response.raise_for_status() data = response.json() return data['prices'] except requests.exceptions.RequestException as e: print(f"Error fetching historical data: {e}") return fallback_historical_data.get(coin_id, f"Error fetching historical data for {coin_id}") # Convert date string to timestamp def date_to_timestamp(date_str): return int(pd.Timestamp(date_str).timestamp()) # Function to plot historical prices using Plotly def plot_historical_prices(coin_name, days_back): try: # Set dynamic date range: from X days ago to today to_date = datetime.now() from_date = to_date - timedelta(days=days_back) from_timestamp = int(from_date.timestamp()) to_timestamp = int(to_date.timestamp()) prices = fetch_historical_data(coin_name, from_timestamp, to_timestamp) if isinstance(prices, str): return prices df = pd.DataFrame(prices, columns=['timestamp', 'price']) df['date'] = pd.to_datetime(df['timestamp'], unit='ms') fig = go.Figure() fig.add_trace(go.Scatter(x=df['date'], y=df['price'], mode='lines', name=coin_name)) fig.update_layout(title=f'{coin_name.capitalize()} Prices (Last {days_back} Days)', xaxis_title='Date', yaxis_title='Price (USD)') return fig except Exception as e: return f"Error in plotting chart: {e}" # Function to fetch real-time trade data from CoinGecko def fetch_real_time_trade_data(coin_id): fallback_data = {'bitcoin': [1633039200000, 42000]} gecko_url = f"https://api.coingecko.com/api/v3/coins/{coin_id}/market_chart?vs_currency=usd&days=1" try: response = requests.get(gecko_url, timeout=10) response.raise_for_status() data = response.json() return data['prices'][-1] # Latest price data except requests.exceptions.RequestException as e: print(f"Error fetching real-time trade data: {e}") return fallback_data.get(coin_id, "Trade data not available") # Function to display real-time trade data def real_time_trade_dashboard(coin): try: data = fetch_real_time_trade_data(coin) return f"The latest trade data for {coin.capitalize()}: ${data[1]}" except Exception as e: return f"Error in real-time trade dashboard: {e}" # AI BTC Analysis (mocked for demo) def btc_analysis(): return """ AI BTC Analysis: - Order book analysis: Buying pressure above, selling pressure below. - Technical analysis: Divergence detected, RSI showing overbought. - Funding rate: Higher on longs, suggesting bullish sentiment. - On-chain analysis: Ichimoku cloud shows potential reversal. - News analysis: Positive sentiment with increasing institutional interest. """ # Gradio Interfaces # AI BTC Analysis Interface btc_analysis_interface = gr.Interface( fn=btc_analysis, inputs=[], outputs=gr.Textbox(label="BTC Analysis"), title="AI-Powered BTC Analysis" ) # Real-time Trade Data Interface real_time_trade_interface = gr.Interface( fn=real_time_trade_dashboard, inputs=gr.Dropdown(choices=['bitcoin', 'ethereum', 'binancecoin'], label="Cryptocurrency"), outputs=gr.Textbox(label="Real-Time Trade Data"), title="Real-Time Cryptocurrency Trade Data" ) # Price Chart Interface crypto_price_chart_interface = gr.Interface( fn=plot_historical_prices, inputs=[ gr.Dropdown(choices=['bitcoin', 'ethereum', 'binancecoin'], label="Cryptocurrency"), gr.Slider(minimum=1, maximum=365, step=1, value=30, label="Number of Days Back") ], outputs=gr.Plot(label="Cryptocurrency Price Chart"), title="Cryptocurrency Price Chart (Last X Days)" ) # Current Price Interface current_price_interface = gr.Interface( fn=fetch_current_price, inputs=gr.Dropdown(choices=['bitcoin', 'ethereum', 'binancecoin'], label="Cryptocurrency"), outputs=gr.Textbox(label="Current Price"), title="Current Cryptocurrency Price" ) # Combining all interfaces into a single tabbed app block = gr.TabbedInterface( [crypto_price_chart_interface, current_price_interface, real_time_trade_interface, btc_analysis_interface], tab_names=["Price Chart", "Current Price", "Real-Time Trade Data", "AI BTC Analysis"] ) # Launch the Gradio app if __name__ == "__main__": block.launch()