-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhourly_breakout_scanner.py
More file actions
665 lines (548 loc) Β· 26.8 KB
/
hourly_breakout_scanner.py
File metadata and controls
665 lines (548 loc) Β· 26.8 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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
#!/usr/bin/env python3
"""
hourly_breakout_scanner.py
Hourly intraday breakout scanner for watchlist symbols:
- Reads symbols from watchlist.csv
- Fetches intraday data (5-minute candles)
- Detects real-time breakouts
- Sends alerts for immediate action
"""
import os
import sys
import pandas as pd
import numpy as np
import requests
import time
from datetime import datetime, timedelta
from dotenv import load_dotenv
import logging
# Load environment
load_dotenv()
# Logging
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(message)s")
logger = logging.getLogger(__name__)
# Configuration
# Metadata & State (Legacy CSVs removed, using MongoDB)
INTRADAY_INTERVAL = "5minute" # 1minute, 5minute, 15minute, 30minute, 60minute
LOOKBACK_DAYS = 5 # Days of intraday data to fetch
MIN_VOLUME_MULTIPLIER = 1.5 # Minimum volume spike for breakout
# Telegram configuration
BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")
CHAT_ID = os.getenv("TELEGRAM_CHAT_ID")
# Add current directory to path
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
# Import from main scanner
import importlib.util
spec = importlib.util.spec_from_file_location("scanner", "streamlined_ipo_scanner.py")
scanner_module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(scanner_module)
# Import shared utilities
get_market_regime = scanner_module.get_market_regime
classify_pattern_type = scanner_module.classify_pattern_type
SCANNER_VERSION = "2.5.0"
def write_daily_log(scanner_name, symbol, action, details=None, candle_timestamp=None, log_type="ACCEPTED"):
"""Write scanner telemetry to MongoDB only (single-write path)."""
try:
from datetime import timezone, timedelta as td
ist = timezone(td(hours=5, minutes=30))
now_ist = datetime.now(ist)
# DB-only write: use provided candle_timestamp if available, else fall back to now_ist
try:
from db import insert_log
effective_candle_ts = candle_timestamp if candle_timestamp is not None else now_ist
insert_log(
scanner=scanner_name, symbol=symbol, action=action,
candle_timestamp=effective_candle_ts,
details=details or {}, version=SCANNER_VERSION, source="live",
log_type=log_type
)
except Exception as db_e:
logger.error(f"[MongoDB] log write FAILED for {symbol}/{action}: {db_e}")
try:
from db import db_metrics
db_metrics["failures"] = db_metrics.get("failures", 0) + 1
except Exception:
pass
except Exception as e:
logger.debug(f"Could not write daily log: {e}")
def send_telegram(msg):
"""Send Telegram notification"""
if not BOT_TOKEN or not CHAT_ID:
logger.warning(f"[Telegram disabled] BOT_TOKEN: {'SET' if BOT_TOKEN else 'MISSING'}, CHAT_ID: {'SET' if CHAT_ID else 'MISSING'}")
return
url = f"https://api.telegram.org/bot{BOT_TOKEN}/sendMessage"
try:
response = requests.post(url, json={
"chat_id": CHAT_ID,
"text": msg,
"parse_mode": "HTML",
"disable_notification": False
}, timeout=10)
if response.status_code == 200:
logger.info("β
Telegram message sent successfully!")
else:
logger.error(f"β Telegram API error: {response.status_code} - {response.text}")
except Exception as e:
logger.error(f"β Telegram error: {e}")
def load_watchlist():
"""Load active symbols from MongoDB watchlist collection."""
try:
from db import watchlist_col
if watchlist_col is None:
logger.warning("[DB] watchlist_col unavailable")
return []
docs = list(watchlist_col.find({"status": "ACTIVE"}, {"symbol": 1, "_id": 0}))
active_symbols = [d["symbol"] for d in docs if d.get("symbol")]
logger.info(f"π Loaded {len(active_symbols)} active symbols from MongoDB watchlist")
return active_symbols
except Exception as e:
logger.error(f"Error loading watchlist from MongoDB: {e}")
return []
# Try to import yfinance for intraday data
try:
import yfinance as yf
YFINANCE_AVAILABLE = True
except ImportError:
YFINANCE_AVAILABLE = False
def fetch_intraday_data_yfinance(symbol, interval=INTRADAY_INTERVAL):
"""Fetch intraday data from yfinance API with rate limiting"""
if not YFINANCE_AVAILABLE:
return None
try:
# Rate limiting: 200ms minimum delay
time.sleep(0.2)
# Map interval to yfinance format
interval_map = {
'1minute': '1m',
'5minute': '5m',
'15minute': '15m',
'30minute': '30m',
'60minute': '1h'
}
yf_interval = interval_map.get(interval, '5m')
# NSE symbols need .NS suffix
ticker_symbol = f"{symbol}.NS"
ticker = yf.Ticker(ticker_symbol)
# Fetch intraday data (max 7 days for intraday)
period = min(LOOKBACK_DAYS, 7)
df = ticker.history(period=f"{period}d", interval=yf_interval)
if df.empty:
return None
# Rename columns to match expected format
df = df.reset_index()
df.columns = ['DATE', 'OPEN', 'HIGH', 'LOW', 'CLOSE', 'VOLUME']
df['LTP'] = df['CLOSE']
# Ensure DATE is datetime (should already be from yfinance, but verify)
if not pd.api.types.is_datetime64_any_dtype(df['DATE']):
df['DATE'] = pd.to_datetime(df['DATE'])
# Sort by date (ascending - oldest to newest)
df = df.sort_values('DATE').reset_index(drop=True)
logger.info(f"β
Got {len(df)} intraday candles from yfinance for {symbol}")
return df
except Exception as e:
logger.warning(f"β οΈ yfinance error for {symbol}: {e}")
return None
def fetch_intraday_data_upstox(symbol, interval=INTRADAY_INTERVAL):
"""Fetch intraday data from Upstox API"""
try:
# Load IPO mappings
try:
from db import get_instrument_key_mapping
mapping = get_instrument_key_mapping()
instrument_key = mapping.get(symbol)
if not instrument_key:
logger.warning(f"Symbol {symbol} not found in Upstox mapping (MongoDB)")
return None
except Exception as e:
logger.warning(f"Error getting Upstox mapping from MongoDB for {symbol}: {e}")
return None
# Get Upstox credentials
access_token = os.getenv('UPSTOX_ACCESS_TOKEN')
if not access_token:
logger.warning("Upstox access token not found")
return None
# Prepare API request
headers = {
'Accept': 'application/json',
'Api-Version': '2.0',
'Authorization': f'Bearer {access_token}'
}
# Calculate date range
end_date = datetime.now()
start_date = end_date - timedelta(days=LOOKBACK_DAYS)
# Format dates for Upstox API
from_str = start_date.strftime('%Y-%m-%d')
to_str = end_date.strftime('%Y-%m-%d')
# Upstox intraday API endpoint
url = f"https://api.upstox.com/v2/historical-candle/{instrument_key}/{interval}/{to_str}/{from_str}"
logger.info(f"π Fetching intraday data for {symbol} ({interval})...")
response = requests.get(url, headers=headers, timeout=30)
# Handle rate limiting
if response.status_code == 429:
logger.warning(f"β οΈ Rate limited for {symbol}, waiting 1 second...")
time.sleep(1)
response = requests.get(url, headers=headers, timeout=30)
if response.status_code == 200:
data = response.json()
if 'data' in data and 'candles' in data['data']:
candles = data['data']['candles']
if candles:
# Convert to DataFrame
df = pd.DataFrame(candles, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume', 'close'])
# Handle timestamp conversion
try:
df['DATE'] = pd.to_datetime(df['timestamp'], unit='s')
except:
try:
df['DATE'] = pd.to_datetime(df['timestamp'])
except:
df['DATE'] = pd.to_datetime(df['timestamp'], format='%Y-%m-%d %H:%M:%S')
df.columns = ['timestamp', 'OPEN', 'HIGH', 'LOW', 'CLOSE', 'VOLUME', 'IGNORE', 'DATE']
df = df[['DATE', 'OPEN', 'HIGH', 'LOW', 'CLOSE', 'VOLUME']]
df['LTP'] = df['CLOSE']
# Ensure DATE is datetime (should already be, but verify for consistency)
if not pd.api.types.is_datetime64_any_dtype(df['DATE']):
df['DATE'] = pd.to_datetime(df['DATE'])
# Sort by date (ascending - oldest to newest)
df = df.sort_values('DATE').reset_index(drop=True)
logger.info(f"β
Got {len(df)} intraday candles for {symbol}")
return df
logger.warning(f"β οΈ No intraday data for {symbol}")
return None
except Exception as e:
logger.warning(f"β οΈ Upstox API error for {symbol}: {e}")
return None
def fetch_intraday_data(symbol, interval=INTRADAY_INTERVAL):
"""
Fetch intraday data from multiple sources with fallback:
1. Upstox API (if available)
2. yfinance (fallback)
Returns DataFrame or None
"""
# Try Upstox first
df = fetch_intraday_data_upstox(symbol, interval)
if df is not None and not df.empty:
return df
# Fallback to yfinance
logger.info(f"β οΈ Upstox failed, trying yfinance for {symbol}...")
df = fetch_intraday_data_yfinance(symbol, interval)
if df is not None and not df.empty:
return df
logger.warning(f"β οΈ Could not fetch intraday data for {symbol} from any source")
return None
def compute_rsi(close, period=14):
"""Calculate RSI"""
delta = close.diff()
gain = (delta.where(delta > 0, 0)).rolling(window=period).mean()
loss = (-delta.where(delta < 0, 0)).rolling(window=period).mean()
rs = gain / loss
return 100 - (100 / (1 + rs))
def detect_intraday_breakout(df, symbol):
"""Detect intraday breakout patterns using LIVE prices for accurate detection"""
if df is None or len(df) < 20:
return None
try:
# Get recent data (last 2 days of intraday candles)
# For 5-minute candles: 2 days = ~96 candles (assuming 9:15 AM to 3:30 PM = 6.25 hours = 75 candles/day)
recent_df = df.tail(150) # Last 150 candles (~2 days)
if len(recent_df) < 20:
return None
# Calculate consolidation levels from historical data (exclude last candle for accurate range)
historical_df = recent_df.iloc[:-1] if len(recent_df) > 1 else recent_df
# Calculate recent high and low from historical data (excluding current candle)
recent_high = historical_df['HIGH'].max() if len(historical_df) > 0 else recent_df['HIGH'].max()
recent_low = historical_df['LOW'].min() if len(historical_df) > 0 else recent_df['LOW'].min()
# Calculate consolidation range (last 50 candles, excluding current)
consolidation_df = historical_df.tail(50) if len(historical_df) >= 50 else historical_df
consolidation_low = consolidation_df['LOW'].min() if len(consolidation_df) > 0 else recent_low
consolidation_high = consolidation_df['HIGH'].max() if len(consolidation_df) > 0 else recent_high
# Get historical data for volume/RSI calculations
current_volume = recent_df['VOLUME'].iloc[-1]
avg_volume = historical_df['VOLUME'].mean() if len(historical_df) > 0 else current_volume
# CRITICAL: Get LIVE price for accurate breakout detection
live_price = None
live_source = "Historical"
try:
# Import get_live_price from main scanner
import importlib.util
spec = importlib.util.spec_from_file_location("scanner", "streamlined_ipo_scanner.py")
scanner_module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(scanner_module)
get_live_price = scanner_module.get_live_price
live_price, live_source, _ = get_live_price(symbol)
if live_price is not None and live_price > 0:
logger.info(f"β
Using live price for {symbol} breakout detection: βΉ{live_price:.2f} ({live_source})")
except Exception as e:
logger.debug(f"Could not get live price for {symbol}: {e}")
# Use live price if available, otherwise use latest historical close
if live_price is not None:
current_price = live_price
current_high = live_price # For breakout detection, use live price as current high
else:
current_price = float(recent_df['CLOSE'].iloc[-1])
current_high = float(recent_df['HIGH'].iloc[-1])
live_source = "Historical" # Ensure source is set to Historical when using historical data
logger.warning(f"β οΈ Using historical price for {symbol}: βΉ{current_price:.2f}")
# Breakout conditions:
# 1. Current price/high breaks above recent high (using LIVE price if available)
# 2. Volume spike (at least 1.5x average)
# 3. RSI momentum confirmation
is_breakout = False
breakout_strength = 0
# Check if price breaks above recent high
if current_high > recent_high:
is_breakout = True
breakout_strength += 1
logger.info(f"π₯ {symbol}: Price broke above recent high! ({current_high:.2f} > {recent_high:.2f}) [Using: {live_source}]")
# Volume confirmation
if current_volume >= avg_volume * MIN_VOLUME_MULTIPLIER:
breakout_strength += 1
logger.info(f"π {symbol}: Volume spike detected! ({current_volume:,.0f} vs avg {avg_volume:,.0f})")
# Calculate RSI for momentum confirmation
rsi = compute_rsi(recent_df['CLOSE'])
current_rsi = rsi.iloc[-1] if len(rsi) > 0 else 50
if current_rsi > 60: # Strong momentum
breakout_strength += 1
# Only trigger if we have a clear breakout
if is_breakout and breakout_strength >= 2:
consolidation_range = consolidation_high - consolidation_low
# Entry price: Use LIVE price if available, otherwise current price
entry_price = current_price
# Stop loss (below consolidation low) - use proper calculation
# Use the lower (more conservative) stop loss: 2% below consolidation low OR 5% of range below, whichever is LOWER
stop_loss_1 = consolidation_low * 0.98 # 2% below consolidation low
stop_loss_2 = consolidation_low - (consolidation_range * 0.05) # 5% of range below
stop_loss = min(stop_loss_1, stop_loss_2) # Use the lower (more conservative) stop
# Target (based on consolidation range) - add 50% of range above consolidation high
target_price = consolidation_high + (consolidation_range * 0.5)
# Risk/Reward
risk = entry_price - stop_loss
reward = target_price - entry_price
risk_reward = reward / risk if risk > 0 else 0
logger.info(f"π {symbol} Breakout Levels:")
logger.info(f" Consolidation: βΉ{consolidation_low:.2f} - βΉ{consolidation_high:.2f}")
logger.info(f" Recent High: βΉ{recent_high:.2f}")
logger.info(f" Entry: βΉ{entry_price:.2f} ({live_source})")
logger.info(f" Stop Loss: βΉ{stop_loss:.2f}")
logger.info(f" Target: βΉ{target_price:.2f}")
logger.info(f" Risk:Reward: 1:{risk_reward:.2f}")
return {
'symbol': symbol,
'entry_price': round(entry_price, 2),
'stop_loss': round(stop_loss, 2),
'target_price': round(target_price, 2),
'current_price': round(current_price, 2),
'recent_high': round(recent_high, 2),
'consolidation_low': round(consolidation_low, 2),
'consolidation_high': round(consolidation_high, 2),
'volume_spike': round(current_volume / avg_volume, 2),
'rsi': round(current_rsi, 2),
'risk_reward': round(risk_reward, 2),
'breakout_strength': breakout_strength,
'price_source': live_source,
'entry_vs_breakout_pct': round(((entry_price / recent_high) - 1.0) * 100.0, 2) if recent_high > 0 else None,
'post_confirm_move_pct': round(((current_price / recent_high) - 1.0) * 100.0, 2) if recent_high > 0 else None,
'held_above_breakout_after_confirm': bool(current_price >= recent_high),
'signal_strength_score': round(float(breakout_strength) * 3.33, 2),
'tier_weight': None,
'volume_score': round(min(2.0, (current_volume / avg_volume) / 2.0), 2) if avg_volume > 0 else None,
'base_score': 1.0,
'momentum_score': round(min(2.0, max(0.0, (current_rsi - 50.0) / 10.0)), 2) if current_rsi is not None else None,
'pattern_type': classify_pattern_type("INTRADAY", 30, breakout_strength/2.0, 10),
'market_regime': get_market_regime(),
'timestamp': datetime.now()
}
return None
except Exception as e:
logger.error(f"Error detecting breakout for {symbol}: {e}")
return None
def format_intraday_alert(breakout_data):
"""Format intraday breakout alert"""
symbol = breakout_data['symbol']
entry = breakout_data['entry_price']
stop = breakout_data['stop_loss']
target = breakout_data['target_price']
current = breakout_data['current_price']
rsi = breakout_data['rsi']
vol_spike = breakout_data['volume_spike']
rr = breakout_data['risk_reward']
strength = breakout_data['breakout_strength']
price_source = breakout_data.get('price_source', 'Historical')
# Add emoji for price source
source_emojis = {
'upstox': 'π',
'yfinance': 'π',
'jugaad': 'π',
'Historical': 'π'
}
emoji = source_emojis.get(price_source.lower(), 'π°')
msg = f"""β‘ <b>INTRADAY BREAKOUT DETECTED</b>
π Symbol: <b>{symbol}</b>
π° Current Price: βΉ{current:,.2f} ({emoji} {price_source})
π― Entry: βΉ{entry:,.2f}
π Stop Loss: βΉ{stop:,.2f}
π Target: βΉ{target:,.2f}
π Risk:Reward: 1:{rr:.1f}
π <b>Breakout Metrics:</b>
β’ RSI: {rsi:.1f}
β’ Volume Spike: {vol_spike:.1f}x
β’ Pattern: <b>{breakout_data.get('pattern_type', 'N/A')}</b>
β’ Regime: <b>{breakout_data.get('market_regime', 'N/A')}</b>
β’ Breakout Strength: {strength}/3
β° Time: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
β οΈ <b>Action Required:</b> Review immediately for entry opportunity"""
return msg
def save_breakout_signal(breakout_data):
"""Save breakout signal to CSV"""
try:
# Get actual candle timestamp for determinism β use market event time, not system time
candle_ts = breakout_data.get('timestamp', datetime.now())
if not hasattr(candle_ts, 'strftime'):
candle_ts = datetime.now()
candle_time = candle_ts.strftime('%H%M')
# signal_date tied to market candle date, not execution date
signal_date = candle_ts.date() if hasattr(candle_ts, 'date') else datetime.now().date()
signal_id = f"INTRADAY_{breakout_data['symbol']}_{signal_date.strftime('%Y%m%d')}_{candle_time}"
# Check if we already have a signal for this symbol today
try:
from db import signals_col
if signals_col is not None:
existing = signals_col.count_documents({
"symbol": breakout_data['symbol'],
"signal_date": signal_date.strftime('%Y-%m-%d') if isinstance(signal_date, datetime) else str(signal_date)
})
if existing > 0:
logger.info(f"Signal already exists for {breakout_data['symbol']} today")
return False
except Exception as e:
logger.warning(f"Error checking MongoDB for existing signals: {e}")
# Create new signal
new_signal = {
"signal_id": signal_id,
"symbol": breakout_data['symbol'],
"signal_date": signal_date.strftime('%Y-%m-%d') if hasattr(signal_date, 'strftime') else str(signal_date),
"entry_price": breakout_data['entry_price'],
"grade": "INTRADAY",
"score": breakout_data['breakout_strength'] * 10,
"stop_loss": breakout_data['stop_loss'],
"target_price": breakout_data['target_price'],
"status": "ACTIVE",
"exit_date": "",
"exit_price": 0,
"pnl_pct": 0,
"days_held": 0,
"signal_type": "INTRADAY",
"scanner": "hourly_breakout_scanner"
}
# MongoDB write: signal
try:
from db import upsert_signal
upsert_signal(new_signal.copy())
except Exception as db_e:
logger.error(f"[MongoDB] signal write FAILED for {signal_id}: {db_e}")
try:
from db import db_metrics
db_metrics["failures"] = db_metrics.get("failures", 0) + 1
except Exception:
pass
logger.info(f"β
Saved breakout signal for {breakout_data['symbol']}")
return True
except Exception as e:
logger.error(f"Error saving signal: {e}")
return False
def scan_watchlist():
"""Scan all symbols in watchlist for breakouts"""
logger.info("π Starting hourly intraday breakout scan...")
logger.info("=" * 60)
# Load watchlist
symbols = load_watchlist()
if not symbols:
logger.warning("No active symbols in watchlist")
return
logger.info(f"π Scanning {len(symbols)} symbols...")
breakouts_found = 0
for i, symbol in enumerate(symbols, 1):
logger.info(f"\n[{i}/{len(symbols)}] Scanning {symbol}...")
try:
# Fetch intraday data (tries Upstox first, then yfinance)
df = fetch_intraday_data(symbol)
if df is None or df.empty:
logger.warning(f"β οΈ No data for {symbol}")
continue
# Detect breakout
breakout = detect_intraday_breakout(df, symbol)
if breakout:
logger.info(f"π― BREAKOUT DETECTED for {symbol}!")
write_daily_log("watchlist", symbol, "SIGNAL_GENERATED", {
"entry": breakout.get("entry_price"),
"stop_loss": breakout.get("stop_loss"),
"target": breakout.get("target_price"),
"breakout_level": breakout.get("recent_high"),
"entry_vs_breakout_pct": breakout.get("entry_vs_breakout_pct"),
"post_confirm_move_pct": breakout.get("post_confirm_move_pct"),
"held_above_breakout_after_confirm": breakout.get("held_above_breakout_after_confirm"),
"signal_strength_score": breakout.get("signal_strength_score"),
"tier_weight": breakout.get("tier_weight"),
"volume_score": breakout.get("volume_score"),
"base_score": breakout.get("base_score"),
"momentum_score": breakout.get("momentum_score"),
"volume_ratio": breakout.get("volume_spike"),
"risk_reward_ratio": breakout.get("risk_reward"),
"price_source": breakout.get("price_source"),
})
# Save signal
if save_breakout_signal(breakout):
# Send alert
alert_msg = format_intraday_alert(breakout)
send_telegram(alert_msg)
breakouts_found += 1
# Small delay to avoid rate limiting
time.sleep(0.5)
else:
logger.info(f"β
{symbol}: No breakout detected")
write_daily_log("watchlist", symbol, "REJECTED_BREAKOUT", {
"rejection_reason": "no_intraday_breakout",
"failing_metric": "breakout",
"failing_value": breakout if breakout is not None else 0,
"threshold": "breakout_strength>=2 and price>recent_high",
"metrics": {"breakout": breakout},
"volume_ratio": None,
}, log_type="REJECTED")
# Rate limiting between symbols
time.sleep(0.3)
except Exception as e:
logger.error(f"Error scanning {symbol}: {e}")
continue
logger.info(f"\n{'='*60}")
logger.info(f"β
Scan complete: {breakouts_found} breakouts found")
try:
from db import db_metrics
db_stats = {
"symbols_scanned": len(symbols),
"signals_found": breakouts_found,
"db_signals": db_metrics.get("signals_generated", 0),
"db_logs": db_metrics.get("logs_written", 0),
"db_failures": db_metrics.get("failures", 0)
}
except Exception:
db_stats = {"symbols_scanned": len(symbols), "signals_found": breakouts_found}
write_daily_log("watchlist", "SYSTEM", "SCAN_COMPLETED", db_stats)
# Send summary
if breakouts_found > 0:
summary = f"""π <b>Hourly Breakout Scan Summary</b>
π Symbols Scanned: {len(symbols)}
π― Breakouts Found: {breakouts_found}
β° Time: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
π§― DB Status: {'β
OK' if db_stats.get('db_failures', 0) == 0 else f"β {db_stats.get('db_failures')} FAILURES"}
{'π New breakouts detected! Check alerts above.' if breakouts_found > 0 else 'β
No new breakouts at this time.'}"""
send_telegram(summary)
def main():
"""Main function"""
print("β‘ Hourly Intraday Breakout Scanner")
print("=" * 60)
print(f"π
Date: {datetime.now().strftime('%Y-%m-%d')}")
print(f"β° Time: {datetime.now().strftime('%H:%M:%S')}")
print("=" * 60)
scan_watchlist()
if __name__ == "__main__":
main()