"""
opening_patterns.py -- [2026-10-28] The user's 40 OPENING PATTERNS (catalog: reports/opening_patterns.html / CATALOG below).
Follows one stock from the open, minute by minute on FINISHED 1-min bars only (no look-ahead), and reports which of the 40
patterns have been CONFIRMED so far (minute of confirmation + the key levels). Read-only: it never trades.
Definitions (user-approved defaults 10/28):
  u (move unit)  = the stock's daily ATR in $ (ref atr14). DIP = 0.15u, SHARP = 0.4u, SIDEWAYS = a 10-bar range < 0.15u.
  context        = GAP UP / GAP DOWN / FLAT; FLAT if |gap| <= max(0.5%, 0.1 x daily ATR %).
  opening range  = first 5 minutes (ORH / ORL); the 15-minute range is reported too.
  swings         = online zig-zag on bar highs / lows, reversal >= DIP (a pivot exists only after the reversal happened).
  window         = 9:30 .. 11:30; nothing is confirmed before 9:35.
  volume         = a bar's volume vs the median 1-min volume so far today (high >= 2x, low < 1x).
Usage: R = Recognizer(prev_close, atr_dollar, open_price); for each finished bar: R.update(bar, t) -> list of newly confirmed
pattern ids. R.confirmed = {id: (t, price)}. analyze_day(bars, ref) runs a whole day (bars = finished 1-min bars from 9:30).
"""
import statistics

