"""p42c_test.py A..B OUT | summary OUT.. -- [2026-10-29] user: #42 with VWAP OFF, buy the FIRST time the 3-min buy share is above the 15-min
after the deep dip (>= 0.5u from the day high to a low on a later bar; the bar must hold above that low), open..9:45. Same stocks as #41.
P = the rule alone; PC = the same but a TRUE cross (3m was <= 15m at some minute since the low); B1 = through the #41 board (VWAP off,
share check = 3m > 15m, position/breakout, time-of-day volume acceleration, liquidity on the bars so far, room 1%, spike); B2 = B1 w/o volume accel."""
import gzip, json, sys
from pathlib import Path
import numpy as np
TR = Path("/var/www/screener/trade"); sys.path.insert(0, str(TR / "reports/playbook")); sys.path.insert(0, str(TR))
BASE = dict(rule="v2", only_pids={42}, liq_n_min=3, vwap2="off", v2_share="above")
VAR = {"B1 #41 board, VWAP off, first 3m>15m + 3m>=55%": dict(BASE, share_min=0.55), "B2 B1 without volume acceleration": dict(BASE, v2_vol=False, share_min=0.55)}
COST = 0.2
def meas(b, bi, P):
    f2 = 0
    for z in b[bi:bi + 120]:
        if z["l"] <= P * 0.98: f2 = -1; break
        if z["h"] >= P * 1.02: f2 = 1; break
    r = lambda n: round((max(z["h"] for z in b[bi:bi + n]) / P - 1) * 100, 3)
    return dict(r15=r(15), r60=r(60), d30=round((min(z["l"] for z in b[bi:bi + 30]) / P - 1) * 100, 3), c15=round((b[min(bi + 14, len(b) - 1)]["c"] / P - 1) * 100, 3), f2=f2)
def play(b, bi, P, stop, tgt):
    for j in range(bi, len(b)):
        x = b[j]
        if x["l"] <= stop: return (min(stop, x["o"]) if j > bi else stop) / P * 100 - 100 - COST
        if tgt and x["h"] >= P * (1 + tgt / 100): return tgt - COST
    return b[-1]["c"] / P * 100 - 100 - COST
