import streamlit as st import pandas as pd import plotly.graph_objects as go from data_engine import fetch_data, add_indicators, prepare_ml_data from model_engine import train_and_get_prediction from news_crawler import fetch_market_news import numpy as np import time import os from datetime import datetime from streamlit_autorefresh import st_autorefresh # Page Configuration st.set_page_config(page_title="AI Trading Signal Bot", layout="wide") # -------------------------- # INITIALIZE SESSION STATE # -------------------------- if 'last_signal' not in st.session_state: st.session_state.last_signal = None if 'signal_history' not in st.session_state: st.session_state.signal_history = [] if 'auto_mode' not in st.session_state: st.session_state.auto_mode = False if 'refresh_interval' not in st.session_state: st.session_state.refresh_interval = 60000 if 'notifications_enabled' not in st.session_state: st.session_state.notifications_enabled = False if 'sound_enabled' not in st.session_state: st.session_state.sound_enabled = True # -------------------------- # SIDEBAR # -------------------------- st.sidebar.header("âš™ī¸ Controls") # Asset Selection st.sidebar.header("Market Selection") asset_map = { "Bitcoin (BTC)": "BTC-USD", "Ethereum (ETH)": "ETH-USD", "Gold": "GC=F", "Silver": "SI=F", "Crude Oil": "CL=F" } selected_asset_name = st.sidebar.selectbox("Choose Asset", list(asset_map.keys())) selected_symbol = asset_map[selected_asset_name] # Timeframe selection (including new 1min) timeframe = st.sidebar.selectbox("Timeframe", ["1m", "5m", "15m", "1h", "1d"], index=3) # Set appropriate period based on timeframe period_map = { "1m": "7d", "5m": "60d", "15m": "60d", "1h": "1mo", "1d": "2y" } period = period_map[timeframe] st.sidebar.markdown("---") # Auto Pilot Mode st.sidebar.header("🤖 Auto Pilot Mode") auto_mode = st.sidebar.toggle("Enable Auto Refresh", value=st.session_state.auto_mode) st.session_state.auto_mode = auto_mode if auto_mode: refresh_options = { "1 Minute": 60000, "5 Minutes": 300000, "15 Minutes": 900000, "30 Minutes": 1800000 } refresh_label = st.sidebar.selectbox("Refresh Interval", list(refresh_options.keys()), index=1) st.session_state.refresh_interval = refresh_options[refresh_label] st.session_state.notifications_enabled = st.sidebar.toggle("🔔 Push Notifications", value=st.session_state.notifications_enabled) st.session_state.sound_enabled = st.sidebar.toggle("🔊 Sound Alert", value=st.session_state.sound_enabled) st_autorefresh(interval=st.session_state.refresh_interval, key="autorefresh") st.sidebar.success("✅ Auto Mode Active") else: st.sidebar.info("⏸ Auto Mode Paused") st.sidebar.markdown("---") # Manual Generate Button generate_clicked = st.sidebar.button("📊 Generate Signal Now", type="primary", use_container_width=True) st.sidebar.markdown("---") st.sidebar.write("Asset Coverage: BTC, ETH, Gold, Oil, Silver") st.sidebar.caption("âš ī¸ This is for educational purposes only. Not financial advice.") # -------------------------- # MAIN APPLICATION # -------------------------- st.title("🚀 AI Trading Signal Bot") if auto_mode: st.info(f"🤖 Auto Pilot is ACTIVE. Auto refreshing every {refresh_label}. Last update: {datetime.now().strftime('%H:%M:%S')}") st.markdown(""" This bot uses **Machine Learning** and **Technical Indicators** to predict market signals. It analyzes candlestick patterns and crawls recent news for context. """) if generate_clicked or auto_mode: with st.spinner(f"Analyzing {selected_asset_name}..."): # 1. Fetch Data df = fetch_data(selected_symbol, period=period, interval=timeframe) if df.empty: st.error("Could not fetch data. Please try again later.") else: # 2. Add Indicators df_with_ind = add_indicators(df.copy()) # 3. Prepare ML Data and Predict X, y, latest_window = prepare_ml_data(df_with_ind) if len(X) == 0: st.warning("Not enough data to generate a signal for this timeframe.") else: # Reshape latest window for model input latest_window = latest_window.reshape(1, latest_window.shape[0], latest_window.shape[1]) prediction_prob = train_and_get_prediction(X, y, latest_window) # 4. News Crawling news_items = fetch_market_news(selected_asset_name) # --- UI DISPLAY --- col1, col2 = st.columns([2, 1]) with col1: st.subheader(f"{selected_asset_name} Price Chart & Signal") # Signal logic if prediction_prob > 0.55: signal = "BUY" color = "green" elif prediction_prob < 0.45: signal = "SELL" color = "red" else: signal = "HOLD" color = "gray" confidence = abs(prediction_prob - 0.5) * 200 # Normalized to 0-100% st.markdown(f"""

