"""Opening Range Breakout + FVG + Engulfing scalping strategy. Configurable filters for optimization. """ from __future__ import annotations from dataclasses import dataclass from zoneinfo import ZoneInfo import pandas as pd NY = ZoneInfo("America/New_York") @dataclass class Params: rr_ratio: float = 3.0 # risk:reward (1:N) max_trades: int = 2 # max trades per session fvg_expiry: int = 30 # FVG valid N bars min_range_pct: float = 0.0 # min range as % of price (0 = off) min_fvg_pct: float = 0.0 # min FVG gap as % of price (0 = off) min_risk_pct: float = 0.0 # min stop distance as % of price (0 = off) session_end_h: int = 11 # stop entering after this hour (NY) session_end_m: int = 0 first_fvg_only: bool = False # only trade the first FVG of the day @dataclass class FVG: direction: str zone_low: float zone_high: float bar_idx: int used: bool = False @dataclass class Trade: direction: str entry: float stop: float tp: float entry_time: object = None exit_price: float = 0.0 exit_time: object = None result: str = "" pnl_r: float = 0.0 def get_opening_range(df: pd.DataFrame, or_minutes: int = 5) -> tuple[float, float] | None: """Get opening range high/low. or_minutes: range duration from 9:30.""" ny = df["timestamp"].dt.tz_convert(NY) or_end = 30 + or_minutes # minutes past the hour mask = (ny.dt.hour == 9) & (ny.dt.minute >= 30) & (ny.dt.minute < or_end) rc = df[mask] if len(rc) < 1: return None return float(rc["high"].max()), float(rc["low"].min()) def run_day(df_day: pd.DataFrame, p: Params | None = None, or_minutes: int = 5) -> list[Trade]: p = p or Params() rng = get_opening_range(df_day, or_minutes) if rng is None: return [] rh, rl = rng mid = (rh + rl) / 2 # Filter: min range size if p.min_range_pct > 0 and mid > 0: if (rh - rl) / mid < p.min_range_pct / 100: return [] ny = df_day["timestamp"].dt.tz_convert(NY) or_end_min = 30 + or_minutes # After opening range: from or_end_min to 16:00 NY if or_end_min < 60: mask = (((ny.dt.hour == 9) & (ny.dt.minute >= or_end_min)) | (ny.dt.hour >= 10)) & (ny.dt.hour < 16) else: mask = (ny.dt.hour >= 10) & (ny.dt.hour < 16) after = df_day[mask].reset_index(drop=True) if len(after) < 5: return [] trades: list[Trade] = [] fvgs: list[FVG] = [] active: Trade | None = None trade_count = 0 for i in range(len(after)): c = after.iloc[i] c_ny = c["timestamp"].astimezone(NY) # Check SL / TP if active: hit_sl = hit_tp = False if active.direction == "long": hit_sl = c["low"] <= active.stop hit_tp = c["high"] >= active.tp else: hit_sl = c["high"] >= active.stop hit_tp = c["low"] <= active.tp if hit_sl: active.exit_price = active.stop active.exit_time = c["timestamp"] active.result = "loss" active.pnl_r = -1.0 trades.append(active) active = None elif hit_tp: active.exit_price = active.tp active.exit_time = c["timestamp"] active.result = "win" active.pnl_r = p.rr_ratio trades.append(active) active = None else: continue # Max trades reached or past entry window if trade_count >= p.max_trades: continue in_window = (c_ny.hour < p.session_end_h or (c_ny.hour == p.session_end_h and c_ny.minute <= p.session_end_m)) if not in_window: continue # Detect FVG if i >= 2: c0, c1, c2 = after.iloc[i-2], after.iloc[i-1], c fvg = None if c1["close"] > rh and c2["low"] > c0["high"]: fvg = FVG("bull", c0["high"], c2["low"], i) elif c1["close"] < rl and c2["high"] < c0["low"]: fvg = FVG("bear", c2["high"], c0["low"], i) if fvg: gap = fvg.zone_high - fvg.zone_low if p.min_fvg_pct > 0 and mid > 0 and gap / mid < p.min_fvg_pct / 100: fvg = None if fvg and not (p.first_fvg_only and fvgs): fvgs.append(fvg) # Expire old FVGs fvgs = [f for f in fvgs if not f.used and (i - f.bar_idx) < p.fvg_expiry] # Check retest + engulfing if i < 1: continue prev = after.iloc[i - 1] for fvg in fvgs: if fvg.used: continue # Prev candle must touch FVG zone if not (prev["low"] <= fvg.zone_high and prev["high"] >= fvg.zone_low): continue # Engulfing check if fvg.direction == "bull": ok = (prev["close"] < prev["open"] and c["close"] > c["open"] and c["close"] >= prev["open"] and c["open"] <= prev["close"]) else: ok = (prev["close"] > prev["open"] and c["close"] < c["open"] and c["close"] <= prev["open"] and c["open"] >= prev["close"]) if not ok: continue entry = float(c["close"]) stop = float(c["low"]) if fvg.direction == "bull" else float(c["high"]) risk = abs(entry - stop) if risk <= 0: continue if p.min_risk_pct > 0 and mid > 0 and risk / mid < p.min_risk_pct / 100: continue tp = entry + p.rr_ratio * risk if fvg.direction == "bull" else entry - p.rr_ratio * risk active = Trade( direction="long" if fvg.direction == "bull" else "short", entry=entry, stop=stop, tp=tp, entry_time=c["timestamp"], ) fvg.used = True trade_count += 1 break # Close open trade at session end if active: last = after.iloc[-1] active.exit_price = float(last["close"]) active.exit_time = last["timestamp"] risk = abs(active.entry - active.stop) pnl = ((active.exit_price - active.entry) if active.direction == "long" else (active.entry - active.exit_price)) active.pnl_r = pnl / risk if risk > 0 else 0 active.result = "win" if active.pnl_r > 0 else "loss" trades.append(active) return trades