if sys.argv[1] != "summary":
    import v2_bar_replay as R
    import stock_board as SB
    import opening_patterns as OP
    OP.Recognizer.M42 = "dip"
    a, b_ = sys.argv[1].split(".."); out = open(sys.argv[2], "w")
    for p in sorted(R.OW.glob("bars/bars_20*.json.gz")):
        day = p.name[5:15]
        if not (a <= day <= b_): continue
        d = json.load(gzip.open(p, "rt")); pp = R.OW / f"pm_history/{day}.json.gz"
        pmh = {r["s"]: r.get("pm_high") for r in json.load(gzip.open(pp, "rt"))["rows"]} if pp.exists() else {}
        for s in d["top30_current"]:
            fp = R.OW / "flow" / day / f"{s}.json"; ref = R.REF.load(day, s)
            if s not in d["symbols"] or not fp.exists() or not ref or not ref.get("prev_close") or not ref.get("atr14"): continue
            bars = [x for x in R.bars_of(d["symbols"][s]["bars"]) if 0 <= R.minute(x["t"]) < 390]
            if len(bars) < 150 or R.minute(bars[0]["t"]) != 0: continue
            fl = json.loads(fp.read_text()); fb, fs = fl["buy"], fl["sell"]
            sh = lambda t, n: sum(fb[max(0, t - n + 1):t + 1]) / max(sum(fb[max(0, t - n + 1):t + 1]) + sum(fs[max(0, t - n + 1):t + 1]), 1)
            Bs = {k: SB.Board(ref["prev_close"], ref["atr14"], bars[0]["o"], pm_high=pmh.get(s), vpm=ref.get("vol_per_min"), **o) for k, o in VAR.items()}
            P0 = OP.Recognizer(ref["prev_close"], ref["atr14"], bars[0]["o"]); done = set(); below = False; low_seen = None
            for i, x in enumerate(bars[:-1]):
                t = R.minute(x["t"])
                if t > 15: break
                P = bars[i + 1]["o"]; rows = []
                P0.update(x, t)
                if P0.v42_low != low_seen: low_seen = P0.v42_low; below = False      # a new low resets the cross memory
                s3, s15 = sh(t, 3), sh(t, 15)
                if P0.v42_ok and s3 > s15 and s3 >= 0.55:
                    if "P" not in done: rows.append(("P deep dip + first 3m>15m + 3m>=55% (no board)", P0.v42_low)); done.add("P")
                    if below and "PC" not in done: rows.append(("PC deep dip + first TRUE cross + 3m>=55% (no board)", P0.v42_low)); done.add("PC")
                    if s15 >= 0.55 and "PB" not in done: rows.append(("PB deep dip + 3m>15m + 3m AND 15m >=55% (no board)", P0.v42_low)); done.add("PB")
                if s3 <= s15: below = True
                for k, B in Bs.items():
                    if B.update(x, t, fb[t], fs[t])["buy"] and k not in done: rows.append((k, B.R.v42_low)); done.add(k)
                for k, low in rows:
                    st = low * 0.998
                    ex = {f"t{tg}": round(play(bars, i + 1, P, st, tg), 3) for tg in (2, 3)} if st < P else {}
                    if ex: ex["hold"] = round(play(bars, i + 1, P, st, None), 3)
                    out.write(json.dumps(dict(kind=k, day=day, sym=s, t=t, above_low=round((P / low - 1) * 100, 3), **meas(bars, i + 1, P), **ex)) + "\n")
                if 5 <= t <= 15 and t % 2 == 1: out.write(json.dumps(dict(kind="RANDOM", day=day, sym=s, t=t, **meas(bars, i + 1, P))) + "\n")
        del d; R.REF._CACHE.clear(); out.flush()
    out.close(); print("P42D_DONE")
else:
    X = [json.loads(l) for f in sys.argv[2:] for l in open(f)]
    Y = lambda Z, h: [z for z in Z if (z["day"] < "2026-07-28") == (h == 1)]
    def f(Z):
        if not Z: return "n     0"
        a = lambda k: np.mean([z[k] for z in Z])
        return (f"n {len(Z):5} | max rise 15m {a('r15'):+.2f}% 60m {a('r60'):+.2f}% | max drop 30m {a('d30'):+.2f}% | higher after 15m {np.mean([z['c15'] > 0 for z in Z]):3.0%} "
                f"| +2% first {np.mean([z['f2'] == 1 for z in Z]):3.0%} / -2% first {np.mean([z['f2'] == -1 for z in Z]):3.0%}")
    def g(Z, k):
        v = np.sort([z[k] for z in Z if k in z])
        return f"{v.mean():+.3f}% (w/o top5 {v[:-5].mean():+.3f})" if len(v) > 10 else "-"
    print("#42 deep dip + first 3m>15m + buy share >=55%, VWAP off, 9:32-9:45, 6 months: first 3m 2026-04-28..07-27 | last 3m 07-28..10-27; from the next open\n")
    for k in ["RANDOM", "P deep dip + first 3m>15m + 3m>=55% (no board)", "PC deep dip + first TRUE cross + 3m>=55% (no board)", "PB deep dip + 3m>15m + 3m AND 15m >=55% (no board)"] + list(VAR):
        Z = [x for x in X if x["kind"] == k]
        med = f"   (buy median {np.median([z['above_low'] for z in Z]):+.2f}% above the V low)" if Z and k != "RANDOM" else ""
        print(f"{k}{med}\n   first 3m {f(Y(Z, 1))}\n   last 3m  {f(Y(Z, 2))}")
        if k != "RANDOM":
            for e, lab in (("t2", "target +2%"), ("t3", "target +3%"), ("hold", "hold to close")):
                print(f"      stop under V low, {lab:13} after cost: first 3m {g(Y(Z, 1), e)} | last 3m {g(Y(Z, 2), e)}")
    print("P42D_SUMMARY_DONE")
