"""up3_test.py -- [2026-10-27] the user's simple entry on the 11 recorded book days (live watch list = minutes the stock had book rows):
SIGNAL = 3 one-minute bars in a row each closing above the previous bar's close (optionally: close >= yesterday's close), 9:33-11:00,
every time (when not already holding the stock). Checks stacked: VOL (3-bar avg volume >= 90% of the 5 bars before),
BUYERS (3-min tick-rule buy share >= 55%), QUEUE (3-min avg book imbalance > 0). Buy next minute open; stop = low of the 3 bars x0.998
clamped 0.5-4% under the buy; exit C3 (live). Per trade after 0.2% cost; first 6 days vs last 5."""
import json, sys
from pathlib import Path
import numpy as np
from datetime import datetime
from zoneinfo import ZoneInfo
HERE = Path(__file__).resolve().parent; TR = Path("/var/www/screener/trade")
sys.path.insert(0, str(HERE)); sys.path.insert(0, str(TR)); sys.path.insert(0, str(TR / "reports/playbook"))
_argv = sys.argv; sys.argv = ["x", "x"]
import io, contextlib
with contextlib.redirect_stdout(io.StringIO()):
    from book_study import DAYS, book, C
sys.argv = _argv
from queue_test import Day
from sim_2y import sim
hm = lambda m: f"{9 + (30 + m) // 60}:{(30 + m) % 60:02d}"
def load():
    S = []
    for day in DAYS:
        Bk = book(day); R = json.load(open(C / f"{day}.json"))
        for s, r in R.items():
            rp = TR / f"data/reference/{day}/{s}.json"
            if not rp.exists(): continue
            ref = json.loads(rp.read_text())
            if not ref.get("prev_close"): continue
            bm = {int(k): v for k, v in r["bars"].items()}; M = sorted(bm)
            t0 = datetime.fromisoformat(day).replace(hour=9, minute=30, tzinfo=ZoneInfo("America/New_York")).timestamp()
            bars = [{"t": t0 + m * 60, "o": bm[m][0], "h": bm[m][1], "l": bm[m][2], "c": bm[m][3], "v": bm[m][4]} for m in M]
            if len(bars) < 60: continue
            S.append((day, s, Day(bars, M, {"buy": r["buy"], "sell": r["sell"]}, ref), Bk.get(s, {})))
    return S
def path(b, bi, P):
    """[2026-10-27] what the price did after the buy, exit ignored: best rise / worst drop within 15/30/60 min, price at 5/15/30/60 min,
    which came first: +1% or -1% (same bar = counted as -1% first)"""
    o = {}
    for n in (15, 30, 60):
        w = b[bi:bi + n]
        o[f"mfe{n}"] = (max(x["h"] for x in w) / P - 1) * 100; o[f"mae{n}"] = (min(x["l"] for x in w) / P - 1) * 100
    for n in (5, 15, 30, 60):
        o[f"r{n}"] = (b[min(bi + n - 1, len(b) - 1)]["c"] / P - 1) * 100
    first = 0
    for x in b[bi:bi + 120]:
        if x["l"] <= P * 0.99: first = -1; break
        if x["h"] >= P * 1.01: first = 1; break
    o["first"] = first
    return o
STEPS = ["SIGNAL", "+VOL", "+BUYERS", "+QUEUE"]
def run(S, pc_rule, upto, only=None, n=3):
    T = []
    for day, s, D, bk in S:
        b, M, pc = D.b, D.m, D.ref["prev_close"]; fb, fs = D.fl["buy"], D.fl["sell"]; free = 0
        for i in range(2 * n + 2, len(b) - 1):
            t = M[i]
            if t < n or t > 90 or i < free or t not in bk: continue
            if M[i] - M[i - n] != n: continue
            if not all(b[k]["c"] > b[k - 1]["c"] for k in range(i - n + 1, i + 1)): continue
            if pc_rule and b[i]["c"] < pc: continue
            chk = {}
            chk["+VOL"] = np.mean([x["v"] for x in b[i - n + 1:i + 1]]) >= 0.9 * np.mean([x["v"] for x in b[i - n - 4:i - n + 1]])
            bb = sum(fb[t - n + 1:t + 1]); ss = sum(fs[t - n + 1:t + 1]); chk["+BUYERS"] = bb + ss > 0 and bb / (bb + ss) >= 0.55
            q = [bk[k]["imbalance"] for k in range(t - n + 1, t + 1) if k in bk]; chk["+QUEUE"] = bool(q) and np.mean(q) > 0
            need = [only] if only else STEPS[1:STEPS.index(upto) + 1]
            if not all(chk[k] for k in need): continue
            bi = i + 1; P = b[bi]["o"]; low = min(x["l"] for x in b[i - n + 1:i + 1]) * 0.998
            stop = min(max(low, P * 0.96), P * 0.995)
            pl, j, why = sim(D, bi, P, stop, 2.0, "C3")
            T.append(dict(day=day, sym=s, t=t, pl=pl, why=why, hold=M[j] - M[bi], **path(b, bi, P)))
            free = j + 1
    return T
half = DAYS[6]
def show(lab, T):
    f = lambda Z: (f"n {len(Z):4} | {np.mean([z['pl'] for z in Z]):+.3f}%/trade  win {np.mean([z['pl'] > 0 for z in Z]):3.0%}  sum {sum(z['pl'] for z in Z):+7.1f}%"
                   if Z else "n    0")
    print(f"  {lab:34} days 1-6 {f([x for x in T if x['day'] < half])}  ||  days 7-11 {f([x for x in T if x['day'] >= half])}")
if __name__ == "__main__":
    S = load(); print(f"{len(S)} stock-days on {len(DAYS)} days; per trade after 0.2% cost, C3 exit\n")
    for pc_rule in (False, True):
        print("A) 3 higher closes, any price" if not pc_rule else "\nB) 3 higher closes AND close >= yesterday's close")
        for st in STEPS: show(("stacked " if st != "SIGNAL" else "") + st, run(S, pc_rule, st))
        for k in STEPS[1:]: show(f"signal + {k[1:]} only", run(S, pc_rule, "SIGNAL", only=k))
    A = run(S, True, "+QUEUE"); json.dump(A, open(HERE / "up3_full.json", "w"))
    print("\nfull rule B trades:", ", ".join(f"{x['day'][5:]} {x['sym']} {hm(x['t'])} {x['pl']:+.1f}%" for x in sorted(A, key=lambda x: x['pl'])))
    print("UP3_DONE")
