"""book_pattern.py -- [2026-10-27] the user's WULF 10:16 pattern on the 11 recorded book days: price rising + bids outweigh asks most of
the last ~14 minutes (BUILD), then a short SELLER FLIP in the last 1-2 minutes that is ABSORBED (price holds). Decided on finished minute t,
buy at t+1 open. One signal per stock per 30 min. Compare with build-without-flip and all minutes. Halves by day."""
import json, sys
from pathlib import Path
import numpy as np
sys.argv = [sys.argv[0], "x"]
HERE = Path(__file__).resolve().parent
from book_study import DAYS, book, C
COST = 0.2
def run(build_share=0.7, build_avg=0.05, rise=0.5, flip=-0.1, mode="flip"):
    out = []
    for day in DAYS:
        Bk = book(day); R = json.load(open(C / f"{day}.json"))
        for s, r in R.items():
            bk = Bk.get(s, {}); bars = {int(k): v for k, v in r["bars"].items()}; last = -99
            for t in range(16, 355):
                if t - last < 30 or t + 1 not in bars or t not in bars: continue
                W = [bk[k]["imbalance"] for k in range(t - 15, t - 1) if k in bk]
                if len(W) < 12 or (t - 15) not in bars or (t - 2) not in bars: continue
                build = np.mean(np.array(W) > 0) >= build_share and np.mean(W) >= build_avg and (bars[t - 2][3] / bars[t - 15][3] - 1) * 100 >= rise
                if mode == "all": ok = True
                elif not build: continue
                else:
                    F = [bk[k]["imbalance"] for k in (t - 1, t) if k in bk]
                    flipped = bool(F) and min(F) <= flip; held = bars[t][3] >= bars[t - 2][3] * 0.998
                    ok = (flipped and held) if mode == "flip" else (not flipped) if mode == "noflip" else (flipped and not held)
                if not ok: continue
                P = bars[t + 1][0]; fut = [bars[k] for k in range(t + 1, t + 31) if k in bars]
                if len(fut) < 20: continue
                c = lambda n: (fut[min(n, len(fut)) - 1][3] / P - 1) * 100
                # bracket: +2% target / -1% stop, else close at 30 min (stop first if same bar)
                br = None
                for b in fut:
                    if b[2] <= P * 0.99: br = -1.0; break
                    if b[1] >= P * 1.02: br = 2.0; break
                out.append(dict(day=day, sym=s, t=t, r5=c(5), r15=c(15), r30=c(30), br=(br if br is not None else c(30)) - COST,
                                hi30=(max(b[1] for b in fut) / P - 1) * 100, lo30=(min(b[2] for b in fut) / P - 1) * 100))
                last = t
    return out
half = DAYS[len(DAYS) // 2]
def show(lab, X):
    def f(Z):
        if not Z: return "n 0"
        return (f"n {len(Z):5} | 5m {np.mean([z['r5'] for z in Z]):+.2f}% 15m {np.mean([z['r15'] for z in Z]):+.2f}% 30m {np.mean([z['r30'] for z in Z]):+.2f}% "
                f"| +1% first? up>1% {np.mean([z['hi30'] > 1 for z in Z]):3.0%} dn<-1% {np.mean([z['lo30'] < -1 for z in Z]):3.0%} | bracket +2/-1 after cost {np.mean([z['br'] for z in Z]):+.3f}%")
    print(f"{lab}\n   H1 {f([x for x in X if x['day'] < half])}\n   H2 {f([x for x in X if x['day'] >= half])}")
print(f"{len(DAYS)} days, half 2 from {half}; price changes gross, bracket after {COST}% cost\n")
B = run(mode="all"); show("ALL list minutes (every 30 min per stock) -- baseline", B)
show("BUILD + FLIP + HELD  (the WULF 10:16 pattern)", P0 := run())
show("BUILD, no flip", run(mode="noflip"))
show("BUILD + FLIP, NOT held (price dropped)", run(mode="flipdrop"))
print("\nvariants of the pattern:")
for kw in (dict(flip=-0.2), dict(build_share=0.6), dict(build_share=0.8), dict(rise=0.0), dict(rise=1.0), dict(build_avg=0.1)):
    show(f"  {kw}", run(**kw))
print("\nWULF 10/26 signals:", [(x['t'], round(x['r30'], 2)) for x in P0 if x['sym'] == 'WULF' and x['day'] == '2026-10-26'])
print("signals by day:", {d: sum(x['day'] == d for x in P0) for d in DAYS})
print("BOOK_PATTERN_DONE")
