"""up3g_11d.py -- [2026-10-27] the user's FIXED rule on all 11 recorded book days (live watch list = minutes with book rows), all day
(signal up to 15:45): dip >= 0.5% (highest close of the 15 min before -> close of the down bar before the run), then 3 GREEN 1-min bars
each closing above the previous close. Checks: >= yesterday's close, volume (3-bar avg >= 90% of the 5 before), buy share 3 min >= 55%,
queue 3-min avg > 0, optional ABOVE VWAP. Buy next minute open, stop = low of the dip bar + 3 bars x0.998 clamped 0.5-4%, C3 exit,
re-entry after the exit. Shows the price path after the buy (exit ignored) vs a random minute, and C3 after 0.2% cost; first 6 / last 5 days."""
import numpy as np
from up3_test import load, sim, path, DAYS, hm
S = load(); half = DAYS[6]
def share(fb, fs, t, n):
    B = sum(fb[max(0, t - n + 1):t + 1]); S_ = sum(fs[max(0, t - n + 1):t + 1]); return B / (B + S_) if B + S_ else 0.5
def cross_n(fb, fs, t, n):
    """[2026-10-27, user] 3-min buy share crossed above the 15-min somewhere in the last n minutes AND stayed above every minute since"""
    for k in range(t, t - n, -1):
        if share(fb, fs, k, 3) <= share(fb, fs, k, 15): return False          # dipped back under after the cross
        if share(fb, fs, k - 1, 3) <= share(fb, fs, k - 1, 15): return True    # k = the cross minute
    return False
def cross(fb, fs, t):
    """[2026-10-27, user] 3-min buy share crosses ABOVE the 15-min buy share: above at the signal minute, at or below in one of the 3 minutes before"""
    return share(fb, fs, t, 3) > share(fb, fs, t, 15) and any(share(fb, fs, k, 3) <= share(fb, fs, k, 15) for k in (t - 3, t - 2, t - 1))
def scan(D, bk, need, pull=0.5, tmax=375):
    b, M, pc = D.b, D.m, D.ref["prev_close"]; fb, fs = D.fl["buy"], D.fl["sell"]; out = []; free = 0
    for i in range(9, len(b) - 1):
        t = M[i]
        if t > tmax or i < free or t not in bk or M[i] - M[i - 4] != 4: continue
        if not (b[i - 3]["c"] < b[i - 4]["c"] and all(b[k]["c"] > b[k - 1]["c"] and b[k]["c"] > b[k]["o"] for k in (i - 2, i - 1, i))): continue
        hi = max(x["c"] for x in b[max(0, i - 18):i - 2])
        if (1 - b[i - 3]["c"] / hi) * 100 < pull: continue
        bb = sum(fb[t - 2:t + 1]); ss = sum(fs[t - 2:t + 1]); q = [bk[k]["imbalance"] for k in (t - 2, t - 1, t) if k in bk]
        chk = {"PC": b[i]["c"] >= pc, "VOL": np.mean([x["v"] for x in b[i - 2:i + 1]]) >= 0.9 * np.mean([x["v"] for x in b[i - 7:i - 2]]),
               "BUY": bb + ss > 0 and bb / (bb + ss) >= 0.55, "Q": bool(q) and np.mean(q) > 0, "VWAP": b[i]["c"] > D.vw[i], "X": cross(fb, fs, t), "X3": cross_n(fb, fs, t, 3), "X4": cross_n(fb, fs, t, 4), "X5": cross_n(fb, fs, t, 5), "ABOVE": share(fb, fs, t, 3) > share(fb, fs, t, 15)}
        if not all(chk[k] for k in need): continue
        bi = i + 1; P = b[bi]["o"]; stop = min(max(min(x["l"] for x in b[i - 3:i + 1]) * 0.998, P * 0.96), P * 0.995)
        pl, j, why = sim(D, bi, P, stop, 2.0, "C3")
        out.append(dict(t=t, pl=pl, why=why, **path(b, bi, P))); free = j + 1
    return out