CATALOG = {
    1: ("A", "Gap up -> dip down -> rises", "bullish", "dip >= 0.15u after the gap, then a close above the pre-dip high"),
    2: ("A", "Gap up -> rises immediately", "bullish", "no dip first; a close above the opening-range high on >= 1.5x median volume"),
    3: ("A", "Gap up -> sideways -> rises", "bullish", "10-min range < 0.15u, then a close above that range"),
    4: ("A", "Gap up -> rises -> drops", "bearish reversal", "an up leg, then a close below the opening-range low"),
    5: ("A", "Gap up -> drops continuously", "bearish", "first leg down >= 0.4u, no bounce >= 0.15u, close below the opening-range low"),
    6: ("A", "Gap up -> dips below opening low -> recovers", "bullish reversal", "a close below the opening-range low, then a close back above the open"),
    7: ("A", "Gap up -> rally -> sharp drop -> weak bounce", "bearish", "up leg, drop >= 0.4u, bounce < half the drop that turns down again"),
    8: ("A", "Gap up -> volatile swings -> tight range", "neutral", ">= 3 swings >= 0.15u, then a 10-min range < 0.15u"),
    9: ("B", "Gap down -> rises", "bullish reversal", "breaks above the opening-range high before breaking its low; a close above VWAP"),
    10: ("B", "Gap down -> drops immediately", "bearish", "first leg down; a close below the opening-range low, bounce < 0.15u"),
    11: ("B", "Gap down -> sideways -> drops", "bearish", "10-min range < 0.15u, then a close below that range"),
    12: ("B", "Gap down -> drops -> sharp recovery", "bullish reversal", "drop >= 0.4u, then a higher low and a close above the open"),
    13: ("B", "Gap down -> drops -> weak bounce -> drops", "bearish", "down leg, bounce < half of it, then a lower low"),
    14: ("B", "Gap down -> breaks lower -> reclaims opening price", "bullish reversal", "a close below the opening-range low, then a close back above the open"),
    15: ("B", "Gap down -> rallies -> rejects previous close", "bearish", "the rally tops out within 0.05u of the previous close (not beyond), then drops >= 0.15u"),
    16: ("B", "Gap down -> volatile swings -> tight range", "neutral", ">= 3 swings >= 0.15u, then a 10-min range < 0.15u"),
    17: ("C", "Flat open -> rises immediately", "bullish", "first leg up; a close above the opening-range high"),
    18: ("C", "Flat open -> drops immediately", "bearish", "first leg down; a close below the opening-range low"),
    19: ("C", "Flat open -> dip -> strong rise", "bullish", "dip >= 0.15u, then a close above the pre-dip high"),
    20: ("C", "Flat open -> rally -> sharp drop", "bearish reversal", "up leg, then a drop >= 0.4u and a close below the opening-range low"),
    21: ("C", "Flat open -> tight range -> upside breakout", "bullish", "10-min range < 0.15u, then a close above it"),
    22: ("C", "Flat open -> tight range -> downside breakdown", "bearish", "10-min range < 0.15u, then a close below it"),
    23: ("C", "Flat open -> breaks high -> falls back into range", "bull trap", "a close above the opening-range high, back below it within 10 min"),
    24: ("C", "Flat open -> breaks low -> recovers into range", "bear trap", "a close below the opening-range low, back above it within 10 min"),
    25: ("D", "Rises -> pulls back -> holds breakout -> rises", "bullish continuation", "up leg breaks a swing high, pullback holds above it, new high"),
    26: ("D", "Rises -> lower high -> breaks support", "bearish reversal", "after an up leg: a lower swing high, then a close below the last swing low"),
    27: ("D", "Drops -> higher low -> breaks resistance", "bullish reversal", "after a down leg: a higher swing low, then a close above the last swing high"),
    28: ("D", "Drops -> weak bounce -> lower low", "bearish continuation", "down leg, bounce < half of it, a new low"),
    29: ("D", "Rises -> shallow dip -> rises (x2)", "bullish continuation", ">= 2 higher lows and >= 3 rising swing highs"),
    30: ("D", "Drops -> weak bounce -> drops (x2)", "bearish continuation", ">= 2 lower highs and >= 3 falling swing lows"),
    31: ("D", "Double bottom", "bullish reversal", "two swing lows within 0.1u, bounce >= 0.15u between, a close above the middle high"),
    32: ("D", "Double top", "bearish reversal", "two swing highs within 0.1u, a close below the middle low"),
    33: ("E", "Sharp rise -> full retracement", "bearish (potential)", "rise >= 0.4u, then back to where it started"),
    34: ("E", "Sharp drop -> full recovery", "bullish (potential)", "drop >= 0.4u, then back to where it started"),
    35: ("E", "Rises -> drops -> rises -> drops (whipsaw)", "neutral", ">= 4 alternating swings, net move < 0.15u"),
    36: ("E", "Opens flat -> narrow range", "neutral / compression", "flat open and the first 30 minutes' range < 0.25u"),
    37: ("E", "Tests resistance repeatedly -> breaks up", "bullish breakout (potential)", ">= 3 highs within 0.05u of a level, then a close above it"),
    38: ("E", "Tests support repeatedly -> breaks down", "bearish breakdown (potential)", ">= 3 lows within 0.05u of a level, then a close below it"),
    39: ("E", "High-volume breakout -> immediate rejection", "failed breakout", "a close above the day's high so far on >= 2x volume, back below it within 5 min"),
    40: ("E", "Low-volume breakout -> returns to range", "unreliable breakout", "a close above the day's high so far on < 1x volume, back below it within 10 min"),
    41: ("F", "Shallow V -> reclaims VWAP", "bullish reversal", "[user 10/28, FLNC 10/20; MARA 10/23] a dip >= 0.15u from the recent high (last 30 min) to a low under VWAP, then a close back above VWAP after >= 2 closes in a row under it"),
    42: ("F", "Deep dip -> V turn (by 9:45)", "bullish reversal", "[user 10/29] 9:32-9:45: a drop >= DEEP x u (0.5u) from the day's high so far to a low on a LATER bar, the low holds, and a bar closes above the previous bar's high"),
}
BIAS_UP = {1, 2, 3, 6, 9, 12, 14, 17, 19, 21, 24, 25, 27, 29, 31, 34, 37, 41, 42}
BIAS_DOWN = {4, 5, 7, 10, 11, 13, 15, 18, 20, 22, 23, 26, 28, 30, 32, 33, 38, 39}


