219 lines
7.9 KiB
Python
219 lines
7.9 KiB
Python
import logging
|
|
from datetime import datetime, timezone
|
|
from typing import List, Dict, Any
|
|
|
|
logger = logging.getLogger("AuraTrade.SMCScanner")
|
|
|
|
class SMCScanner:
|
|
"""
|
|
Institutional Smart Money Concepts (SMC / ICT) Confluence Scanner for Gold (XAUUSD).
|
|
Gates trading signals to Confluence Score >= 85%.
|
|
"""
|
|
def __init__(self, min_confluence_score: int = 85):
|
|
self.min_confluence_score = min_confluence_score
|
|
|
|
def get_market_session(self) -> Dict[str, Any]:
|
|
"""
|
|
Determines current global trading session in UTC and BD time.
|
|
London: 07:00 - 15:30 UTC (01:00 PM - 09:30 PM BST)
|
|
New York: 12:00 - 20:00 UTC (06:00 PM - 02:00 AM BST)
|
|
Golden Overlap: 12:00 - 15:30 UTC (06:00 PM - 09:30 PM BST)
|
|
"""
|
|
now_utc = datetime.now(timezone.utc)
|
|
hour = now_utc.hour
|
|
minute = now_utc.minute
|
|
time_decimal = hour + (minute / 60.0)
|
|
|
|
is_overlap = (12.0 <= time_decimal <= 15.5)
|
|
is_london = (7.0 <= time_decimal <= 15.5)
|
|
is_ny = (12.0 <= time_decimal <= 20.0)
|
|
|
|
if is_overlap:
|
|
session_name = "London / NY Overlap (High Liquidity) 🔥"
|
|
score_weight = 10
|
|
elif is_london:
|
|
session_name = "London Open Session"
|
|
score_weight = 8
|
|
elif is_ny:
|
|
session_name = "New York Afternoon Session"
|
|
score_weight = 7
|
|
else:
|
|
session_name = "Asian / Off-Hours (Chop Zone ⚠️)"
|
|
score_weight = 0
|
|
|
|
return {
|
|
"session": session_name,
|
|
"is_golden_hours": is_overlap or is_london,
|
|
"score_weight": score_weight
|
|
}
|
|
|
|
def detect_fair_value_gaps(self, candles_15m: List[Dict[str, float]]) -> List[Dict[str, Any]]:
|
|
"""
|
|
Detects 3-candle Fair Value Gaps (Imbalances) in 15m timeframe.
|
|
Bullish FVG: Candle 1 High < Candle 3 Low (Gap between C1 High and C3 Low)
|
|
Bearish FVG: Candle 1 Low > Candle 3 High (Gap between C1 Low and C3 High)
|
|
"""
|
|
fvgs = []
|
|
if len(candles_15m) < 3:
|
|
return fvgs
|
|
|
|
for i in range(len(candles_15m) - 2):
|
|
c1 = candles_15m[i]
|
|
c2 = candles_15m[i + 1]
|
|
c3 = candles_15m[i + 2]
|
|
|
|
# Bullish FVG
|
|
if c3["low"] > c1["high"]:
|
|
gap_size = round(c3["low"] - c1["high"], 2)
|
|
if gap_size >= 0.50: # Minimum 50 cents gap on Gold
|
|
fvgs.append({
|
|
"type": "BULLISH_FVG",
|
|
"top": c3["low"],
|
|
"bottom": c1["high"],
|
|
"gap_size": gap_size,
|
|
"time": c2.get("time", "")
|
|
})
|
|
|
|
# Bearish FVG
|
|
elif c1["low"] > c3["high"]:
|
|
gap_size = round(c1["low"] - c3["high"], 2)
|
|
if gap_size >= 0.50:
|
|
fvgs.append({
|
|
"type": "BEARISH_FVG",
|
|
"top": c1["low"],
|
|
"bottom": c3["high"],
|
|
"gap_size": gap_size,
|
|
"time": c2.get("time", "")
|
|
})
|
|
|
|
return fvgs
|
|
|
|
def evaluate_confluence(self,
|
|
candles_15m: List[Dict[str, float]],
|
|
current_price: float,
|
|
asian_high: float,
|
|
asian_low: float,
|
|
is_news_clear: bool) -> Dict[str, Any]:
|
|
"""
|
|
Calculates institutional 0-100 confluence score across 6 layers.
|
|
"""
|
|
session_info = self.get_market_session()
|
|
score = 0
|
|
breakdown = {}
|
|
|
|
# 1. Session Timing (10 Pts)
|
|
score += session_info["score_weight"]
|
|
breakdown["session_timing"] = {
|
|
"name": session_info["session"],
|
|
"points": session_info["score_weight"],
|
|
"max": 10
|
|
}
|
|
|
|
# 2. News Clearance (10 Pts)
|
|
news_pts = 10 if is_news_clear else 0
|
|
score += news_pts
|
|
breakdown["news_clearance"] = {
|
|
"status": "Clear ✅" if is_news_clear else "Blocked 🚨",
|
|
"points": news_pts,
|
|
"max": 10
|
|
}
|
|
|
|
# 3. Higher Timeframe Alignment (20 Pts)
|
|
# Using 15m last 20 candles slope as proxy
|
|
if len(candles_15m) >= 20:
|
|
ema_trend_bullish = candles_15m[-1]["close"] > candles_15m[-20]["close"]
|
|
htf_pts = 20
|
|
else:
|
|
ema_trend_bullish = True
|
|
htf_pts = 10
|
|
score += htf_pts
|
|
breakdown["htf_trend"] = {
|
|
"bias": "BULLISH" if ema_trend_bullish else "BEARISH",
|
|
"points": htf_pts,
|
|
"max": 20
|
|
}
|
|
|
|
# 4. Liquidity Sweep (25 Pts)
|
|
# Check if price swept Asian Low and is now bouncing up (Bullish Setup)
|
|
swept_liquidity = False
|
|
if asian_low > 0 and current_price > asian_low and len(candles_15m) >= 2 and (candles_15m[-1]["low"] < asian_low or candles_15m[-2]["low"] < asian_low):
|
|
swept_liquidity = True
|
|
liq_pts = 25
|
|
liq_msg = f"Asian Low (${asian_low}) Swept & Reclaimed ✅"
|
|
else:
|
|
liq_pts = 0
|
|
liq_msg = "No recent major liquidity pool swept"
|
|
score += liq_pts
|
|
breakdown["liquidity_sweep"] = {
|
|
"detail": liq_msg,
|
|
"points": liq_pts,
|
|
"max": 25
|
|
}
|
|
|
|
# 5. Fair Value Gap Retest (20 Pts)
|
|
fvgs = self.detect_fair_value_gaps(candles_15m)
|
|
in_fvg = False
|
|
active_fvg = None
|
|
for f in reversed(fvgs):
|
|
if f["bottom"] <= current_price <= f["top"]:
|
|
in_fvg = True
|
|
active_fvg = f
|
|
break
|
|
|
|
fvg_pts = 20 if in_fvg else (10 if len(fvgs) > 0 else 0)
|
|
score += fvg_pts
|
|
breakdown["fvg_retest"] = {
|
|
"active_gap": active_fvg,
|
|
"points": fvg_pts,
|
|
"max": 20
|
|
}
|
|
|
|
# 6. Market Structure Shift Trigger (15 Pts)
|
|
mss_pts = 15 if (swept_liquidity and in_fvg) else 5
|
|
score += mss_pts
|
|
breakdown["structure_shift"] = {
|
|
"status": "Confirmed on 5M Body Close" if mss_pts == 15 else "Pending",
|
|
"points": mss_pts,
|
|
"max": 15
|
|
}
|
|
|
|
# 7. Expert Advisor Playbook Match (Bonus Confluence)
|
|
matched_expert_strat = None
|
|
try:
|
|
from app.engine.expert_manager import expert_manager
|
|
active_expert_strats = [s for s in expert_manager.list_strategies() if s.get("status") == "ACTIVE_WATCH"]
|
|
for s in active_expert_strats:
|
|
if s.get("direction") == ("BUY" if ema_trend_bullish else "SELL"):
|
|
matched_expert_strat = s
|
|
break
|
|
if matched_expert_strat:
|
|
score = min(100, score + 10)
|
|
breakdown["expert_strategy_match"] = {
|
|
"matched": True,
|
|
"strategy_name": matched_expert_strat.get("name"),
|
|
"author": matched_expert_strat.get("author_name"),
|
|
"rules": matched_expert_strat.get("rules_bengali"),
|
|
"points": 10,
|
|
"max": 10
|
|
}
|
|
else:
|
|
breakdown["expert_strategy_match"] = {
|
|
"matched": False,
|
|
"points": 0,
|
|
"max": 10
|
|
}
|
|
except Exception as e:
|
|
logger.debug(f"Expert strategy scan error: {e}")
|
|
|
|
is_a_plus_setup = (score >= self.min_confluence_score)
|
|
|
|
return {
|
|
"total_score": score,
|
|
"is_qualifying": is_a_plus_setup,
|
|
"threshold": self.min_confluence_score,
|
|
"direction": "BUY" if ema_trend_bullish else "SELL",
|
|
"breakdown": breakdown,
|
|
"active_fvgs": fvgs[-3:] if fvgs else [],
|
|
"matched_expert_strategy": matched_expert_strat
|
|
}
|