def run(need, **kw):
    T = []
    for day, s, D, bk in S:
        for x in scan(D, bk, need, **kw): T.append(dict(day=day, sym=s, **x))
    return T
base = []
for day, s, D, bk in S:
    for i in range(8, len(D.b) - 1):
        if D.m[i] % 10 == 0 and D.m[i] <= 375 and D.m[i] in bk: base.append(dict(day=day, **path(D.b, i + 1, D.b[i + 1]["o"])))
def f(Z, c3=True):
    if not Z: return "n    0"
    a = lambda k: np.mean([z[k] for z in Z])
    return (f"n {len(Z):4} | +1% first {np.mean([z['first'] == 1 for z in Z]):3.0%} -1% first {np.mean([z['first'] == -1 for z in Z]):3.0%} | "
            f"30m {a('r30'):+.2f}% best/worst 30m {a('mfe30'):+.2f}/{a('mae30'):+.2f}" + (f" | C3 {a('pl'):+.3f}%/trade win {np.mean([z['pl'] > 0 for z in Z]):3.0%} sum {sum(z['pl'] for z in Z):+6.1f}%" if c3 else ""))
def row(lab, T, c3=True):
    print(f"{lab}\n   days 1-6  {f([x for x in T if x['day'] < half], c3)}\n   days 7-11 {f([x for x in T if x['day'] >= half], c3)}\n   all       {f(T, c3)}")
print(f"{len(S)} stock-days, {len(DAYS)} days; price path gross, C3 after 0.2% cost\n")
row("RANDOM minute (baseline, all day)", base, False)
for need, lab in ((["PC", "VOL", "BUY", "Q", "X3"], "RULE + cross in last 3 min, still above"), (["PC", "VOL", "BUY", "Q", "X4"], "RULE + cross in last 4 min, still above"),
                  (["PC", "VOL", "BUY", "Q", "X5"], "RULE + cross in last 5 min, still above"),
                  (["PC", "VOL", "BUY", "X3"], "no queue + cross 3"), (["PC", "VOL", "BUY", "X4"], "no queue + cross 4"), (["PC", "VOL", "BUY", "X5"], "no queue + cross 5"),
                  (["PC", "VOL", "BUY", "Q", "X"], "THE RULE + 3m CROSSES 15m buy share"), (["PC", "VOL", "BUY", "Q", "ABOVE"], "THE RULE + 3m above 15m (no cross needed)"),
                  (["PC", "VOL", "BUY", "X"], "rule without queue + CROSS"), (["PC", "X"], "dip + 3 green + prev close + CROSS only"),
                  (["PC"], "dip + 3 green + above prev close"), (["PC", "VOL"], "+ volume"), (["PC", "VOL", "BUY"], "+ buyers"),
                  (["PC", "VOL", "BUY", "Q"], "+ queue  = THE RULE"), (["PC", "VOL", "BUY", "Q", "VWAP"], "THE RULE + above VWAP"),
                  (["PC", "VOL", "BUY", "VWAP"], "rule without queue + above VWAP")):
    row(lab, run(need))
R = run(["PC", "VOL", "BUY", "Q"]); RV = run(["PC", "VOL", "BUY", "Q", "X5"])
print("\nTHE RULE by time of the signal:")
for a_, b_ in ((0, 90), (90, 210), (210, 376)):
    row(f"  {hm(a_)}-{hm(b_)}", [x for x in R if a_ <= x["t"] < b_])
print("\nTHE RULE trades:", ", ".join(f"{x['day'][5:]} {x['sym']} {hm(x['t'])} {x['pl']:+.1f}%{'' if any(y['day'] == x['day'] and y['sym'] == x['sym'] and y['t'] == x['t'] for y in RV) else '*'}" for x in sorted(R, key=lambda x: x['pl'])))
print("(* = blocked by the cross-in-5-min check)\nUP3G_DONE")
