-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathalpha_hub.py
More file actions
332 lines (265 loc) · 12.7 KB
/
Copy pathalpha_hub.py
File metadata and controls
332 lines (265 loc) · 12.7 KB
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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
# --- CRITICAL FIX FOR WEBPAGE FREEZING ---
import matplotlib
matplotlib.use('Agg') # Forces non-interactive backend (No pop-up windows)
import matplotlib.pyplot as plt
import streamlit as st
import yfinance as yf
import pandas as pd
import pandas_ta as ta
import plotly.graph_objects as go
import numpy as np
import requests
import io
from datetime import datetime
# --- CONFIGURATION ---
st.set_page_config(layout="wide", page_title="Damilare Alpha Hub", page_icon="🛡️")
# Credentials (Hardcoded for immediate use)
TELEGRAM_TOKEN = "8503707109:AAHkliGveqmXrTg00pDhFAK5OjWw3KakJWE"
TELEGRAM_CHAT_ID = "1934129034"
WATCHLIST = {
"Gold Futures": "GC=F",
"Bitcoin": "BTC-USD",
"EUR/USD": "EURUSD=X",
"GBP/USD": "GBPUSD=X",
"Nasdaq 100": "^IXIC",
"S&P 500": "^GSPC"
}
STRATEGY_OPTIONS = [
"Iron Apathy (Reversion)",
"Golden Cross (Trend)",
"SMC / ICT (Structure)",
"Elliott Wave (Cycles)",
"CRT (Candle Range Theory)"
]
# --- ADVANCED CALCULATION ENGINE ---
class Alpha_Engine:
@staticmethod
def calculate_fractals(df):
# Identify Swing Highs (Higher than neighbors)
df['Fractal_High'] = df['High'][(df['High'].shift(1) < df['High']) & (df['High'].shift(-1) < df['High'])]
# Identify Swing Lows (Lower than neighbors)
df['Fractal_Low'] = df['Low'][(df['Low'].shift(1) > df['Low']) & (df['Low'].shift(-1) > df['Low'])]
return df
@staticmethod
def calculate_smc(df):
df = Alpha_Engine.calculate_fractals(df)
# Bullish FVG
df['Bullish_FVG'] = np.where((df['High'].shift(2) < df['Low']) & (df['Close'].shift(1) > df['Open'].shift(1)),
1, 0)
# Bearish FVG
df['Bearish_FVG'] = np.where((df['Low'].shift(2) > df['High']) & (df['Close'].shift(1) < df['Open'].shift(1)),
1, 0)
return df
# --- ROBUST NOTIFICATION FUNCTION (TEXT + IMAGE) ---
def send_telegram_alert(message, df=None, symbol="Asset"):
if not TELEGRAM_TOKEN or not TELEGRAM_CHAT_ID: return
# 1. Image Generation (If dataframe provided)
if df is not None:
try:
# Create a clean static chart in memory
fig_static, ax = plt.subplots(figsize=(10, 5))
# Plot Price
ax.plot(df.index, df['Close'], color='cyan', label='Price', linewidth=1)
# Add EMA 200 if available
if 'EMA_200' in df.columns:
ax.plot(df.index, df['EMA_200'], color='orange', linestyle='--', label='EMA 200', linewidth=1)
# Styling
ax.set_title(f"{symbol} - Snapshot")
ax.legend()
ax.grid(True, alpha=0.2)
# Dark Theme styling for the image
fig_static.patch.set_facecolor('#0e1117')
ax.set_facecolor('#0e1117')
ax.tick_params(colors='white')
ax.xaxis.label.set_color('white')
ax.yaxis.label.set_color('white')
ax.title.set_color('white')
for spine in ax.spines.values(): spine.set_edgecolor('white')
# Save to buffer
buf = io.BytesIO()
plt.savefig(buf, format='png', facecolor=fig_static.get_facecolor())
buf.seek(0)
plt.close(fig_static) # Close to prevent memory leak
# Send Photo API
url = f"https://api.telegram.org/bot{TELEGRAM_TOKEN}/sendPhoto"
payload = {'chat_id': TELEGRAM_CHAT_ID, 'caption': message}
files = {'photo': buf}
requests.post(url, data=payload, files=files)
except Exception as e:
# Fallback to text if image fails
print(f"Image Error: {e}")
requests.get(
f"https://api.telegram.org/bot{TELEGRAM_TOKEN}/sendMessage?chat_id={TELEGRAM_CHAT_ID}&text={message}")
else:
# Text Only API
requests.get(
f"https://api.telegram.org/bot{TELEGRAM_TOKEN}/sendMessage?chat_id={TELEGRAM_CHAT_ID}&text={message}")
@st.cache_data(ttl=300)
def fetch_data(symbol, period='1mo', interval='1h'):
try:
df = yf.download(symbol, period=period, interval=interval, progress=False)
if isinstance(df.columns, pd.MultiIndex): df.columns = df.columns.get_level_values(0)
if df.empty: return None
return df
except:
return None
# --- STRATEGY DRAWERS ---
def draw_iron_apathy(fig, df):
bb = ta.bbands(df['Close'], length=20, std=2)
bbu = [c for c in bb.columns if c.startswith('BBU')][0]
bbl = [c for c in bb.columns if c.startswith('BBL')][0]
df = pd.concat([df, bb], axis=1)
df['EMA_200'] = ta.ema(df['Close'], length=200)
fig.add_trace(go.Scatter(x=df.index, y=df[bbu], line=dict(color='gray', width=1, dash='dot'), name='Upper BB'))
fig.add_trace(go.Scatter(x=df.index, y=df[bbl], line=dict(color='gray', width=1, dash='dot'), name='Lower BB'))
fig.add_trace(go.Scatter(x=df.index, y=df['EMA_200'], line=dict(color='orange', width=2), name='Trend (EMA 200)'))
last = df.iloc[-2]
buy = (last['Close'] < last[bbl]) and (last['Close'] > last['EMA_200'])
sell = (last['Close'] > last[bbu]) and (last['Close'] < last['EMA_200'])
return buy, sell
def draw_golden_cross(fig, df):
df['EMA_50'] = ta.ema(df['Close'], length=50)
df['EMA_200'] = ta.ema(df['Close'], length=200)
fig.add_trace(go.Scatter(x=df.index, y=df['EMA_50'], line=dict(color='cyan', width=1), name='Fast EMA (50)'))
fig.add_trace(go.Scatter(x=df.index, y=df['EMA_200'], line=dict(color='gold', width=2), name='Slow EMA (200)'))
last = df.iloc[-2]
prev = df.iloc[-3]
buy = (last['EMA_50'] > last['EMA_200']) and (prev['EMA_50'] <= prev['EMA_200'])
sell = (last['EMA_50'] < last['EMA_200']) and (prev['EMA_50'] >= prev['EMA_200'])
return buy, sell
def draw_smc_ict(fig, df):
df = Alpha_Engine.calculate_smc(df)
swings = df[df['Fractal_High'].notnull()]
fig.add_trace(go.Scatter(x=swings.index, y=swings['Fractal_High'], mode='markers',
marker=dict(symbol='triangle-down', size=10, color='red'), name='Swing High'))
swings_low = df[df['Fractal_Low'].notnull()]
fig.add_trace(go.Scatter(x=swings_low.index, y=swings_low['Fractal_Low'], mode='markers',
marker=dict(symbol='triangle-up', size=10, color='green'), name='Swing Low'))
# Draw FVGs
bull_fvg_indices = df.index[df['Bullish_FVG'] == 1].tolist()
for idx in bull_fvg_indices[-10:]:
try:
loc = df.index.get_loc(idx)
fig.add_shape(type="rect", x0=df.index[loc - 2], y0=df['High'].iloc[loc - 2], x1=df.index[-1],
y1=df['Low'].iloc[loc],
fillcolor="rgba(0,255,0,0.1)", line_width=0)
except:
pass
return False, False
def draw_elliott_wave(fig, df):
df = Alpha_Engine.calculate_fractals(df)
fractals = []
for i in range(len(df)):
if pd.notnull(df['Fractal_High'].iloc[i]):
fractals.append({'idx': df.index[i], 'price': df['Fractal_High'].iloc[i], 'type': 'High'})
elif pd.notnull(df['Fractal_Low'].iloc[i]):
fractals.append({'idx': df.index[i], 'price': df['Fractal_Low'].iloc[i], 'type': 'Low'})
recent_fractals = fractals[-6:]
x_vals = [f['idx'] for f in recent_fractals]
y_vals = [f['price'] for f in recent_fractals]
fig.add_trace(go.Scatter(x=x_vals, y=y_vals, mode='lines+markers+text',
line=dict(color='white', width=2, dash='dash'),
text=["0", "1", "2", "3", "4", "5"],
textposition="top center",
name='Elliott Wave Count'))
if len(recent_fractals) > 4:
last_pt = recent_fractals[-1]
if last_pt['type'] == 'Low':
return True, False
elif last_pt['type'] == 'High':
return False, True
return False, False
def draw_crt(fig, df):
prev = df.iloc[-2] # The "Range" Candle
curr = df.iloc[-1] # The "Live" Candle
fig.add_shape(type="rect", x0=df.index[-2], y0=prev['Low'], x1=df.index[-1], y1=prev['High'],
line=dict(color="blue", width=1), fillcolor="rgba(0,0,255,0.1)", name="Prev Candle Range")
buy = False
sell = False
# Deviation Low (Liquidity Grab)
if (curr['Low'] < prev['Low']) and (curr['Close'] > prev['Low']):
buy = True
fig.add_annotation(x=curr.name, y=curr['Low'], text="CRT: Deviation Buy", showarrow=True, arrowhead=1)
# Deviation High (Liquidity Grab)
if (curr['High'] > prev['High']) and (curr['Close'] < prev['High']):
sell = True
fig.add_annotation(x=curr.name, y=curr['High'], text="CRT: Deviation Sell", showarrow=True, arrowhead=1)
return buy, sell
# --- MAIN UI ---
st.title("🛡️ Damilare Alpha Hub: Ultimate Edition")
st.markdown(f"**Status:** `Online` | **Time:** `{datetime.now().strftime('%H:%M:%S')}`")
# Sidebar
st.sidebar.header("Mission Control")
selected_name = st.sidebar.selectbox("Asset", list(WATCHLIST.keys()))
symbol = WATCHLIST[selected_name]
strategy_mode = st.sidebar.radio("Active Strategy", STRATEGY_OPTIONS)
# 1. SCANNER
if st.sidebar.button("🚀 SCAN ALL (ALL STRATEGIES)"):
progress = st.sidebar.progress(0)
alerts = 0
st.sidebar.write("Scanning...")
for i, (name, ticker) in enumerate(WATCHLIST.items()):
data = fetch_data(ticker)
if data is not None:
# We run a quick CRT check for the scanner
try:
prev = data.iloc[-2];
curr = data.iloc[-1]
if (curr['Low'] < prev['Low']) and (curr['Close'] > prev['Low']):
send_telegram_alert(f"🟢 CRT BUY: {name}\nReason: Liquidity Grab (Deviation Low)",
df=None) # Text only for scanner speed
alerts += 1
if (curr['High'] > prev['High']) and (curr['Close'] < prev['High']):
send_telegram_alert(f"🔴 CRT SELL: {name}\nReason: Liquidity Grab (Deviation High)", df=None)
alerts += 1
except:
pass
progress.progress((i + 1) / len(WATCHLIST))
if alerts > 0:
st.sidebar.success(f"Scan Done. {alerts} Signals Found.")
else:
st.sidebar.info("Scan Done. Market is quiet.")
# 2. CHART AREA
df = fetch_data(symbol)
if df is not None:
# Prepare Data for Image Generation (Standardize columns)
df['EMA_200'] = ta.ema(df['Close'], length=200) # Ensure this exists for the chart image
fig = go.Figure(data=[go.Candlestick(x=df.index, open=df['Open'], high=df['High'], low=df['Low'], close=df['Close'],
name=selected_name)])
buy_sig, sell_sig = False, False
if "Iron Apathy" in strategy_mode:
buy_sig, sell_sig = draw_iron_apathy(fig, df)
elif "Golden Cross" in strategy_mode:
buy_sig, sell_sig = draw_golden_cross(fig, df)
elif "SMC" in strategy_mode:
buy_sig, sell_sig = draw_smc_ict(fig, df)
st.caption("ℹ️ SMC: Showing Market Structure Breaks and FVGs.")
elif "Elliott Wave" in strategy_mode:
buy_sig, sell_sig = draw_elliott_wave(fig, df)
st.caption("ℹ️ Elliott Wave: Visualizing the last 5 market swings (1-2-3-4-5).")
elif "CRT" in strategy_mode:
buy_sig, sell_sig = draw_crt(fig, df)
st.caption("ℹ️ CRT: Trading deviations of the previous candle's range.")
fig.update_layout(height=650, template="plotly_dark", xaxis_rangeslider_visible=False,
title=f"{selected_name} - {strategy_mode}")
st.plotly_chart(fig, use_container_width=True)
# SIGNAL PANEL
st.markdown("### 📡 Live Signal Output")
col1, col2 = st.columns(2)
col1.metric("Live Price", f"{df['Close'].iloc[-1]:.2f}")
if buy_sig:
col2.success(f"BUY SIGNAL ({strategy_mode})")
if st.button("Broadcast Buy"):
st.toast("Sending to Telegram...", icon="📤")
send_telegram_alert(f"🟢 MANUAL BUY: {selected_name} [{strategy_mode}]", df, selected_name)
st.success("Sent!")
elif sell_sig:
col2.error(f"SELL SIGNAL ({strategy_mode})")
if st.button("Broadcast Sell"):
st.toast("Sending to Telegram...", icon="📤")
send_telegram_alert(f"🔴 MANUAL SELL: {selected_name} [{strategy_mode}]", df, selected_name)
st.success("Sent!")
else:
col2.info("WAITING FOR SETUP...")
else:
st.error("Data connection failed.")