"""
stock_board.py -- [2026-10-28] The user's STOCK BOARD: follows one stock from the open, every finished 1-min bar, and keeps:
  RESISTANCE  starts at the premarket high; the first swing high of the day (e.g. the gap-up run) REPLACES it; every later swing
              high is AVERAGED in (resistance = mean of the day's swing highs).               [user 10/28: "averaged"]
  SUPPORT     the first dip's swing low; every later swing low is AVERAGED in. Before any swing: the day's low so far.
  RANGE       resistance - support ($, % of price, x daily ATR) and the price's position in it (0 = support, 1 = resistance).
  VOLUME ACC  last 3 bars' average volume / the bars before them (the 15 before; from 6 bars on, all before -> buys from ~9:36).
  BUY / SELL  share of buyers over 3 and 15 minutes (flow), and whether each rose vs 1 minute ago.
  VWAP        price vs VWAP and VWAP's 5-minute slope.
  PATTERN     opening_patterns.Recognizer (the 40 patterns): a BULLISH pattern ARMS the board for 15 minutes ("buy candidate");
              a bearish / neutral one = "keep watching" (a bearish one cancels the arm).
  BUY SIGNAL  [user 10/28 "yes"] armed AND rise confirmed: close above the trigger (the high of the bar that confirmed the pattern),
              3-min buy share above the 15-min, volume accelerating (>= 1.0) AND VWAP not sloping down (5-min slope >= 0, user 10/28).
              The buy is at the next bar's open.
Entries only, record / study only: it never places an order. Swings, patterns and levels use finished bars (no look-ahead).
Options [2026-10-28, user on AVEX 10/21: "the support is at the wrong position" + "buying while VWAP is still falling"]:
  levels="break"  swing lows / highs are averaged WHILE THEY HOLD; a close below support resets support to the new low (the broken
                  support joins the resistance list), a close above resistance resets resistance to the new high (it joins support).
  p41_own         [2026-10-28, user: SNAP 10/12 "a perfect V"] #41 (shallow V -> reclaims VWAP) gets ITS OWN confirmation: close above
                  the #41 bar's high + 3-min buy share above the 15-min + close above VWAP -- no volume-acceleration and no VWAP-slope
                  requirement (a V usually rises on less volume and VWAP still points down right after the dip); a valid #41 candidate is not
                  replaced by a later bullish pattern.
  vwap_rising     VWAP check ON. vwap_rule "line_up" (DEFAULT, user 10/28 SNAP / MARA): the VWAP LINE itself is rising -- VWAP now >= 0.02% above
                  3 minutes ago and not below 1 minute ago (the price may still be under VWAP). "up" = 5-min slope higher than a minute ago
                  (my first reading, wrong: passed MARA 10:44's flat VWAP); "ge0" = 5-min slope >= 0.
  rule            "v1" (DEFAULT, the rules so far) | "v2" (user 10/28 "start over"): bullish pattern = buy spot; position <= 0.5 -> buy;
                  position > 0.5 -> only on a breakout (close above resistance, brk_n closes in a row); VWAP never falling (vwap2 "rising" | "flat");
                  + time-of-day volume acceleration >= 1 (v2_vol, needs vpm) + 3m buy share > 15m and both rising (v2_share); trigger optional (v2_trigger).
  keep_first      OPTION, OFF (user 10/28: "don't add this rule yet"; idea from SNAP 9:40): while a candidate is valid (15 min) a later BULLISH pattern does not replace it or raise
                  its trigger (SNAP: #41 trigger 6.38 was replaced by #27 6.43, then #34 6.47 -> it bought the top); a bearish pattern still cancels.
  pos_band        e.g. 0.8: no buy while the price is in the top band right UNDER resistance (position 0.8..1.0); above resistance (> 1) allowed.
  persist         N >= 2: 3-min buy share > 15-min in each of the last N minutes AND both higher than N minutes ago (user 10/28).
  vacc_tod_min    TIME-OF-DAY volume acceleration (needs vpm = ref vol_per_min): (last 3 bars / their 14-day normal) / (bars before / normal);
                  user 10/28. None = off.
  vacc_min        volume-acceleration requirement; DEFAULT None = OFF (user 10/28: "volume acceleration at this time will probably never
                  happen" -- a V rises on drying volume); 1.0 = the old rule.          above_support  no buy unless the close is above support.
"""
from opening_patterns import Recognizer, CATALOG, BIAS_UP, BIAS_DOWN


