"""crossvol.py 11d|2y -- [2026-10-27] the user: NO green bars / dip. Trigger = 3-min buy share crosses ABOVE the 15-min buy share this minute
(at or below the minute before) + VOLUME support (3-bar avg >= 90% of the 5 bars before). Variants add: >= yesterday's close, buy share >= 55%,
volume >= 1.5x, queue (11 days only), trend day (2y). Buy next minute open; stop = low of the last 3 bars x0.998 clamped 0.5-4%; C3 exit;
re-entry after the exit; signal 9:35-15:45. Price path after the buy vs coin flip; halves / years."""
import gzip, json, sys
from pathlib import Path
import numpy as np
HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE)); sys.path.insert(0, "/var/www/screener/trade/reports/playbook"); sys.path.insert(0, "/var/www/screener/trade")
from sim_2y import sim
from up3_test import path
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
V = {"cross + volume": ["VOL"], "cross + volume + >= prev close": ["VOL", "PC"], "cross + volume + prev close + buyers >= 55%": ["VOL", "PC", "BUY"],
     "cross + STRONG volume (>= 1.5x) + prev close": ["VOL15", "PC"], "cross + volume + prev close + above VWAP": ["VOL", "PC", "VWAP"]}
def scan(D, need, bk=None, br=None, 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(8, len(b) - 1):
        t = M[i]
        if t < 5 or t > tmax or i < free or (bk is not None and t not in bk): continue
        s3, s15 = share(fb, fs, t, 3), share(fb, fs, t, 15)
        if not (s3 > s15 and share(fb, fs, t - 1, 3) <= share(fb, fs, t - 1, 15)): continue
        vr = np.mean([x["v"] for x in b[i - 2:i + 1]]) / max(1e-9, np.mean([x["v"] for x in b[i - 7:i - 2]]))
        chk = {"VOL": vr >= 0.9, "VOL15": vr >= 1.5, "PC": b[i]["c"] >= pc, "BUY": s3 >= 0.55, "VWAP": b[i]["c"] > D.vw[i]}
        if bk is not None:
            q = [bk[k]["imbalance"] for k in (t - 2, t - 1, t) if k in bk]; chk["Q"] = bool(q) and np.mean(q) > 0
        if br is not None: chk["TREND"] = br[t] is not None and br[t] >= 0.5
        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 - 2: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=round(pl, 3), why=why, **{k: round(v, 3) for k, v in path(b, bi, P).items()})); free = j + 1
    return out
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} | +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%} | 30m {a('r30'):+.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):+7.1f}%")
mode = sys.argv[1]
if mode == "11d":
    from up3_test import load, DAYS
    S = load(); half = DAYS[6]; V11 = dict(V); V11["cross + volume + prev close + buyers + QUEUE"] = ["VOL", "PC", "BUY", "Q"]; V11["cross + volume + prev close + QUEUE"] = ["VOL", "PC", "Q"]
    print(f"{len(S)} stock-days, 11 days; C3 after 0.2% cost")
    for lab, need in V11.items():
        T = [dict(day=d, sym=s, **x) for d, s, D, bk in S for x in scan(D, need, bk=bk)]
        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])}")
    print("CROSSVOL11_DONE")
else:
    import v2_bar_replay as R
    from queue_test import Day
    V2 = dict(V); V2["cross + volume + prev close + trend day"] = ["VOL", "PC", "TREND"]
    OUT = {k: [] for k in V2}; n = 0
    for p in sorted(R.OW.glob("bars/bars_20*.json.gz")):
        day = p.name[5:15]
        if not ("2024-10-01" <= day <= "2026-10-02"): continue
        d = json.load(gzip.open(p, "rt")); Ds = {}
        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("atr14") or not ref.get("prev_close"): continue
            b = [x for x in R.bars_of(d["symbols"][s]["bars"]) if 0 <= R.minute(x["t"]) < 390]
            if len(b) < 200: continue
            Ds[s] = Day(b, [R.minute(x["t"]) for x in b], json.loads(fp.read_text()), ref)
        del d
        cl = {}
        for s, D in Ds.items():
            a = np.full(390, np.nan); O = D.b[0]["o"]
            for x, m in zip(D.b, D.m): a[m] = (x["c"] / O - 1) * 100
            for m in range(1, 390):
                if np.isnan(a[m]): a[m] = a[m - 1]
            cl[s] = a
        for s, D in Ds.items():
            others = np.array([cl[z] for z in cl if z != s]); br = [None if not len(others) else float(np.nanmean(others[:, m])) for m in range(390)]
            for k, need in V2.items():
                for x in scan(D, need, br=br): OUT[k].append(dict(day=day, sym=s, **x))
        n += 1
        if n % 50 == 0: print(day, n, flush=True)
    json.dump(OUT, open(HERE / "crossvol_2y.json", "w"))
    print(f"\n{n} days; C3 after 0.2% cost; year 1 = 2024-10..2025-09, year 2 = 2025-10..2026-10")
    for k, T in OUT.items():
        print(f"{k}\n   year 1 {f([x for x in T if x['day'] < '2025-10-01'])}\n   year 2 {f([x for x in T if x['day'] >= '2025-10-01'])}")
    print("CROSSVOL2Y_DONE")
