import pandas as pd import requests import random from datetime import datetime, timedelta # ----------------------------- # Fetch BTC Data # ----------------------------- def fetch_btc_data(): try: url = "https://api.coingecko.com/api/v3/coins/bitcoin/market_chart?vs_currency=usd&days=50" res = requests.get(url, timeout=10) res.raise_for_status() data = res.json() prices = data['prices'] df = pd.DataFrame(prices, columns=['time', 'close']) df['time'] = pd.to_datetime(df['time'], unit='ms') return df except Exception as e: print(f"Error fetching BTC data: {e}") return pd.DataFrame() # ----------------------------- # Simulated Prediction # ----------------------------- def simulate_lstm_prediction(df, hours_ahead=0): if df.empty or len(df) < 5: return None, None, None current_price = df.iloc[-1]['close'] momentum = (df.iloc[-1]['close'] - df.iloc[-5]['close']) / df.iloc[-5]['close'] time_factor = hours_ahead * 0.015 variance = (random.random() - 0.5) * (0.04 + time_factor) pred_price = current_price * (1 + (momentum * 0.35) + variance) trend = "HIGH ↑" if pred_price > current_price else "LOW ↓" confidence = random.uniform(65, 92) return pred_price, trend, confidence # ----------------------------- # Create Plot # ----------------------------- def create_plot(df): import plotly.graph_objects as go if df.empty: fig = go.Figure() fig.update_layout(template="plotly_dark", height=400, annotations=[dict(text="No data available", x=0.5, y=0.5, showarrow=False, font=dict(size=20))]) return fig fig = go.Figure() fig.add_trace(go.Scatter(x=df['time'], y=df['close'], mode='lines', name='BTC Price', line=dict(color='#3b82f6', width=4), fill='tozeroy', fillcolor='rgba(59, 130, 246, 0.1)')) fig.update_layout(template="plotly_dark", height=400, margin=dict(l=0,r=0,t=0,b=0), xaxis=dict(showgrid=False, title="Date"), yaxis=dict(showgrid=True, gridcolor='rgba(255,255,255,0.05)', title="Price (USD)")) return fig # ----------------------------- # Main Backend Function # ----------------------------- def run_dashboard(): df = fetch_btc_data() current_time = datetime.utcnow() + timedelta(hours=5) # PKT Time if df.empty: error_html = "
⚠️ Unable to fetch data
" return None, error_html, error_html, error_html, error_html, error_html current_price = df.iloc[-1]['close'] current_box = f"""
🕐 {current_time.strftime('%H:%M')}
${current_price:,.2f}
Current Bitcoin Price
""" # 1 Hour p1, t1, c1 = simulate_lstm_prediction(df, 1) time1 = current_time + timedelta(hours=1) pred1 = format_prediction_box(time1.strftime("%H:%M"), p1, t1, c1) # 2 Hours p2, t2, c2 = simulate_lstm_prediction(df, 2) time2 = current_time + timedelta(hours=2) pred2 = format_prediction_box(time2.strftime("%H:%M"), p2, t2, c2) # 1 Day p3, t3, c3 = simulate_lstm_prediction(df, 24) time3 = current_time + timedelta(hours=24) pred3 = format_prediction_box(time3.strftime("%b %d, %H:%M"), p3, t3, c3) plot = create_plot(df) analysis = f"""

💡 {random.choice([ "Momentum persistence detected in recent sequences.", "Strong correlation with historical breakout patterns.", "Attention mechanisms highlighting key support levels." ])}

""" return plot, current_box, pred1, pred2, pred3, analysis # Helper function for prediction box def format_prediction_box(time_str, price, trend, confidence): if price is None: return "

Prediction unavailable

" if "HIGH" in trend: color = "#34d399"; icon = "📈"; bg = "rgba(52, 211, 153, 0.1)" else: color = "#f87171"; icon = "📉"; bg = "rgba(248, 113, 113, 0.1)" return f"""
🕐 {time_str}
${price:,.2f}
{icon} {trend}
Confidence: {confidence:.0f}%
"""