File size: 12,215 Bytes
03d7347 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 | 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"""
<div style="padding:20px; border-radius:10px; background-color:#1e1e1e; border-left: 10px solid {color}; color: white;">
<h2 style="color:{color}; margin:0;">SIGNAL: {signal}</h2>
<p style="margin:0;">AI Model Confidence: {confidence:.2f}%</p>
<p style="margin:0; font-size:12px; opacity:0.7;">Generated at: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}</p>
</div>
""", 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"""
<script>
if (Notification.permission === "granted") {{
new Notification("AI Trading Bot", {{
body: "SIGNAL {signal} for {selected_asset_name} - Confidence: {confidence:.2f}%",
icon: "https://cdn-icons-png.flaticon.com/512/1035/1035688.png"
}});
{f"new Audio('https://assets.mixkit.co/sfx/preview/mixkit-software-interface-start-2574.mp3').play();" if st.session_state.sound_enabled else ""}
}}
</script>
""", 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("""
<script>
if (Notification.permission !== "granted") {
Notification.requestPermission();
}
</script>
""", 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") |