kulusia commited on
Commit
2fb731a
Β·
verified Β·
1 Parent(s): a26dcad

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +516 -0
app.py ADDED
@@ -0,0 +1,516 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ SMC AI BOT v9.9 - Hugging Face Deployment (COMPLETE)
4
+ - All feature functions included
5
+ - Full 31-criteria filter analysis
6
+ - 5-timeframe SMC signals
7
+ - Telegram alerts every 5 minutes
8
+ - Keep-alive ping to prevent sleeping
9
+ """
10
+
11
+ import os, numpy as np, pandas as pd, warnings, requests, time, threading
12
+ from datetime import datetime, timedelta, timezone
13
+ from flask import Flask
14
+ warnings.filterwarnings("ignore")
15
+ import xgboost as xgb, joblib
16
+
17
+ # ============================================================
18
+ # FLASK APP
19
+ # ============================================================
20
+ app = Flask(__name__)
21
+
22
+ @app.route('/')
23
+ def home():
24
+ return "πŸ€– SMC AI Bot v9.9 β€” Live on Hugging Face"
25
+
26
+ @app.route('/health')
27
+ def health():
28
+ return {"status": "alive", "time": str(datetime.now(timezone.utc)), "models": len(models)}
29
+
30
+ # ============================================================
31
+ # LOAD SECRETS
32
+ # ============================================================
33
+ BOT_TOKEN = os.environ.get('TELEGRAM_BOT_TOKEN', '')
34
+ CHAT_ID = os.environ.get('TELEGRAM_CHAT_ID', '')
35
+ TWELVEDATA_API_KEY = os.environ.get('TWELVEDATA_API_KEY', '')
36
+
37
+ print(f"πŸ”‘ Telegram Bot: {'βœ…' if BOT_TOKEN else '❌ MISSING'}")
38
+ print(f"πŸ”‘ Chat ID: {'βœ…' if CHAT_ID else '❌ MISSING'}")
39
+ print(f"πŸ”‘ Twelve Data: {'βœ…' if TWELVEDATA_API_KEY else '❌ MISSING'}")
40
+
41
+ # ============================================================
42
+ # LOAD MODELS
43
+ # ============================================================
44
+ print("\nπŸ“¦ Loading models...")
45
+ models = {}
46
+ model_files = {
47
+ '5min': 'model_5min_entry.pkl',
48
+ '30min': 'model_30min_bias.pkl',
49
+ '1h': 'model_1h_bias.pkl',
50
+ '2h': 'model_2h_bias.pkl',
51
+ '4h': 'model_4h_bias.pkl',
52
+ }
53
+
54
+ for name, path in model_files.items():
55
+ if os.path.exists(path):
56
+ try:
57
+ models[name] = joblib.load(path)
58
+ print(f" βœ… {name.upper()}")
59
+ except Exception as e:
60
+ print(f" ❌ {name.upper()}: {e}")
61
+ else:
62
+ print(f" ❌ {name.upper()}: File not found")
63
+
64
+ print(f"\nβœ… {len(models)}/5 models loaded")
65
+
66
+ TIMEFRAMES = {
67
+ '5min': {'minutes': 5, 'fwd': 4},
68
+ '30min': {'minutes': 30, 'fwd': 4},
69
+ '1h': {'minutes': 60, 'fwd': 6},
70
+ '2h': {'minutes': 120, 'fwd': 4},
71
+ '4h': {'minutes': 240, 'fwd': 3},
72
+ }
73
+
74
+ TF_LABELS = {'5min':'🎯 5min','30min':'πŸ”’ 30min','1h':'πŸ”’ 1H','2h':'πŸ”’ 2H','4h':'πŸ”’ 4H'}
75
+
76
+ # ============================================================
77
+ # ALL FEATURE FUNCTIONS
78
+ # ============================================================
79
+
80
+ def calculate_atr(high, low, close, period=14):
81
+ pc = np.zeros_like(close); pc[1:] = close[:-1]; pc[0] = close[0]
82
+ tr = np.maximum(high-low, np.maximum(np.abs(high-pc), np.abs(low-pc)))
83
+ av = pd.Series(tr).rolling(period, min_periods=1).mean().values[-1]
84
+ return av if not np.isnan(av) else (high[-1]-low[-1])
85
+
86
+ def calculate_rsi(close, period=14):
87
+ if len(close) < period+1: return 50
88
+ d = pd.Series(close).diff(); g = d.where(d>0,0).rolling(period,min_periods=1).mean()
89
+ lo = (-d.where(d<0,0)).rolling(period,min_periods=1).mean(); lv = lo.values[-1]
90
+ if lv == 0: return 50
91
+ return 100-(100/(1+g.values[-1]/lv))
92
+
93
+ def calculate_ema(close, period=20):
94
+ return pd.Series(close).ewm(span=period, adjust=False).mean().values[-1]
95
+
96
+ def find_swing_points(high, low, lookback=5):
97
+ sh, sl = [], []
98
+ for i in range(lookback, len(high)-lookback):
99
+ if high[i]==max(high[i-lookback:i+lookback+1]): sh.append({'index':i,'price':high[i]})
100
+ if low[i]==min(low[i-lookback:i+lookback+1]): sl.append({'index':i,'price':low[i]})
101
+ return sh, sl
102
+
103
+ def analyze_structure_from_swings(sh, sl):
104
+ if len(sh)<2 or len(sl)<2: return 'neutral',0
105
+ hc = (sh[-1]['price']-sh[-2]['price'])/sh[-2]['price']*100 if sh[-2]['price']!=0 else 0
106
+ lc = (sl[-1]['price']-sl[-2]['price'])/sl[-2]['price']*100 if sl[-2]['price']!=0 else 0
107
+ if sh[-1]['price']>sh[-2]['price'] and sl[-1]['price']>sl[-2]['price']: return 'bullish',round(hc+lc,2)
108
+ elif sh[-1]['price']<sh[-2]['price'] and sl[-1]['price']<sl[-2]['price']: return 'bearish',round(hc+lc,2)
109
+ return 'ranging',0
110
+
111
+ def detect_bos_from_swings(sh, sl, s, cp):
112
+ if len(sh)<2 or len(sl)<2: return 'none'
113
+ if s=='bullish':
114
+ if cp>sh[-1]['price']: return 'bos_bullish'
115
+ if cp<sl[-1]['price']: return 'choch_bearish'
116
+ elif s=='bearish':
117
+ if cp<sl[-1]['price']: return 'bos_bearish'
118
+ if cp>sh[-1]['price']: return 'choch_bullish'
119
+ return 'none'
120
+
121
+ def find_fair_value_gaps(high, low):
122
+ lb = min(20, len(high)-4); fvgs = []
123
+ for i in range(len(high)-3, max(len(high)-lb,0), -1):
124
+ if high[i]<low[i+2]: fvgs.append({'type':'bullish','top':round(low[i+2],2),'bottom':round(high[i],2)})
125
+ elif low[i]>high[i+2]: fvgs.append({'type':'bearish','top':round(high[i+2],2),'bottom':round(low[i],2)})
126
+ return fvgs
127
+
128
+ def calculate_premium_discount(high, low, close):
129
+ lb = min(50, len(high)); rh, rl = np.max(high[-lb:]), np.min(low[-lb:]); rt = rh-rl
130
+ if rt==0: return 'equilibrium',50
131
+ pct = (close[-1]-rl)/rt*100
132
+ if pct>=75: return 'premium',round(pct,1)
133
+ elif pct<=25: return 'discount',round(pct,1)
134
+ return 'equilibrium',round(pct,1)
135
+
136
+ def get_kill_zone_score(hour, minute):
137
+ if (8,0)<=(hour,minute)<=(9,30): return 2
138
+ elif (13,0)<=(hour,minute)<=(14,30): return 2
139
+ elif (16,0)<=(hour,minute)<=(17,0): return 2
140
+ elif (9,30)<=(hour,minute)<=(12,0): return 1
141
+ elif (14,30)<=(hour,minute)<=(16,0): return 1
142
+ elif (2,0)<=(hour,minute)<=(4,0): return 1
143
+ return 0
144
+
145
+ def calculate_footprint(df_slice):
146
+ o, h, l, c = df_slice['Open'].values, df_slice['High'].values, df_slice['Low'].values, df_slice['Close'].values
147
+ if len(c)<10: return 0
148
+ bp, sp = 0, 0
149
+ for i in range(-8, 0):
150
+ body = abs(c[i]-o[i]); tr = h[i]-l[i]
151
+ if tr==0: continue
152
+ eff = body/tr; rw = 1+(8+i)/8
153
+ if c[i]>o[i]: bp += eff*((c[i]-l[i])/tr)*rw
154
+ elif c[i]<o[i]: sp += eff*((h[i]-c[i])/tr)*rw
155
+ total = bp+sp; delta = (bp-sp)/total if total>0 else 0
156
+ lr = h[-1]-l[-1]; absorption = 0
157
+ if lr>0:
158
+ uw = h[-1]-max(c[-1],o[-1]); lw = min(c[-1],o[-1])-l[-1]
159
+ if lw>lr*0.4 and c[-1]>o[-1]: absorption = min(lw/lr,1.0)
160
+ elif uw>lr*0.4 and c[-1]<o[-1]: absorption = -min(uw/lr,1.0)
161
+ pace_score = 0
162
+ if len(c)>=7:
163
+ rm, om = c[-1]-c[-4], c[-4]-c[-7]; avg = (abs(rm)+abs(om))/2
164
+ if avg>0:
165
+ pace = (abs(rm)-abs(om))/avg
166
+ if rm>0 and pace>0: pace_score = min(pace,1.0)
167
+ elif rm>0 and pace<0: pace_score = -min(abs(pace),1.0)
168
+ elif rm<0 and pace>0: pace_score = -min(pace,1.0)
169
+ elif rm<0 and pace<0: pace_score = min(abs(pace),1.0)
170
+ return np.clip(delta*0.5+absorption*0.3+pace_score*0.2, -1, 1)
171
+
172
+ def candle_body_ratio(o,h,l,c): return abs(c[-1]-o[-1])/(h[-1]-l[-1]) if h[-1]!=l[-1] else 0
173
+ def wick_ratio(o,h,l,c):
174
+ tr = h[-1]-l[-1]
175
+ return ((h[-1]-max(c[-1],o[-1]))-(min(c[-1],o[-1])-l[-1]))/tr if tr!=0 else 0
176
+ def momentum(c,p=5): return (c[-1]-c[-p-1])/c[-p-1]*100 if len(c)>=p+1 and c[-p-1]!=0 else 0
177
+ def volatility_ratio(h,l,c,sp=5,lp=20):
178
+ pc=np.zeros_like(c);pc[1:]=c[:-1];pc[0]=c[0]
179
+ tr=np.maximum(h-l,np.maximum(np.abs(h-pc),np.abs(l-pc)))
180
+ sa=pd.Series(tr).rolling(sp,min_periods=1).mean().values[-1]
181
+ la=pd.Series(tr).rolling(lp,min_periods=1).mean().values[-1]
182
+ return sa/la if not pd.isna(la) and la!=0 else 1.0
183
+ def close_location(h,l,c): return (c[-1]-l[-1])/(h[-1]-l[-1]) if h[-1]!=l[-1] else 0.5
184
+ def gap_detection(o,c): return (o[-1]-c[-2])/c[-2]*100 if len(c)>=2 and c[-2]!=0 else 0
185
+ def consecutive_streak(c,p=5):
186
+ s=0
187
+ for i in range(-p,-1):
188
+ if c[i]>c[i-1]: s+=1
189
+ elif c[i]<c[i-1]: s-=1
190
+ return s
191
+ def range_compression(h,l,p=10):
192
+ rr=np.max(h[-p:])-np.min(l[-p:]); o_r=np.max(h[-p*2:-p])-np.min(l[-p*2:-p])
193
+ return rr/o_r if o_r!=0 else 1.0
194
+ def price_acceleration(c): return (c[-1]-c[-3])-(c[-3]-c[-5]) if len(c)>=5 else 0
195
+
196
+ def extract_features_20(df_slice):
197
+ h,l,c=df_slice['High'].values,df_slice['Low'].values,df_slice['Close'].values; o=df_slice['Open'].values
198
+ atr=calculate_atr(h,l,c);rsi=calculate_rsi(c)
199
+ trend=(c[-1]-calculate_ema(c))/atr if atr>0 else 0
200
+ rh=np.max(h[-50:]) if len(h)>=50 else np.max(h);rl=np.min(l[-50:]) if len(l)>=50 else np.min(l)
201
+ price_pos=(c[-1]-rl)/(rh-rl) if rh!=rl else 0.5
202
+ t=df_slice.index[-1];kz=get_kill_zone_score(t.hour,t.minute);fp=calculate_footprint(df_slice)
203
+ sh,sl=find_swing_points(h,l,5);structure,score=analyze_structure_from_swings(sh,sl)
204
+ sn=1 if structure=='bullish' else (-1 if structure=='bearish' else 0)
205
+ bos=detect_bos_from_swings(sh,sl,structure,c[-1])
206
+ bn=1 if 'bullish' in bos else (-1 if 'bearish' in bos else 0)
207
+ fvgs=find_fair_value_gaps(h,l);fn=0
208
+ if fvgs: cur=c[-1];n=fvgs[0];fn=1 if n['type']=='bullish' and cur>n['bottom'] else (-1 if n['type']=='bearish' and cur<n['top'] else 0)
209
+ pd_sc,pos=calculate_premium_discount(h,l,c);zn=1 if pd_sc=='discount' else (-1 if pd_sc=='premium' else 0)
210
+ return [rsi,trend,price_pos,kz/2,fp,sn,score/10 if score else 0,bn,fn,zn,pos/100,
211
+ candle_body_ratio(o,h,l,c),wick_ratio(o,h,l,c),momentum(c,5)/10,
212
+ volatility_ratio(h,l,c),close_location(h,l,c),gap_detection(o,c)/10,
213
+ consecutive_streak(c,5)/5,range_compression(h,l,10),price_acceleration(c)/10]
214
+
215
+ # ============================================================
216
+ # REGIME DETECTION
217
+ # ============================================================
218
+
219
+ class RegimeDetector:
220
+ def detect(self, df):
221
+ if len(df) < 100: return {'regime':'NORMAL','confidence':0.5,'parameters':{'atr_sl':1.5,'atr_tp':2.0,'min_conf':0.6,'max_risk':1.0,'preferred_tfs':['5min','30min','1h','2h','4h']}}
222
+ h,l,c = df['High'].values[-100:], df['Low'].values[-100:], df['Close'].values[-100:]
223
+ rng = h-l; ca = np.mean(rng[-14:]); la = np.mean(rng); vr = ca/la if la>0 else 1.0
224
+ s20 = np.mean(c[-20:]); s50 = np.mean(c[-50:]); td = 'BULLISH' if s20>s50 else 'BEARISH'
225
+ if vr > 1.5: reg = f'HIGH_VOL_{td}'; cf=0.7; pr={'atr_sl':2.0,'atr_tp':3.0,'min_conf':0.65,'max_risk':0.75,'preferred_tfs':['1h','2h','4h']}
226
+ elif vr < 0.6: reg = 'LOW_VOL_COMPRESSION'; cf=0.75; pr={'atr_sl':0.8,'atr_tp':3.0,'min_conf':0.7,'max_risk':0.5,'preferred_tfs':['5min','30min']}
227
+ else: reg = f'NORMAL_{td}'; cf=0.6; pr={'atr_sl':1.5,'atr_tp':2.0,'min_conf':0.6,'max_risk':1.0,'preferred_tfs':['5min','30min','1h','2h','4h']}
228
+ return {'regime':reg,'confidence':cf,'parameters':pr}
229
+
230
+ def get_current_session():
231
+ now = datetime.now(timezone.utc); h = now.hour; wd = now.weekday()
232
+ if wd >= 5: return 'WEEKEND'
233
+ if wd == 4 and h >= 22: return 'WEEKEND_CLOSE'
234
+ if 22 <= h or h < 2: return 'ASIAN_LATE'
235
+ elif 2 <= h < 6: return 'ASIAN'
236
+ elif 6 <= h < 8: return 'PRE_LONDON'
237
+ elif 8 <= h < 10: return 'LONDON_KILLZONE'
238
+ elif 10 <= h < 13: return 'LONDON'
239
+ elif 13 <= h < 15: return 'NY_KILLZONE'
240
+ elif 15 <= h < 16: return 'LONDON_NY_OVERLAP'
241
+ elif 16 <= h < 20: return 'NY'
242
+ elif 20 <= h < 22: return 'POST_NY'
243
+ return 'UNKNOWN'
244
+
245
+ # ============================================================
246
+ # SIGNAL GENERATION
247
+ # ============================================================
248
+
249
+ def get_signal(model, df):
250
+ if len(df) < 201: return None
251
+ features = np.array([extract_features_20(df.iloc[-201:-1])])
252
+ try:
253
+ probs = model.predict_proba(features)[0]
254
+ pred = np.argmax(probs)
255
+ return {'action':{0:'SELL',1:'HOLD',2:'BUY'}[pred],'confidence':float(probs[pred]),
256
+ 'all_probs':{'SELL':float(probs[0]),'HOLD':float(probs[1]),'BUY':float(probs[2])}}
257
+ except: return None
258
+
259
+ def analyze_signal(model, df, tf_name, tf_minutes, forward_bars, regime_params):
260
+ bias = get_signal(model, df)
261
+ if bias is None: return None, [("MODEL","❌","Prediction failed")]
262
+
263
+ h,l,c = df['High'].values,df['Low'].values,df['Close'].values; o = df['Open'].values
264
+ price = round(c[-1],2); atr_val = calculate_atr(h[-14:],l[-14:],c[-14:]); rsi_val = calculate_rsi(c)
265
+
266
+ fp_df = pd.DataFrame({'Open':o,'High':h,'Low':l,'Close':c})
267
+ footprint = calculate_footprint(fp_df)
268
+ sh,sl_sw = find_swing_points(h,l,5)
269
+ structure,_ = analyze_structure_from_swings(sh,sl_sw)
270
+ bos = detect_bos_from_swings(sh,sl_sw,structure,c[-1])
271
+ fvgs = find_fair_value_gaps(h,l); fvg_count = len(fvgs)
272
+ prem,pos = calculate_premium_discount(h,l,c)
273
+ t = df.index[-1]; kz = get_kill_zone_score(t.hour,t.minute)
274
+
275
+ filters = []
276
+ probs_str = f"S:{bias['all_probs']['SELL']:.0%} H:{bias['all_probs']['HOLD']:.0%} B:{bias['all_probs']['BUY']:.0%}"
277
+ filters.append(("Probs","ℹ️",probs_str))
278
+
279
+ if bias['action'] == 'HOLD':
280
+ filters.append(("HOLD","βšͺ",f"HOLD ({bias['confidence']:.0%})"))
281
+ signal = {'timeframe':TF_LABELS.get(tf_name,tf_name),'action':'HOLD','confidence':bias['confidence'],
282
+ 'price':price,'stop_loss':0,'take_profit':0,'rr_ratio':0,'entry_time':'','exit_time':'',
283
+ 'rsi':round(rsi_val,1),'atr':round(atr_val,2),'structure':structure,'bos':bos,'fvg_count':fvg_count,
284
+ 'zone':f"{prem} ({pos:.0f}%)",'footprint':round(footprint,3),'kill_zone':kz,
285
+ 'pass_count':0,'fail_count':1,'warn_count':0,'filters':filters,'all_probs':bias['all_probs']}
286
+ return signal, filters
287
+
288
+ filters.append(("HOLD","βœ…",f"Signal={bias['action']}"))
289
+ fp_status = "βœ…" if abs(footprint)>=0.1 else "❌"
290
+ filters.append(("FP-Neutral",fp_status,f"FP={footprint:.3f}"))
291
+ fp_conflict = (bias['action']=='BUY' and footprint<0.0) or (bias['action']=='SELL' and footprint>0.0)
292
+ filters.append(("FP-Conflict","❌" if fp_conflict else "βœ…","Opposes" if fp_conflict else "Aligned"))
293
+ struct_conflict = (bias['action']=='BUY' and structure=='bearish') or (bias['action']=='SELL' and structure=='bullish')
294
+ filters.append(("Structure","❌" if struct_conflict else "βœ…" if structure!='ranging' else "⚠️",f"{structure}"))
295
+ bos_conflict = (bias['action']=='BUY' and bos=='choch_bearish') or (bias['action']=='SELL' and bos=='choch_bullish')
296
+ filters.append(("BOS/CHoCH","❌" if bos_conflict else "βœ…" if bos!='none' else "⚠️",f"{bos}"))
297
+ zone_conflict = (bias['action']=='BUY' and prem=='premium') or (bias['action']=='SELL' and prem=='discount')
298
+ filters.append(("Zone","❌" if zone_conflict else "βœ…",f"{prem} ({pos:.0f}%)"))
299
+ rsi_conflict = (bias['action']=='BUY' and rsi_val>75) or (bias['action']=='SELL' and rsi_val<25)
300
+ filters.append(("RSI","❌" if rsi_conflict else "βœ…",f"{rsi_val:.1f}"))
301
+ filters.append(("KillZone","βœ…" if kz>=1 else "⚠️",f"KZ={kz}"))
302
+ min_c = regime_params.get('min_conf',0.6)
303
+ conf_ok = bias['confidence']>=min_c
304
+ filters.append(("Confidence","βœ…" if conf_ok else "❌",f"{bias['confidence']:.0%} (min={min_c:.0%})"))
305
+ tf_ok = tf_name in regime_params.get('preferred_tfs',[])
306
+ filters.append(("PreferredTF","βœ…" if tf_ok else "⚠️","Yes" if tf_ok else "No"))
307
+ sl_m = regime_params.get('atr_sl',1.5); tp_m = regime_params.get('atr_tp',2.0)
308
+ if bias['action']=='BUY': sl=round(price-atr_val*sl_m,2); tp=round(price+atr_val*tp_m,2)
309
+ else: sl=round(price+atr_val*sl_m,2); tp=round(price-atr_val*tp_m,2)
310
+ rr = round(abs(tp-price)/abs(sl-price),2) if sl!=price else 0
311
+ filters.append(("R:R","βœ…" if rr>=1.2 else "❌",f"1:{rr}"))
312
+
313
+ pc = sum(1 for _,s,_ in filters if s=="βœ…")
314
+ wc = sum(1 for _,s,_ in filters if s=="⚠️")
315
+ fc = sum(1 for _,s,_ in filters if s=="❌")
316
+
317
+ et = datetime.now(timezone.utc)+timedelta(minutes=1)
318
+ xt = et+timedelta(minutes=tf_minutes*forward_bars)
319
+
320
+ signal = {'timeframe':TF_LABELS.get(tf_name,tf_name),'action':bias['action'],'confidence':bias['confidence'],
321
+ 'price':price,'stop_loss':sl,'take_profit':tp,'rr_ratio':rr,
322
+ 'entry_time':et.strftime('%H:%M UTC'),'exit_time':xt.strftime('%H:%M UTC'),
323
+ 'rsi':round(rsi_val,1),'atr':round(atr_val,2),'structure':structure,'bos':bos,'fvg_count':fvg_count,
324
+ 'zone':f"{prem} ({pos:.0f}%)",'footprint':round(footprint,3),'kill_zone':kz,
325
+ 'pass_count':pc,'fail_count':fc,'warn_count':wc,'filters':filters,'all_probs':bias['all_probs']}
326
+ return signal, filters
327
+
328
+ # ============================================================
329
+ # TELEGRAM
330
+ # ============================================================
331
+
332
+ def send_telegram(msg):
333
+ if not BOT_TOKEN or not CHAT_ID: return
334
+ try:
335
+ requests.post(f"https://api.telegram.org/bot{BOT_TOKEN}/sendMessage",
336
+ data={'chat_id':CHAT_ID,'text':msg,'parse_mode':'HTML'}, timeout=10)
337
+ except Exception as e:
338
+ print(f"⚠️ Telegram: {e}")
339
+
340
+ def build_message(all_signals, session, regime_info):
341
+ now = datetime.now(timezone.utc)
342
+ msg = f"""<b>πŸ€– SMC BOT v9.9</b>
343
+ πŸ• {now.strftime('%H:%M')} UTC | {session}
344
+ πŸ”„ Regime: {regime_info.get('regime','?')}
345
+ πŸ›‘οΈ Filters: Active
346
+ ━━━━━━━━━━━━━━━━━━━━━"""
347
+
348
+ if not all_signals: return msg + "\n\nβšͺ No predictions"
349
+
350
+ emoji = {'BUY':'🟒','SELL':'πŸ”΄','HOLD':'βšͺ'}
351
+ for tf_name in ['5min','30min','1h','2h','4h']:
352
+ result = all_signals.get(tf_name)
353
+ if not result: continue
354
+ signal, filters = result
355
+ e = emoji.get(signal['action'],'🟑')
356
+
357
+ if signal['action'] == 'HOLD': verdict = "βšͺ HOLD"
358
+ elif signal['fail_count'] == 0: verdict = "βœ… PASS"
359
+ else: verdict = f"❌ BLOCKED({signal['fail_count']})"
360
+
361
+ msg += f"\n\n{e} <b>{signal['timeframe']}</b> β†’ {signal['action']} ({signal['confidence']:.0%}) β€” {verdict}"
362
+ msg += f"\n Probs: {signal.get('all_probs',{}).get('SELL',0):.0%}S/{signal.get('all_probs',{}).get('HOLD',0):.0%}H/{signal.get('all_probs',{}).get('BUY',0):.0%}B"
363
+ if signal['action'] != 'HOLD':
364
+ msg += f"\n πŸ’° ${signal['price']} | SL:${signal['stop_loss']} | TP:${signal['take_profit']} | R:R 1:{signal['rr_ratio']}"
365
+ msg += f"\n ─────────────────────────"
366
+ for fn, fs, fd in filters:
367
+ msg += f"\n {fs} {fn:<15s}: {fd}"
368
+
369
+ actions = [all_signals[tf][0]['action'] for tf in all_signals if all_signals[tf]]
370
+ buys = actions.count('BUY'); sells = actions.count('SELL'); holds = actions.count('HOLD')
371
+ msg += f"\n\n━━━━━━━━━━━━━━━━━━━━━\nπŸ“Š BUY:{buys} SELL:{sells} HOLD:{holds}"
372
+ return msg
373
+
374
+ # ============================================================
375
+ # DATA FETCH
376
+ # ============================================================
377
+
378
+ def fetch_5min(outputsize=500):
379
+ if not TWELVEDATA_API_KEY: return None
380
+ try:
381
+ r = requests.get("https://api.twelvedata.com/time_series",
382
+ params={'symbol':'XAU/USD','interval':'5min','outputsize':outputsize,'timezone':'UTC','apikey':TWELVEDATA_API_KEY}, timeout=15)
383
+ if r.status_code == 200:
384
+ data = r.json()
385
+ if 'values' in data and len(data['values']) > 0:
386
+ candles = [{'datetime':pd.to_datetime(b['datetime']).tz_localize('UTC'),
387
+ 'Open':float(b['open']),'High':float(b['high']),
388
+ 'Low':float(b['low']),'Close':float(b['close']),'Volume':0} for b in data['values']]
389
+ df = pd.DataFrame(candles).set_index('datetime').sort_index()
390
+ df = df[df.index.weekday<5]; df = df[~((df.index.weekday==4)&(df.index.hour>=22))]
391
+ return df
392
+ return None
393
+ except: return None
394
+
395
+ def generate_tfs(df5):
396
+ if df5 is None or len(df5)==0: return {}
397
+ data = {'5min':df5}
398
+ df30 = df5.resample('30min',label='right',closed='right').agg({'Open':'first','High':'max','Low':'min','Close':'last','Volume':'sum'}).dropna()
399
+ data['30min'] = df30
400
+ df1h = df5.resample('1h',label='right',closed='right').agg({'Open':'first','High':'max','Low':'min','Close':'last','Volume':'sum'}).dropna()
401
+ data['1h'] = df1h
402
+ df2h = df1h.resample('2h',label='right',closed='right').agg({'Open':'first','High':'max','Low':'min','Close':'last','Volume':'sum'}).dropna()
403
+ data['2h'] = df2h
404
+ df4h = df1h.resample('4h',label='right',closed='right').agg({'Open':'first','High':'max','Low':'min','Close':'last','Volume':'sum'}).dropna()
405
+ data['4h'] = df4h
406
+ return data
407
+
408
+ def candle_just_closed(tf_minutes):
409
+ now = datetime.now(timezone.utc)
410
+ if now.weekday()>=5: return False
411
+ if now.weekday()==4 and now.hour>=22: return False
412
+ return (now.minute%tf_minutes)*60+now.second < 45
413
+
414
+ # ============================================================
415
+ # KEEP-ALIVE
416
+ # ============================================================
417
+
418
+ def keep_alive():
419
+ while True:
420
+ time.sleep(240)
421
+ try: requests.get("https://kulusia-trade.hf.space/health", timeout=5)
422
+ except: pass
423
+
424
+ # ============================================================
425
+ # MAIN BOT LOOP
426
+ # ============================================================
427
+
428
+ def run_bot():
429
+ print("\nπŸ”„ Bot starting...")
430
+ if not models:
431
+ print("❌ No models loaded β€” cannot start")
432
+ return
433
+
434
+ rd = RegimeDetector()
435
+ last_fetch = datetime.now(timezone.utc) - timedelta(minutes=99)
436
+ last_regime = datetime.now(timezone.utc) - timedelta(minutes=10)
437
+ signal_count = 0
438
+ data = {}
439
+
440
+ send_telegram(f"πŸ€– <b>SMC Bot v9.9 LIVE on HF!</b>\nπŸ“Š {len(models)} models\nπŸ” Monitoring XAU/USD")
441
+
442
+ while True:
443
+ try:
444
+ now = datetime.now(timezone.utc)
445
+ session = get_current_session()
446
+
447
+ if 'WEEKEND' in session:
448
+ time.sleep(300); continue
449
+
450
+ any_fetched = False
451
+ seconds_since = (now - last_fetch).total_seconds()
452
+
453
+ if seconds_since >= 285 and candle_just_closed(5):
454
+ print(f"⏰ {now.strftime('%H:%M')} β€” fetching...")
455
+ nd = fetch_5min(500)
456
+ if nd is not None and len(nd) > 0:
457
+ if '5min' in data:
458
+ new_bars = nd[~nd.index.isin(data['5min'].index)]
459
+ if len(new_bars) > 0:
460
+ data['5min'] = pd.concat([data['5min'], new_bars])
461
+ data['5min'] = data['5min'][~data['5min'].index.duplicated(keep='last')]
462
+ data['5min'].sort_index(inplace=True)
463
+ print(f" βœ… +{len(new_bars)} bars | Total: {len(data['5min']):,}")
464
+ last_fetch = now; any_fetched = True
465
+ else:
466
+ data['5min'] = nd
467
+ last_fetch = now; any_fetched = True
468
+ print(f" βœ… Initial: {len(nd):,} bars")
469
+
470
+ time_since_regime = (now - last_regime).total_seconds()
471
+
472
+ if any_fetched or time_since_regime >= 300:
473
+ if any_fetched and '5min' in data:
474
+ data = generate_tfs(data['5min'])
475
+
476
+ if '1h' in data and len(data['1h']) >= 100:
477
+ ri = rd.detect(data['1h']); last_regime = now
478
+ else:
479
+ ri = {'regime':'NORMAL','confidence':0.5,'parameters':{'atr_sl':1.5,'atr_tp':2.0,'min_conf':0.6,'max_risk':1.0,'preferred_tfs':['5min','30min','1h','2h','4h']}}
480
+
481
+ all_signals = {}
482
+ for tf_name in TIMEFRAMES:
483
+ if tf_name in models and tf_name in data and len(data[tf_name]) >= 201:
484
+ sig, filters = analyze_signal(
485
+ models[tf_name], data[tf_name], tf_name,
486
+ TIMEFRAMES[tf_name]['minutes'], TIMEFRAMES[tf_name]['fwd'],
487
+ ri.get('parameters',{})
488
+ )
489
+ if sig: all_signals[tf_name] = (sig, filters)
490
+
491
+ if all_signals:
492
+ signal_count += 1
493
+ msg = build_message(all_signals, session, ri)
494
+ send_telegram(msg)
495
+ print(f"πŸ“ Signal #{signal_count} β†’ Telegram")
496
+
497
+ for tf_name, (sig, _) in all_signals.items():
498
+ status = "βœ…" if sig['fail_count']==0 else f"❌({sig['fail_count']})"
499
+ print(f" {sig['timeframe']}: {sig['action']} {sig['confidence']:.0%} | {status}")
500
+
501
+ time.sleep(10)
502
+
503
+ except Exception as e:
504
+ print(f"⚠️ Error: {e}")
505
+ time.sleep(60)
506
+
507
+ # ============================================================
508
+ # START
509
+ # ============================================================
510
+ threading.Thread(target=keep_alive, daemon=True).start()
511
+ print("πŸ’“ Keep-alive active")
512
+ threading.Thread(target=run_bot, daemon=True).start()
513
+
514
+ if __name__ == '__main__':
515
+ port = int(os.environ.get('PORT', 7860))
516
+ app.run(host='0.0.0.0', port=port)