"""up5c_test.py -- [2026-10-27] the user's up-run entry on 5-MINUTE candles (from the 1-min bars, aligned 9:30/9:35/..): 3 finished
5-min candles in a row each closing above the previous candle's close (earliest 9:50), signal up to 11:00, buy next minute open.
Checks: VOL (3-candle avg volume >= 90% of the up to 5 candles before), BUYERS (15-min buy share >= 55%), QUEUE (15-min avg imbalance > 0).
Stop = low of the 3 candles x0.998 clamped 0.5-4%; C3 exit; path after the buy like up3_path."""
import numpy as np
from up3_test import load, path, sim, DAYS, hm
S = load(); half = DAYS[6]
def run(pc_rule, need):
    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"]; idx = {m: i for i, m in enumerate(M)}
        cand = []
        for k in range(0, 95, 5):
            ii = [idx[m] for m in range(k, k + 5) if m in idx]
            if len(ii) < 3: cand.append(None); continue
            cand.append(dict(end=k + 4, c=b[ii[-1]]["c"], l=min(b[i]["l"] for i in ii), v=sum(b[i]["v"] for i in ii)))
        free = -1
        for ci in range(3, len(cand)):
            w = cand[ci - 3:ci + 1]
            if any(x is None for x in w): continue
            t = w[-1]["end"]
            if t > 90 or t < free or t not in bk or t + 1 not in idx: continue
            if not all(w[j]["c"] > w[j - 1]["c"] for j in (1, 2, 3)): continue
            if pc_rule and w[-1]["c"] < pc: continue
            prev = [x["v"] for x in cand[max(0, ci - 7):ci - 2] if x]
            chk = {"VOL": bool(prev) and np.mean([x["v"] for x in w[1:]]) >= 0.9 * np.mean(prev)}
            bb = sum(fb[t - 14:t + 1]); ss = sum(fs[t - 14:t + 1]); chk["BUYERS"] = bb + ss > 0 and bb / (bb + ss) >= 0.55
            q = [bk[m]["imbalance"] for m in range(t - 14, t + 1) if m in bk]; chk["QUEUE"] = bool(q) and np.mean(q) > 0
            if not all(chk[k] for k in need): continue
            bi = idx[t + 1]; P = b[bi]["o"]; stop = min(max(min(x["l"] for x in w[1:]) * 0.998, 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, **path(b, bi, P))); free = D.m[j] + 1
    return T
def row(lab, T):
    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):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"after 15m {a('r15'):+.2f} 30m {a('r30'):+.2f} 60m {a('r60'):+.2f} | best/worst 30m {a('mfe30'):+.2f}/{a('mae30'):+.2f} | C3 after cost {a('pl'):+.3f}%")
    print(f"{lab}\n   days 1-6  {f([x for x in T if x['day'] < half])}\n   days 7-11 {f([x for x in T if x['day'] >= half])}\n   all       {f(T)}")
print("== 3 rising 5-MINUTE candles ==")
row("A signal", run(False, []))
row("B signal (+ above yesterday's close)", run(True, []))
row("B + volume", run(True, ["VOL"]))
row("B + volume + buyers", run(True, ["VOL", "BUYERS"]))
row("B full rule (+ queue)", F := run(True, ["VOL", "BUYERS", "QUEUE"]))
print("full rule trades:", ", ".join(f"{x['day'][5:]} {x['sym']} {hm(x['t'])} {x['pl']:+.1f}%" for x in sorted(F, key=lambda x: x['pl'])))