class Recognizer:
    DIP, SHARP, SIDE, NEAR, LEVEL = 0.15, 0.40, 0.15, 0.05, 0.10
    DEEP = 0.5                        # #42 deep dip (x u)

    def __init__(self, prev_close, atr_dollar, open_price):
        self.pc, self.u, self.o = prev_close, max(atr_dollar, open_price * 0.005), open_price
        gap = (open_price / prev_close - 1) * 100; atrp = atr_dollar / prev_close * 100
        self.gap = gap; self.ctx = "FLAT" if abs(gap) <= max(0.5, 0.1 * atrp) else ("GU" if gap > 0 else "GD")
        self.H, self.L, self.C, self.V, self.T = [], [], [], [], []
        self.VW = []                      # VWAP after each bar (#41)
        self.pv = 0.0; self.cv = 0.0; self.vwap = open_price
        self.piv = []                     # confirmed swing pivots: (kind 'H'/'L', price, t)
        self.dir = 0; self.ext = None; self.ext_t = 0
        self.confirmed = {}; self.ev = {}  # events with their minute
        self.orh = self.orl = None

    # ---------- helpers ----------
    def _dist(self, a, b):
        return abs(a - b) / self.u

    def _legs(self):
        """swing legs from the open: list of (dir, size_u, start_price, end_price, t_end); the last one may still run"""
        pts = [("O", self.o, 0)] + self.piv + ([("X", self.ext, self.ext_t)] if self.ext is not None else [])
        legs = []
        for a, b in zip(pts, pts[1:]):
            d = 1 if b[1] > a[1] else -1
            legs.append((d, abs(b[1] - a[1]) / self.u, a[1], b[1], b[2]))
        return [l for l in legs if l[1] > 0]

    def _confirm(self, pid, t, new):
        if pid not in self.confirmed:
            self.confirmed[pid] = (t, self.C[-1]); new.append(pid)

    # ---------- per finished bar ----------
    def update(self, bar, t):
        h, l, c, v = bar["h"], bar["l"], bar["c"], bar["v"]
        self.H.append(h); self.L.append(l); self.C.append(c); self.V.append(v); self.T.append(t)
        self.pv += (h + l + c) / 3 * v; self.cv += v; self.vwap = self.pv / self.cv if self.cv else c
        self.VW.append(self.vwap)
        if len(self.H) == 5:
            self.orh, self.orl = max(self.H), min(self.L)
        # online zig-zag (reversal >= DIP)
        thr = self.DIP * self.u
        if self.dir == 0:
            if h - self.o >= thr: self.dir, self.ext, self.ext_t = 1, h, t
            elif self.o - l >= thr: self.dir, self.ext, self.ext_t = -1, l, t
            elif self.ext is None or abs(c - self.o) > abs(self.ext - self.o): self.ext, self.ext_t = c, t
        elif self.dir == 1:
            if h > self.ext: self.ext, self.ext_t = h, t
            elif self.ext - l >= thr: self.piv.append(("H", self.ext, self.ext_t)); self.dir, self.ext, self.ext_t = -1, l, t
        else:
            if l < self.ext: self.ext, self.ext_t = l, t
            elif h - self.ext >= thr: self.piv.append(("L", self.ext, self.ext_t)); self.dir, self.ext, self.ext_t = 1, h, t
        new = []
        # 42 [2026-10-29, user]: DEEP DIP -> V TURN, 9:32-9:45 only (checked before the 9:35 start of the other patterns). The day's high so far
        # (before this bar), the lowest low on a LATER bar (before this bar; same-bar high+low does not count -- EROC 8/12), drop >= DEEP x u,
        # this bar's low holds above it and this bar closes above the previous bar's high.
        n = len(self.H)
        if 2 <= t <= 15 and n >= 3:
            hi_i = max(range(0, n - 1), key=lambda k: self.H[k])
            if hi_i + 1 < n - 1:
                li = min(range(hi_i + 1, n - 1), key=lambda k: self.L[k]); low = self.L[li]
                if self.H[hi_i] - low >= self.DEEP * self.u and l >= low and c > self.H[-2]:
                    self.v42_low = low; self._confirm(42, t, new)
        if t < 5 or t > 120 or self.orh is None:
            return new
        self._events(t)
        self._match(t, new)
        return new

    def _events(self, t):
        c = self.C[-1]; E = self.ev
        if c > self.orh and "brk_orh" not in E: E["brk_orh"] = t
        if c < self.orl and "brk_orl" not in E: E["brk_orl"] = t
        if len(self.H) >= 10:
            hi10, lo10 = max(self.H[-10:]), min(self.L[-10:])
            if (hi10 - lo10) < self.SIDE * self.u:
                E.setdefault("range_first", t); E["range"] = (hi10, lo10, t)

    def _match(self, t, new):
        c, ctx, E, u = self.C[-1], self.ctx, self.ev, self.u
        legs = self._legs(); big = [l for l in legs if l[1] >= self.DIP]
        first = big[0] if big else None
        med = statistics.median(self.V) if self.V else 0; vx = self.V[-1] / med if med else 0
        rng = E.get("range"); in_range_end = rng is not None and rng[2] == t
        lows = [p for p in self.piv if p[0] == "L"]; highs = [p for p in self.piv if p[0] == "H"]
        # ---- A / C: dip then rise above the pre-dip high (1 / 19)
        if first and first[0] == -1 and len(big) >= 2 and c > first[2]:
            self._confirm(1 if ctx == "GU" else 19 if ctx == "FLAT" else 0, t, new)
        # 2 / 17: first leg up, break of the opening-range high (2 also needs volume)
        if first and first[0] == 1 and len(big) == 1 and "brk_orh" in E:
            if ctx == "GU" and vx >= 1.5: self._confirm(2, t, new)
            if ctx == "FLAT": self._confirm(17, t, new)
        # 3 / 21 / 11 / 22: a range, then a break out of it
        if rng and not in_range_end and t - rng[2] <= 10:
            hi, lo = rng[0], rng[1]
            if c > hi: self._confirm({"GU": 3, "FLAT": 21}.get(ctx, 0), t, new)
            if c < lo: self._confirm({"GD": 11, "FLAT": 22}.get(ctx, 0), t, new)
        # 4 / 20: up leg first, then lose the opening-range low (20 needs a sharp drop)
        if first and first[0] == 1 and c < self.orl:
            if ctx == "GU": self._confirm(4, t, new)
            if ctx == "FLAT" and any(l[0] == -1 and l[1] >= self.SHARP for l in big): self._confirm(20, t, new)
        # 5 / 10 / 18: first leg down, below the opening-range low, no real bounce
        if first and first[0] == -1 and len(big) == 1 and c < self.orl:
            if ctx == "GU" and first[1] >= self.SHARP: self._confirm(5, t, new)
            if ctx == "GD": self._confirm(10, t, new)
            if ctx == "FLAT": self._confirm(18, t, new)
        # 6 / 14: below the opening-range low, then back above the open
        if "brk_orl" in E and c > self.o and t > E["brk_orl"]:
            self._confirm({"GU": 6, "GD": 14}.get(ctx, 0), t, new)
        # 24 / 23: traps (flat open)
        if ctx == "FLAT":
            if "brk_orl" in E and c > self.orl and t - E["brk_orl"] <= 10 and t > E["brk_orl"]: self._confirm(24, t, new)
            if "brk_orh" in E and c < self.orh and t - E["brk_orh"] <= 10 and t > E["brk_orh"]: self._confirm(23, t, new)
        # 7: up, sharp drop, weak bounce that turns down
        for i in range(len(big) - 3):
            a, b, cc, d = big[i:i + 4]
            if a[0] == 1 and b[0] == -1 and b[1] >= self.SHARP and cc[0] == 1 and cc[1] < 0.5 * b[1] and d[0] == -1 and ctx == "GU":
                self._confirm(7, t, new)
        # 8 / 16: >= 3 swings, then a tight range
        if len(big) >= 3 and in_range_end and big[2][4] < t:
            self._confirm({"GU": 8, "GD": 16}.get(ctx, 0), t, new)
        # 9: gap down, first leg up, above the open and VWAP
        if ctx == "GD" and "brk_orh" in E and E["brk_orh"] < E.get("brk_orl", 999) and c > self.vwap: self._confirm(9, t, new)
        # 12: gap down, drop >= sharp, a higher low, above the open
        if ctx == "GD" and first and first[0] == -1 and first[1] >= self.SHARP and c > self.o and len(lows) >= 1:
            self._confirm(12, t, new)
        # 13 / 28: down leg, weak bounce (< half), lower low
        for i in range(len(big) - 2):
            a, b, cc = big[i:i + 3]
            if a[0] == -1 and b[0] == 1 and b[1] < 0.5 * a[1] and cc[0] == -1 and cc[3] < a[3]:
                if ctx == "GD" and i == 0: self._confirm(13, t, new)
                self._confirm(28, t, new)
        # 15: gap down, rally to the previous close, rejected
        if ctx == "GD":
            hi = max(self.H)
            if abs(hi - self.pc) <= self.NEAR * u and (hi - c) >= self.DIP * u and self.H.index(hi) < len(self.H) - 1: self._confirm(15, t, new)
        # 25: up leg breaks a swing high, pullback holds above it, new high
        if len(highs) >= 2 and len(lows) >= 1:
            h1, h2 = highs[-2], highs[-1]; lo = lows[-1]
            if h2[1] > h1[1] and lo[2] > h2[2] and lo[1] >= h1[1] - self.NEAR * u and c > h2[1]: self._confirm(25, t, new)
        # 26: lower swing high, then a close below the last swing low
        if len(highs) >= 2 and lows and highs[-1][1] < highs[-2][1] and c < lows[-1][1] and lows[-1][2] < highs[-1][2]: self._confirm(26, t, new)
        # 27: higher swing low, then a close above the last swing high
        if len(lows) >= 2 and highs and lows[-1][1] > lows[-2][1] and c > highs[-1][1] and highs[-1][2] < lows[-1][2]: self._confirm(27, t, new)
        # 29 / 30: staircases -- 3 rising swing lows + rising highs (29) / 3 falling swing highs + falling lows (30)
        if len(lows) >= 3 and len(highs) >= 2 and lows[-3][1] < lows[-2][1] < lows[-1][1] and highs[-2][1] < highs[-1][1] < c:
            self._confirm(29, t, new)
        if len(highs) >= 3 and len(lows) >= 2 and highs[-3][1] > highs[-2][1] > highs[-1][1] and lows[-2][1] > lows[-1][1] > c:
            self._confirm(30, t, new)
        # 31 / 32: double bottom / top
        if len(lows) >= 2 and highs:
            l1, l2 = lows[-2], lows[-1]; mid = [x for x in highs if l1[2] < x[2] < l2[2]]
            if mid and self._dist(l1[1], l2[1]) <= self.LEVEL and c > mid[-1][1]: self._confirm(31, t, new)
        if len(highs) >= 2 and lows:
            h1, h2 = highs[-2], highs[-1]; mid = [x for x in lows if h1[2] < x[2] < h2[2]]
            if mid and self._dist(h1[1], h2[1]) <= self.LEVEL and c < mid[-1][1]: self._confirm(32, t, new)
        # 33 / 34: full retracement / recovery of a sharp move
        for lg in big[:-1]:
            if lg[0] == 1 and lg[1] >= self.SHARP and c <= lg[2]: self._confirm(33, t, new)
            if lg[0] == -1 and lg[1] >= self.SHARP and c >= lg[2]: self._confirm(34, t, new)
        # 35: whipsaw
        if len(big) >= 4 and abs(c - self.o) < self.DIP * u: self._confirm(35, t, new)
        # 36: flat open, narrow first 30 minutes
        if ctx == "FLAT" and t == 30 and (max(self.H) - min(self.L)) < 0.25 * u: self._confirm(36, t, new)
        # 37 / 38: repeated tests, then the break
        if len(self.H) >= 15:
            lvl = max(self.H[:-1]); touches = sum(1 for x in self.H[:-1] if lvl - x <= self.NEAR * u)
            if touches >= 3 and c > lvl: self._confirm(37, t, new)
            lvl = min(self.L[:-1]); touches = sum(1 for x in self.L[:-1] if x - lvl <= self.NEAR * u)
            if touches >= 3 and c < lvl: self._confirm(38, t, new)
        # 39 / 40: breakout above the day's high so far, then back below
        if len(self.C) >= 6:
            for k in range(max(5, len(self.C) - 10), len(self.C) - 1):
                prior = max(self.H[:k]); 
                if self.C[k] > prior:
                    medk = statistics.median(self.V[:k + 1]); vk = self.V[k] / medk if medk else 0
                    back = c < prior
                    if back and vk >= 2 and len(self.C) - 1 - k <= 5: self._confirm(39, t, new)
                    if back and vk < 1 and len(self.C) - 1 - k <= 10: self._confirm(40, t, new)
                    break
        # 41 [2026-10-28, user]: shallow V -> reclaims VWAP. The recent HIGH = highest high of the last 30 bars (not the last 2); the V LOW =
        # the lowest low after that high (at least 2 bars old); drop >= DIP, the low under VWAP, every close since the low at/under VWAP,
        # and THIS bar is the first close back above VWAP.
        if len(self.C) >= 8:
            n = len(self.L); w0 = max(0, n - 30)
            hi_i = max(range(w0, n - 2), key=lambda k: self.H[k])
            if hi_i + 1 < n - 2:
                li = min(range(hi_i + 1, n - 2), key=lambda k: self.L[k])
                low = self.L[li]
                # [2026-10-28, user MARA 10/23 9:39] reclaim = this close above VWAP after >= 2 closes in a row at/under VWAP (a brief poke above VWAP
                # inside the V no longer cancels it); the V low still has to be under VWAP and inside the last 30 bars
                if self.H[hi_i] - low >= self.DIP * u and low < self.VW[li] and c > self.vwap and n >= 3 \
                        and self.C[n - 2] <= self.VW[n - 2] and self.C[n - 3] <= self.VW[n - 3]:
                    self._confirm(41, t, new)
        self.confirmed.pop(0, None)
        if 0 in new: new.remove(0)


def analyze_day(bars, ref, minute_of):
    """bars: finished 1-min bars from 9:30 (dicts t,o,h,l,c,v); -> (Recognizer, [(t, pattern_id, price)])"""
    b0 = [b for b in bars if 0 <= minute_of(b["t"]) < 390]
    if not b0 or not ref.get("atr14") or not ref.get("prev_close"):
        return None, []
    R = Recognizer(ref["prev_close"], ref["atr14"], b0[0]["o"]); out = []
    for b in b0:
        t = minute_of(b["t"])
        if t > 120: break
        for pid in R.update(b, t):
            out.append((t, pid, b["c"]))
    return R, out
