"""x42_gate.py OUT | summary OUT -- [2026-10-30] user's GATE on the give-back sell: price drops (give-back would sell) BUT EMA9 rising (last
finished bar) AND the 3m buy share HOLDING (not down > 5 pts vs 1 min earlier; G50 also needs >= 50%) -> HOLD; then sell at the next open once
the buy share FADES: F1 3m share >= 5 pts under its level at the hold start | F2 3m < 50% | F3 3m < 15m share. Hard stop always (2% | 0.4 x daily
ATR); a new high during the hold ends it (normal give-back again). 1543 #42 LIQ2+ROOM buys, 0.2% cost."""
import gzip, json, sys
from pathlib import Path
import numpy as np
TR = Path("/var/www/screener/trade"); sys.path.insert(0, str(TR / "reports/playbook")); sys.path.insert(0, str(TR))
COST = 0.2
def run(b, M, E9, S3, S15, bi, P, stop, gate, fade):
    peak = P; held = None; n_hold = 0
    for j in range(bi, len(b)):
        x = b[j]
        if x["l"] <= stop: return (min(stop, x["o"]) if j > bi else stop) / P * 100 - 100 - COST, j, n_hold
        if M[j] >= 385: return x["c"] / P * 100 - 100 - COST, j, n_hold
        m = M[j - 1] if j > bi else None
        if held is not None:
            if x["h"] > peak: held = None                                   # new high -> hold over, normal give-back again
            else:
                s3 = S3[m]
                f = {"F1": s3 <= held - 0.05, "F2": s3 < 0.5, "F3": s3 < S15[m]}[fade]
                if f: return x["o"] / P * 100 - 100 - COST, j, n_hold      # buy share faded on the last finished bar -> sell at this open
        if held is None and j > bi and peak - P >= P * 0.02:
            gx = min(peak - 0.25 * (peak - P), b[j - 1]["c"] * 0.9999)
            if x["l"] <= gx:
                s3, s3p = S3[m], S3[m - 1]
                hold = gate != "GB" and E9[j - 1] >= E9[j - 2] and s3 >= s3p - 0.05 and (gate != "G50" or s3 >= 0.5)
                if not hold: return min(gx, x["o"]) / P * 100 - 100 - COST, j, n_hold
                held = s3; n_hold += 1
        peak = max(peak, x["h"])
    return b[-1]["c"] / P * 100 - 100 - COST, len(b) - 1, n_hold
if sys.argv[1] != "summary":
    import v2_bar_replay as R
    T = [json.loads(l) for l in open("x42_exits.jsonl")]; byday = {}
    for t in T: byday.setdefault(t["day"], []).append(t)
    out = open(sys.argv[1], "w")
    for day in sorted(byday):
        d = json.load(gzip.open(R.OW / f"bars/bars_{day}.json.gz", "rt"))
        for t in byday[day]:
            s = t["sym"]; ref = R.REF.load(day, s); fl = json.loads((R.OW / "flow" / day / f"{s}.json").read_text()); fb, fs = fl["buy"], fl["sell"]
            sh = lambda m, k: sum(fb[max(0, m - k + 1):m + 1]) / max(sum(fb[max(0, m - k + 1):m + 1]) + sum(fs[max(0, m - k + 1):m + 1]), 1)
            S3 = [sh(m, 3) for m in range(390)]; S15 = [sh(m, 15) for m in range(390)]
            bars = [x for x in R.bars_of(d["symbols"][s]["bars"]) if 0 <= R.minute(x["t"]) < 390]; M = [R.minute(x["t"]) for x in bars]
            E9 = []; e9 = bars[0]["c"]
            for x in bars: e9 += (x["c"] - e9) * 0.2; E9.append(e9)
            bi = M.index(t["t"]) + 1; P = bars[bi]["o"]; atrp = ref["atr14"] / ref["prev_close"] * 100
            res = {}
            for sk, sv in (("f2", P * 0.98), ("atr04", P * (1 - 0.4 * atrp / 100))):
                pl, j, nh = run(bars, M, E9, S3, S15, bi, P, sv, "GB", "F1"); res[f"GB|-|{sk}"] = round(pl, 3)
                for g in ("G", "G50"):
                    for f in ("F1", "F2", "F3"):
                        pl, j, nh = run(bars, M, E9, S3, S15, bi, P, sv, g, f); res[f"{g}|{f}|{sk}"] = round(pl, 3); res[f"{g}|{f}|{sk}|held"] = nh
            out.write(json.dumps(dict(day=day, sym=s, res=res)) + "\n")
        del d; R.REF._CACHE.clear()
    out.close(); print("XG_DONE")
else:
    X = [json.loads(l) for l in open(sys.argv[2])]
    Y = lambda y: [x for x in X if (x["day"] < "2025-10-01") == (y == 1)]
    keys = [k for k in X[0]["res"] if not k.endswith("|held")]
    gl = {"GB": "plain give-back (no gate)", "G": "gate: EMA9 up + 3m holding", "G50": "gate: EMA9 up + 3m holding + 3m >= 50%"}
    fl_ = {"-": "", "F1": "sell when 3m drops 5 pts", "F2": "sell when 3m < 50%", "F3": "sell when 3m < 15m"}
    rows = sorted(keys, key=lambda k: -min(np.mean([x["res"][k] for x in Y(1)]), np.mean([x["res"][k] for x in Y(2)])))
    print(f"GATE test on the #42 LIQ2+ROOM buys ({len(X)}), 2 years; profit per trade after 0.2% cost, year 1 | year 2 (sorted by the worse year)\n")
    for k in rows:
        g, f, s_ = k.split("|"); c = []
        for y in (1, 2):
            v = np.array([x["res"][k] for x in Y(y)]); c.append(f"{v.mean():+.3f}% win {np.mean(v > 0):3.0%} {v[v > 0].mean():+.2f}/{v[v <= 0].mean():+.2f}")
        nh = f" gate used in {np.mean([x['res'][k + '|held'] > 0 for x in X]):3.0%}" if g != "GB" else ""
        print(f"  {gl[g]:40} {fl_[f]:26} stop {s_:5} | {c[0]} | {c[1]}{nh}")
    u = next(x for x in X if x["sym"] == "URGN" and x["day"] == "2025-06-16")
    print("\nURGN 2025-06-16:", {k: v for k, v in u["res"].items() if not k.endswith("|held")})
    print("XG_SUMMARY_DONE")
