""" Multi-Timeframe Analyzer (Expanded: 1D, 4H, 1H, 15M, 5M) ========================================================= Determines the 'active' timeframe for a symbol based on recent volatility (ATR ratio) and computes market structure (HH+HL = bullish, LH+LL = bearish, etc.) across ALL timeframes from Macro (1D) to Scalp/Trigger (5M). """ import logging from typing import Any logger = logging.getLogger(__name__) def _valid_ohlc_candles(candles: list[dict]) -> list[dict]: """Filter candles to rows that contain non-null high, low, and close values.""" if not candles: return [] return [ c for c in candles if isinstance(c, dict) and c.get("high") is not None and c.get("low") is not None and c.get("close") is not None ] def _atr(candles: list[dict], period: int = 14) -> float: """Average True Range over the most recent `period` candles.""" valid = _valid_ohlc_candles(candles) if len(valid) < 2: return 0.0 recent = valid[-(period + 1):] trs = [] for i in range(1, len(recent)): high = float(recent[i]["high"]) low = float(recent[i]["low"]) prev_close = float(recent[i - 1]["close"]) tr = max(high - low, abs(high - prev_close), abs(low - prev_close)) trs.append(tr) return sum(trs) / len(trs) if trs else 0.0 def _atr_ratio(candles: list[dict], period: int = 14, lookback: int = 100) -> float: """ Current ATR / Average ATR over lookback candles. > 2.5 → extreme volatility / macro breakout (1D / 4H) > 1.6 → high volatility (4H) 0.8–1.6 → normal trending (1H) 0.45–0.8 → compressed / ranging (15M sweep) < 0.45 → ultra-low volatility / micro squeeze (5M) """ valid = _valid_ohlc_candles(candles) if lookback > period + 1 and len(valid) > lookback: valid = valid[-lookback:] if len(valid) < period + 1: return 1.0 current_atr = _atr(valid, period) # Compute rolling ATRs across available candles rolling_atrs = [] step = max(1, len(valid) // 10) for start in range(0, len(valid) - period, step): chunk = valid[start: start + period + 1] a = _atr(chunk, period) if a > 0: rolling_atrs.append(a) if not rolling_atrs: return 1.0 avg_atr = sum(rolling_atrs) / len(rolling_atrs) return current_atr / avg_atr if avg_atr else 1.0 def _efficiency_ratio(candles: list[dict], period: int = 14) -> float: """ Kaufman Efficiency Ratio (ER) over the last `period` bars: |close[-1] - close[-1-period]| / sum(|close[i] - close[i-1]|) 1.0 = pure monotonic trend; < 0.25 = overlapping sideways chop. Returns 1.0 when insufficient bars exist so short mocks are unaffected. """ valid = _valid_ohlc_candles(candles) if len(valid) < period + 1 or period < 1: return 1.0 closes = [float(c["close"]) for c in valid[-(period + 1):]] net_move = abs(closes[-1] - closes[0]) total_path = sum(abs(closes[i] - closes[i - 1]) for i in range(1, len(closes))) if total_path <= 0.0: return 0.0 return round(net_move / total_path, 4) def _calc_atr_stretch(candles: list[dict], ema_period: int = 9, atr_period: int = 14) -> float: """ Signed ATR distance of current close from EMA(ema_period): (close - EMA(ema_period)) / ATR(atr_period) Positive = stretched above EMA, Negative = stretched below EMA. """ valid = _valid_ohlc_candles(candles) if len(valid) < atr_period + 1: return 0.0 atr_val = _atr(valid, atr_period) if atr_val <= 0: return 0.0 closes = [float(c["close"]) for c in valid] if not closes: return 0.0 ema_val = _calc_ema(closes, ema_period) return round((closes[-1] - ema_val) / atr_val, 3) def _calc_ema(closes: list[float], period: int) -> float: """ Calculates Exponential Moving Average over the full closes series. Seeds initial state with the Simple Moving Average (SMA) of the first `period` bars when sufficient history exists to eliminate single-bar seed bias, then applies standard recursive exponential smoothing across all remaining bars. """ if not closes: return 0.0 if period <= 1 or len(closes) == 1: return float(closes[-1]) k = 2.0 / (period + 1) if len(closes) >= period: ema = sum(closes[:period]) / period for c in closes[period:]: ema = c * k + ema * (1.0 - k) else: ema = closes[0] for c in closes[1:]: ema = c * k + ema * (1.0 - k) return ema def _market_structure(candles: list[dict]) -> str: """ Determines genuine market structure from swing points and trend filter: 1. Detects fractal swing highs (peaks) and swing lows (troughs) 2. Higher Highs + Higher Lows (HH + HL) with no downside breakdown = 'bullish' 3. Lower Highs + Lower Lows (LH + LL) with no upside breakout = 'bearish' 4. EMA(20) / EMA(9) trend confluence confirmation 5. Mixed / conflicting = 'ranging' """ valid = _valid_ohlc_candles(candles) if len(valid) < 5: return "ranging" closes = [float(c["close"]) for c in valid] highs = [float(c["high"]) for c in valid] lows = [float(c["low"]) for c in valid] # Find swing highs and swing lows across the last 30 candles window = min(len(valid), 30) start_idx = len(valid) - window # Pass 1: 5-bar Bill Williams fractals (robust against micro-noise) swing_highs: list[float] = [] swing_lows: list[float] = [] for i in range(start_idx + 2, len(valid) - 2): if (highs[i] >= highs[i - 1] and highs[i] >= highs[i - 2] and highs[i] >= highs[i + 1] and highs[i] >= highs[i + 2]): swing_highs.append(highs[i]) if (lows[i] <= lows[i - 1] and lows[i] <= lows[i - 2] and lows[i] <= lows[i + 1] and lows[i] <= lows[i + 2]): swing_lows.append(lows[i]) # Pass 2: Fallback to 3-bar swings if data is tight if len(swing_highs) < 2 or len(swing_lows) < 2: swing_highs.clear() swing_lows.clear() for i in range(start_idx + 1, len(valid) - 1): if highs[i] >= highs[i - 1] and highs[i] >= highs[i + 1]: swing_highs.append(highs[i]) if lows[i] <= lows[i - 1] and lows[i] <= lows[i + 1]: swing_lows.append(lows[i]) current_close = closes[-1] ema9 = _calc_ema(closes, 9) ema20 = _calc_ema(closes, 20) # Check swing point progression with structure invalidation protection has_swing_structure = len(swing_highs) >= 2 and len(swing_lows) >= 2 if has_swing_structure: hh = swing_highs[-1] > swing_highs[-2] hl = swing_lows[-1] > swing_lows[-2] lh = swing_highs[-1] < swing_highs[-2] ll = swing_lows[-1] < swing_lows[-2] # Invalidation check: if price broke below the most recent swing low, structure is broken structure_intact_bull = current_close >= swing_lows[-1] and (current_close > ema20 or ema9 > ema20) structure_intact_bear = current_close <= swing_highs[-1] and (current_close < ema20 or ema9 < ema20) if hh and hl and structure_intact_bull: return "bullish" if lh and ll and structure_intact_bear: return "bearish" # EMA trend fallback & confirmation (requires minimum directional efficiency when history >= 13 bars) fallback_er = _efficiency_ratio(valid, min(12, len(valid) - 1)) if len(valid) >= 13 else 1.0 if fallback_er >= 0.22: if current_close > ema20 and ema9 > ema20 and closes[-1] > closes[-min(4, len(closes))]: return "bullish" if current_close < ema20 and ema9 < ema20 and closes[-1] < closes[-min(4, len(closes))]: return "bearish" return "ranging" class MTFAnalyzer: """ Multi-Timeframe analysis spanning 1D, 4H, 1H, 15M, and 5M. """ PRIORITY_TFS = ["1d", "4h", "1h", "15m", "5m"] def analyze(self, ohlcv: dict[str, list[dict]]) -> dict[str, Any]: """ ohlcv: dict keyed by timeframe string ('1d', '4h', '1h', '15m', '5m'). """ # Prefer 1h or 15m for volatility calculation ref_tf = "1h" if "1h" in ohlcv and len(ohlcv.get("1h", [])) > 15 else "15m" ref_candles = ohlcv.get(ref_tf, []) atr_ratio = _atr_ratio(ref_candles) if ref_candles else 1.0 efficiency_ratio = _efficiency_ratio(ref_candles, 14) if ref_candles else 1.0 swing_er_candles = ohlcv.get("4h", []) if len(ohlcv.get("4h", [])) >= 13 else ref_candles swing_efficiency_ratio = _efficiency_ratio(swing_er_candles, 12) if swing_er_candles else 1.0 # Market structure on ALL timeframes structure_per_tf: dict[str, str] = {} for tf in self.PRIORITY_TFS: candles = ohlcv.get(tf, []) structure_per_tf[tf] = _market_structure(candles) if len(candles) >= 4 else "unknown" # Determine adaptive active timeframe based on volatility & directional efficiency if atr_ratio > 2.5: market_condition = "volatile" active_tf_candidates = ["1d", "4h", "1h"] elif atr_ratio > 1.6: market_condition = "volatile" active_tf_candidates = ["4h", "1h"] elif atr_ratio < 0.55: market_condition = "squeeze" active_tf_candidates = ["5m", "15m"] elif atr_ratio < 0.85 or efficiency_ratio < 0.25: market_condition = "ranging" active_tf_candidates = ["15m", "1h"] else: market_condition = "trending" active_tf_candidates = ["1h", "4h", "15m"] # Pick first candidate that has sufficient data active_tf = "1h" for tf in active_tf_candidates: if tf in ohlcv and len(ohlcv[tf]) >= 4: active_tf = tf break # Comprehensive MTF scoring across 1D, 4H, 1H, 15M, 5M: # 1D (Macro trend, weight 1) # 4H (Key structural trend, weight 2) # 1H (Intraday momentum, weight 1) # 15M / 5M (Trigger / local structure, weight 1) score = 0 struct_1d = structure_per_tf.get("1d", "ranging") struct_4h = structure_per_tf.get("4h", "ranging") struct_1h = structure_per_tf.get("1h", "ranging") struct_15m = structure_per_tf.get("15m", "ranging") struct_5m = structure_per_tf.get("5m", "ranging") if struct_1d == "bullish": score += 1 elif struct_1d == "bearish": score -= 1 if struct_4h == "bullish": score += 2 elif struct_4h == "bearish": score -= 2 if struct_1h == "bullish": score += 1 elif struct_1h == "bearish": score -= 1 if struct_15m == "bullish": score += 1 elif struct_15m == "bearish": score -= 1 if struct_5m == "bullish": score += 1 elif struct_5m == "bearish": score -= 1 # Clamp between -2 and +2 to prevent MTF from dominating confluence score = max(-2, min(2, score)) # Dual-Horizon MTF structure & EMA(9) ATR stretch s_1d = 1 if struct_1d == "bullish" else (-1 if struct_1d == "bearish" else 0) s_4h = 1 if struct_4h == "bullish" else (-1 if struct_4h == "bearish" else 0) s_1h = 1 if struct_1h == "bullish" else (-1 if struct_1h == "bearish" else 0) has_15m = "15m" in ohlcv and len(ohlcv.get("15m", [])) >= 4 s_15m = (1 if struct_15m == "bullish" else (-1 if struct_15m == "bearish" else 0)) if has_15m else s_1h intraday_structure = max(-2, min(2, s_15m + s_1h)) if s_4h == 0 and s_1d == 0 and len(ohlcv.get("4h", [])) < 15: swing_structure = max(-2, min(2, 2 * s_1h)) else: swing_structure = max(-2, min(2, (2 * s_4h) + s_1d)) intraday_stretch_candles = ( ohlcv.get("1h", []) if len(ohlcv.get("1h", [])) >= 15 else ohlcv.get("15m", []) ) swing_stretch_candles = ( ohlcv.get("4h", []) if len(ohlcv.get("4h", [])) >= 15 else ohlcv.get("1d", []) ) intraday_atr_stretch = _calc_atr_stretch(intraday_stretch_candles, ema_period=9, atr_period=14) swing_atr_stretch = _calc_atr_stretch(swing_stretch_candles, ema_period=9, atr_period=14) active_structure = structure_per_tf.get(active_tf, "ranging") label_map = { 2: "Strong MTF Bullish Structure (HTF Aligned)", 1: "Mildly Bullish Structure", 0: "Ranging / Mixed Structure", -1: "Mildly Bearish Structure", -2: "Strong MTF Bearish Structure (HTF Aligned)", } label = label_map.get(score, "Ranging / Mixed Structure") return { "active_timeframe": active_tf, "market_condition": market_condition, "regime": market_condition, "atr_ratio": round(atr_ratio, 3), "efficiency_ratio": round(efficiency_ratio, 3), "swing_efficiency_ratio": round(swing_efficiency_ratio, 3), "structure_per_tf": structure_per_tf, "score": score, "weighted_score": score, "intraday_structure": intraday_structure, "intraday_atr_stretch": intraday_atr_stretch, "swing_structure": swing_structure, "swing_atr_stretch": swing_atr_stretch, "label": label, "active_structure": active_structure, }