"""p42_exit.py collect A..B OUT | analyze OUT.. -- [2026-10-29] #42 exits: stop just under the V low (low x 0.998), targets +2/+3/+4% or hold to 15:55;
stop checked on the bar low (fill at the stop or the open if gapped), target on the high (same bar: stop first = conservative). 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)); sys.path.insert(0, str(TR / "reports/ev3"))
COST = 0.2
def play(b, M, bi, P, stop, tgt):
    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
        if tgt and x["h"] >= P * (1 + tgt / 100): return tgt - COST
        if M[j] >= 385: return x["c"] / P * 100 - 100 - COST
    return b[-1]["c"] / P * 100 - 100 - COST
if sys.argv[1] == "collect":
    import v2_bar_replay as R
    from p42_test import signals
    a, b_ = sys.argv[2].split(".."); out = open(sys.argv[3], "w")
    for p in sorted(R.OW.glob("bars/bars_20*.json.gz")):
        day = p.name[5:15]
        if not (a <= day <= b_): continue
        d = json.load(gzip.open(p, "rt"))
        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"): continue
            bars = [x for x in R.bars_of(d["symbols"][s]["bars"]) if 0 <= R.minute(x["t"]) < 390]
            if len(bars) < 150 or R.minute(bars[0]["t"]) != 0: continue
            M = [R.minute(x["t"]) for x in bars]; fl = json.loads(fp.read_text())
            for v, k, i, lo, dip in signals(bars, M, fl, ref["atr14"]):
                if v not in ("A", "V", "V1", "AD", "AO", "VD", "VO"): continue
                P = bars[i + 1]["o"]; st = lo * 0.998
                if st >= P: continue
                res = {f"t{tg}": round(play(bars, M, i + 1, P, st, tg), 3) for tg in (2, 3, 4)}
                res["hold"] = round(play(bars, M, i + 1, P, st, None), 3)
                out.write(json.dumps(dict(kind=f"{v}{k}", day=day, sym=s, risk=round((1 - st / P) * 100, 3), **res)) + "\n")
        del d; R.REF._CACHE.clear()
    out.close(); print("P42X_DONE")
else:
    X = [json.loads(l) for f in sys.argv[2:] for l in open(f)]
    H = lambda Z, h: [z for z in Z if (z["day"] < "2026-07-28") == (h == 1)]
    print("#42 (V turn) with the stop just under the V low; profit per trade after 0.2% cost; first 3 months | last 3 months\n")
    for kind in ("A0.5", "V0.5", "AD0.5", "AO0.5", "VD0.5", "VO0.5"):
        Z = [x for x in X if x["kind"] == kind]
        print(f"{kind}: {len(Z)} buys, risk to the stop median {np.median([z['risk'] for z in Z]):.2f}%")
        for k, lab in (("t2", "target +2%"), ("t3", "target +3%"), ("t4", "target +4%"), ("hold", "no target, hold to 15:55")):
            cells = []
            for h in (1, 2):
                v = np.sort([z[k] for z in H(Z, h)]); cells.append(f"{v.mean():+.3f}% (w/o top5 {v[:-5].mean():+.3f}) win {np.mean(v > 0):3.0%} avg win {v[v > 0].mean():+.2f} / loss {v[v <= 0].mean():+.2f}")
            print(f"   {lab:26} first 3m {cells[0]} | last 3m {cells[1]}")
        for lo_, hi_ in ((0, 1.0), (1.0, 2.0), (2.0, 99)):
            Zr = [z for z in Z if lo_ <= z["risk"] < hi_]
            if Zr: print(f"      risk {lo_}-{hi_}%: n {len(Zr):4} | target +3%: first 3m {np.mean([z['t3'] for z in H(Zr, 1)]) if H(Zr, 1) else 0:+.3f}% | last 3m {np.mean([z['t3'] for z in H(Zr, 2)]) if H(Zr, 2) else 0:+.3f}%")
    print("P42X_ANALYSIS_DONE")