class Board:
    ARM_MIN = 15

    def __init__(self, prev_close, atr_dollar, open_price, pm_high=None, levels="avg", vwap_rising=True, above_support=False, p41_own=False, vacc_min=None, vwap_rule="line_up", vpm=None, vacc_tod_min=None, persist=1, pos_band=None, keep_first=False, rule="v1", vwap2="rising", brk_n=2, v2_vol=True, v2_share=True, v2_trigger=False, v41_max_vwap=None, v41_max_wait=None, v41_fast=False, spike_x=5.0, liq_min=2000, room_min=1.0, only_pids=None, liq_n_min=15, share_min=None):
        self.R = Recognizer(prev_close, atr_dollar, open_price)
        self.pm_high = pm_high; self.hi_list = []; self.lo_list = []; self.n_piv = 0
        self.fb, self.fs = [], []; self.vw_hist = []; self.armed = None; self.state = "watching"; self.rows = []; self.buys = []
        self.levels, self.vwap_rising, self.above_support, self.p41_own = levels, vwap_rising, above_support, p41_own
        self.vacc_min, self.vwap_rule = vacc_min, vwap_rule; self.vws_prev = None
        self.vpm, self.vacc_tod_min = vpm, vacc_tod_min; self.mins = []
        self.persist = persist; self.s3h, self.s15h = [], []; self.pos_band = pos_band; self.keep_first = keep_first
        self.rule, self.vwap2, self.brk_n = rule, vwap2, brk_n; self.above_res = 0
        self.v2_vol, self.v2_share, self.v2_trigger = v2_vol, v2_share, v2_trigger
        self.v41_max_vwap, self.v41_max_wait, self.v41_fast = v41_max_vwap, v41_max_wait, v41_fast
        self.spike_x, self.liq_min, self.room_min = spike_x, liq_min, room_min
        self.share_min = share_min                               # [10/29 #42] 3-min buy share must be >= this (e.g. 0.55)
        self.only_pids, self.liq_n_min = only_pids, liq_n_min   # [10/29 #42] only these patterns arm a candidate | liquidity judged on >= liq_n_min bars (up to 15)

    def _share(self, n, back=0):
        b = self.fb[-n - back:len(self.fb) - back] if back else self.fb[-n:]; s = self.fs[-n - back:len(self.fs) - back] if back else self.fs[-n:]
        return sum(b) / (sum(b) + sum(s)) if sum(b) + sum(s) else 0.5

    def update(self, bar, t, buy_vol, sell_vol):
        """bar: finished 1-min bar (h,l,c,v); buy_vol / sell_vol: that minute's flow. -> the board row (dict); row['buy'] True = buy signal"""
        R = self.R; new = R.update(bar, t); self.fb.append(buy_vol); self.fs.append(sell_vol); self.vw_hist.append(R.vwap)
        for k, p, tp in R.piv[self.n_piv:]:
            if k == "H": self.hi_list.append(p)
            else: self.lo_list.append(p)
        self.n_piv = len(R.piv)
        c = R.C[-1]
        res = sum(self.hi_list) / len(self.hi_list) if self.hi_list else max(self.pm_high or 0, max(R.H))
        sup = sum(self.lo_list) / len(self.lo_list) if self.lo_list else min(R.L)
        if self.levels == "break":
            # a broken level flips sides; the other side follows the running extreme since the break until a new swing forms
            if self.lo_list and c < sup:
                self.hi_list = [sup]; self.lo_list = []; self.brk = len(R.L) - 1
            elif self.hi_list and c > res:
                self.lo_list = [res]; self.hi_list = []; self.brk = len(R.H) - 1
            k0 = getattr(self, "brk", 0)
            res = sum(self.hi_list) / len(self.hi_list) if self.hi_list else max(R.H[k0:])
            sup = sum(self.lo_list) / len(self.lo_list) if self.lo_list else min(R.L[k0:])
        rng = max(res - sup, 1e-9)
        # [2026-10-28, user: 'shorter'] from 6 bars on: last 3 bars vs ALL the bars before them (up to the 15 before) -- buys from ~9:36
        V = R.V; prev = V[-18:-3] if len(V) >= 18 else V[:-3]
        # [2026-10-28, user: "volume acceleration has to consider the time of day"] each bar vs its 14-day normal for that minute (ref vol_per_min):
        # (last 3 bars / their normal) / (the bars before, up to 15 / their normal); > 1 = picking up vs what is normal at this time of day
        self.mins.append(t); vacc_tod = None
        if self.vpm and len(V) >= 6:
            M_ = self.mins; nl = sum(self.vpm[m] for m in M_[-3:]); pm_ = M_[-18:-3] if len(M_) >= 18 else M_[:-3]; npv = sum(self.vpm[m] for m in pm_)
            if nl and npv and sum(prev): vacc_tod = (sum(V[-3:]) / nl) / (sum(prev) / npv)
        vacc = (sum(V[-3:]) / 3) / (sum(prev) / len(prev)) if len(V) >= 6 and sum(prev) else None
        s3, s15 = self._share(3), self._share(15); s3p, s15p = self._share(3, 1), self._share(15, 1)
        self.s3h.append(s3); self.s15h.append(s15)
        # [2026-10-28, user on AVEX 11:06] PERSISTENCE: the 3-min buy share above the 15-min in EACH of the last N minutes and both higher now
        # than N minutes ago (N = persist; 1 = the plain "3m > 15m now" check)
        N = self.persist
        pers_ok = (N <= 1) or (len(self.s3h) > N and all(a > b for a, b in zip(self.s3h[-N:], self.s15h[-N:]))
                               and self.s3h[-1] > self.s3h[-1 - N] and self.s15h[-1] > self.s15h[-1 - N])
        vws = (R.vwap / self.vw_hist[-6] - 1) * 100 if len(self.vw_hist) >= 6 else 0.0
        for pid in new:                                  # patterns confirmed on this bar
            if self.only_pids is not None and pid not in self.only_pids: continue
            if pid in BIAS_UP:
                if self.p41_own and self.armed and self.armed["pid"] == 41 and pid != 41 and t - self.armed["t"] <= self.ARM_MIN:
                    continue                                 # keep the valid #41 candidate (its own confirmation)
                if self.keep_first and self.armed and t - self.armed["t"] <= self.ARM_MIN:
                    continue                                 # [user 10/28 SNAP] keep the FIRST valid candidate: a later bullish pattern does not replace it / raise its trigger
                self.armed = dict(pid=pid, t=t, trigger=bar["h"]); self.state = f"BUY CANDIDATE (#{pid})"
            elif pid in BIAS_DOWN:
                self.armed = None; self.state = f"keep watching (bearish #{pid})"
            elif self.armed is None:
                self.state = f"keep watching (#{pid})"
        buy = False
        if self.rule == "v2":
            # [2026-10-28, user "start over"] RULE V2: a bullish pattern marks the buy spot (candidate 15 min, bearish cancels); the board confirms:
            #  position <= 0.5 -> buy allowed; position > 0.5 -> only on a BREAKOUT (close above resistance, brk_n closes in a row);
            #  VWAP never falling: "rising" = VWAP >= 0.02% above 3 min ago and not below 1 min ago; "flat" = not more than 0.02% below 3 min ago
            #  and not below 1 min ago. No trigger / buy-share / volume checks.
            self.above_res = self.above_res + 1 if c > res else 0
            vw = self.vw_hist
            if self.vwap2 == "off":
                v_ok = True                              # [10/29 test only] no VWAP check
            elif len(vw) >= 4:
                v_ok = (vw[-1] >= vw[-4] * 1.0002 if self.vwap2 == "rising" else vw[-1] >= vw[-4] * 0.9998) and vw[-1] >= vw[-2]
            else:
                v_ok = False
            pos_ = (c - sup) / rng
            expired = self.armed and t - self.armed["t"] > self.ARM_MIN
            if expired:
                self.armed = None; self.state = "watching (candidate expired)"
            # [user 10/28] + volume vs the time of day (time-of-day acceleration >= 1) + 3-min buy share above the 15-min and BOTH rising
            vol_ok = (not self.v2_vol) or (vacc_tod is not None and vacc_tod >= 1.0)
            sh_ok = (not self.v2_share) or ((s3 > s15) if self.v2_share == "above" else (s3 > s15 and s3 > s3p and s15 > s15p))
            if self.share_min is not None:
                sh_ok = sh_ok and s3 >= self.share_min
            if self.armed is not None and self.armed["pid"] == 42 and self.R.M42 == "dip":
                sh_ok = sh_ok and self.R.v42_ok          # [10/29 #42 dip mode] the dip low must still hold on this bar (no new low)
            trg_ok = (not self.v2_trigger) or (self.armed is not None and c > self.armed["trigger"])
            if self.armed and t - self.armed["t"] > self.ARM_MIN:
                pass
            # [2026-10-29, user: the #41 losers were bought "way after the V"] options for #41 only:
            #   v41_fast     at the reclaim only: close above VWAP + 3m buy share > 15m (no VWAP-slope / volume / both-rising checks)
            #   v41_max_vwap no #41 buy more than this % above VWAP (do not chase)     v41_max_wait  cancel the #41 candidate after N minutes
            is41 = self.armed is not None and self.armed["pid"] == 41
            if is41 and self.v41_max_wait is not None and t - self.armed["t"] > self.v41_max_wait:
                self.armed = None; self.state = "watching (#41 too late -- skipped)"; is41 = False
            chase_ok = not (is41 and self.v41_max_vwap is not None and (c / R.vwap - 1) * 100 > self.v41_max_vwap)
            if is41 and self.v41_fast:
                v_ok, vol_ok, sh_ok = c > R.vwap, True, s3 > s15
            # [2026-10-29, user loser review rules 2-4] rule 2 = brk_n (closes in a row above resistance); rule 3 spike_x: in a breakout situation
            # (position > 0.5) no buy on a bar with volume >= spike_x x the median 1-min volume so far; rule 4 liq_min: >= liq_min shares/min
            # over the last 15 bars AND no empty minutes in them
            V_ = R.V; med_v = sorted(V_)[len(V_) // 2] if V_ else 0
            spike = self.spike_x is not None and pos_ > 0.5 and med_v and V_[-1] >= self.spike_x * med_v
            liq_ok = True
            if self.liq_min is not None:
                mm = self.mins[-15:] if len(self.mins) >= 15 else self.mins
                nb = min(len(V_), 15)
                liq_ok = nb >= self.liq_n_min and sum(V_[-nb:]) / nb >= self.liq_min and (mm[-1] - mm[0]) <= nb - 1
            # [2026-10-29, user loser review rule 6] ROOM TO THE NEAREST CEILING: the nearest level ABOVE the close among the opening high
            # (first 5 min), yesterday's close, the premarket high, the day's high so far and the board resistance must be >= room_min % above;
            # nothing above = no ceiling (allowed)
            room_ok = True
            if self.room_min is not None:
                # [10/29 fix] the day's high BEFORE this bar (a spike-and-reject signal bar must not move the ceiling away -- CLSK 5/19 9:55)
                lv = [x for x in (R.orh, R.pc, self.pm_high, max(R.H[:-1]) if len(R.H) > 1 else None, res) if x]
                above = [x for x in lv if x > c]
                room_ok = (not above) or (min(above) / c - 1) * 100 >= self.room_min
            if self.armed and (not chase_ok or spike or not liq_ok or not room_ok):
                pass
            elif self.armed and v_ok and vol_ok and sh_ok and trg_ok and (pos_ <= 0.5 or self.above_res >= self.brk_n):
                buy = True; self.buys.append(dict(t=t, pid=self.armed["pid"], armed_t=self.armed["t"]))
                self.state = f"BUY SIGNAL (#{self.armed['pid']}, {'low in range' if pos_ <= 0.5 else 'breakout'})"; self.armed = None
            self.vws_prev = vws
            row = dict(t=t, c=c, res=round(res, 4), sup=round(sup, 4), range_pct=round(rng / c * 100, 2), range_atr=round(rng / R.u, 2),
                       pos=round(pos_, 2), vacc=round(vacc, 2) if vacc else None, vacc_tod=round(vacc_tod, 2) if vacc_tod else None, s3=round(s3, 3), s15=round(s15, 3),
                       s3_up=s3 > s3p, s15_up=s15 > s15p, vwap=round(R.vwap, 4), vs_vwap=round((c / R.vwap - 1) * 100, 2), vwap_slope=round(vws, 3),
                       new=new, state=self.state, buy=buy)
            self.rows.append(row); return row
        if self.armed and t - self.armed["t"] > self.ARM_MIN:
            self.armed = None; self.state = "watching (candidate expired)"
        elif self.armed and t > self.armed["t"] and c > self.armed["trigger"] and s3 > s15 and pers_ok and (
                (self.p41_own and self.armed["pid"] == 41 and c > R.vwap) or
                (not (self.p41_own and self.armed["pid"] == 41)
                 and (self.vacc_min is None or (vacc is not None and vacc >= self.vacc_min))
                 and (self.vacc_tod_min is None or (vacc_tod is not None and vacc_tod >= self.vacc_tod_min))
                 and (not self.vwap_rising or (vws >= 0 if self.vwap_rule == "ge0" else
                      (len(self.vw_hist) >= 4 and self.vw_hist[-1] >= self.vw_hist[-4] * 1.0002 and self.vw_hist[-1] >= self.vw_hist[-2]) if self.vwap_rule == "line_up" else
                      self.vws_prev is not None and vws > self.vws_prev))
                 and (self.pos_band is None or not (self.pos_band <= (c - sup) / rng <= 1.0))
                 and (not self.above_support or c > sup))):
            buy = True; self.buys.append(dict(t=t, pid=self.armed["pid"], armed_t=self.armed["t"])); self.state = f"BUY SIGNAL (#{self.armed['pid']} confirmed)"
            self.armed = None
        self.vws_prev = vws
        row = dict(t=t, c=c, res=round(res, 4), sup=round(sup, 4), range_pct=round(rng / c * 100, 2), range_atr=round(rng / R.u, 2),
                   pos=round((c - sup) / rng, 2), vacc=round(vacc, 2) if vacc else None, vacc_tod=round(vacc_tod, 2) if vacc_tod else None, s3=round(s3, 3), s15=round(s15, 3),
                   s3_up=s3 > s3p, s15_up=s15 > s15p, vwap=round(R.vwap, 4), vs_vwap=round((c / R.vwap - 1) * 100, 2), vwap_slope=round(vws, 3),
                   new=new, state=self.state, buy=buy)
        self.rows.append(row); return row