SIGNAL: {signal}

AI Model Confidence: {confidence:.2f}%

Generated at: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}

""", unsafe_allow_html=True) # Check for signal change if st.session_state.last_signal is not None and st.session_state.last_signal != signal: # Signal changed - trigger notification if st.session_state.notifications_enabled: st.toast(f"🔔 SIGNAL CHANGE: {signal} for {selected_asset_name}", icon="🚨") # Browser notification script st.components.v1.html(f""" """, height=0) # Save current signal st.session_state.last_signal = signal # Add to history history_entry = { "time": datetime.now().strftime('%Y-%m-%d %H:%M:%S'), "asset": selected_asset_name, "signal": signal, "confidence": f"{confidence:.2f}%" } st.session_state.signal_history.insert(0, history_entry) if len(st.session_state.signal_history) > 20: st.session_state.signal_history.pop() # Plotly Chart fig = go.Figure(data=[go.Candlestick(x=df.index, open=df['Open'], high=df['High'], low=df['Low'], close=df['Close'], name="Candlestick")]) fig.add_trace(go.Scatter(x=df_with_ind.index, y=df_with_ind['EMA_20'], name="EMA 20", line=dict(color='orange', width=1))) fig.add_trace(go.Scatter(x=df_with_ind.index, y=df_with_ind['EMA_50'], name="EMA 50", line=dict(color='blue', width=1))) fig.update_layout(xaxis_rangeslider_visible=False, template="plotly_dark", height=500) st.plotly_chart(fig, use_container_width=True) st.write("### Technical Indicators (Latest)") st.dataframe(df_with_ind[['Close', 'EMA_20', 'EMA_50', 'RSI', 'MACD', 'ATR']].tail(5), use_container_width=True) with col2: # Notification permission request if st.session_state.notifications_enabled: st.components.v1.html(""" """, height=0) st.subheader("📰 Market Context") if news_items: for item in news_items[:5]: st.markdown(f"**{item['title']}**") if item['snippet']: st.caption(item['snippet']) st.divider() else: st.write("No recent news found.") st.subheader("đŸ•¯ī¸ Candlestick Strategy") # Find recent patterns pattern_cols = [col for col in df_with_ind.columns if col.startswith('CDL')] recent_patterns = df_with_ind[pattern_cols].tail(1).iloc[0] detected = recent_patterns[recent_patterns == True] if not detected.empty: st.write("Current Candle Patterns:") for pat in detected.index: name = pat.replace('CDL_', '').replace('_', ' ') st.success(f"✅ Detected: {name}") else: st.info("â„šī¸ No strong candlestick patterns in the current candle.") st.subheader("📜 Signal History") if st.session_state.signal_history: history_df = pd.DataFrame(st.session_state.signal_history) st.dataframe(history_df, use_container_width=True, hide_index=True) else: st.write("No signal history yet.") else: st.info("👆 Select an asset from the sidebar and click 'Generate Signal Now' or enable Auto Pilot Mode to start.") # First run welcome st.markdown("---") st.subheader("📌 Features:") colf1, colf2, colf3 = st.columns(3) with colf1: st.markdown("✅ Real live market data") st.markdown("✅ 1 minute timeframe support") st.markdown("✅ ML trained predictions") with colf2: st.markdown("✅ Auto Pilot auto refresh mode") st.markdown("✅ Browser push notifications") st.markdown("✅ Sound alerts") with colf3: st.markdown("✅ Public access without login") st.markdown("✅ Signal change detection") st.markdown("✅ Signal history log")