"""x42_emahold.py OUT | summary OUT -- [2026-10-30] user (URGN 6/16/25): "EMA9 wasn't sloping down" when C3's give-back sold. Test on the 1543
#42 LIQ2+ROOM buys: give-back exit (armed once the best price >= +2%, sells when the price falls under best - 25% of the gain or under the last
close, intrabar) is only ALLOWED when: GB plain (always) | H1 EMA9 fell on the last finished bar | H2 EMA9 fell 2 bars in a row |
H3 EMA9 fell + last close < EMA9. Stops: 0.4 x daily ATR | fixed 2% | 10-bar low (0.5-4%). 15:55 sell-all, 0.2% cost. (No X1 control.)"""
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, bi, P, stop, hold):
    peak = P
    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
        if j > bi and peak - P >= P * 0.02:
            gx = min(peak - 0.25 * (peak - P), b[j - 1]["c"] * 0.9999)
            dn1 = E9[j - 1] < E9[j - 2]; dn2 = dn1 and E9[j - 2] < E9[j - 3]
            ok = {"GB": True, "H1": dn1, "H2": dn2, "H3": dn1 and b[j - 1]["c"] < E9[j - 1]}[hold]
            if ok and x["l"] <= gx: return min(gx, x["o"]) / P * 100 - 100 - COST, j
        peak = max(peak, x["h"])
        if M[j] >= 385: return x["c"] / P * 100 - 100 - COST, j
    return b[-1]["c"] / P * 100 - 100 - COST, len(b) - 1
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)
            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
            sw = min(x["l"] for x in bars[max(0, bi - 10):bi])
            st = {"atr04": P * (1 - 0.4 * atrp / 100), "f2": P * 0.98, "low10": min(max(sw * 0.998, P * 0.96), P * 0.995)}
            res = {}
            for h in ("GB", "H1", "H2", "H3"):
                for k, v in st.items():
                    pl, j = run(bars, M, E9, bi, P, v, h); res[f"{h}|{k}"] = round(pl, 3); res[f"{h}|{k}|min"] = M[min(j, len(M) - 1)] - M[bi]
            res["C3live|f2"] = t["res"]["C3|f2"]
            out.write(json.dumps(dict(day=day, sym=s, t=t["t"], atr=round(atrp, 2), res=res)) + "\n")
        del d; R.REF._CACHE.clear()
    out.close(); print("XEH_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)]
    def st(Z, k):
        v = np.array([z["res"][k] for z in Z]); w, l = v[v > 0], v[v <= 0]
        mn = f" hold {np.median([z['res'][k + '|min'] for z in Z]):3.0f}m" if k + "|min" in Z[0]["res"] else ""
        return f"{v.mean():+.3f}%  win {np.mean(v > 0):3.0%}  {w.mean():+.2f}/{l.mean():+.2f}{mn}"
    keys = [k for k in X[0]["res"] if not k.endswith("|min")]
    keys = sorted(keys, key=lambda k: -min(np.mean([z["res"][k] for z in Y(1)]), np.mean([z["res"][k] for z in Y(2)])))
    lab = {"GB": "give-back always", "H1": "GB only if EMA9 fell", "H2": "GB only if EMA9 fell 2 bars", "H3": "GB only if EMA9 fell + close<EMA9", "C3live": "LIVE C3 (with X1)"}
    print(f"EMA9-hold test on the #42 LIQ2+ROOM buys ({len(X)}), 2 years; profit per trade after 0.2% cost (sorted by the worse year)\n")
    for k in keys:
        h, s_ = k.split("|")[:2]
        print(f"  {lab[h]:36} stop {s_:5} | y1 {st(Y(1), k):44} | y2 {st(Y(2), k)}")
    print("\nURGN 2025-06-16:", {k: v for k, v in next(x for x in X if x['sym'] == 'URGN' and x['day'] == '2025-06-16')['res'].items() if not k.endswith('|min')})
    print("XEH_SUMMARY_DONE")
