"""board_exit_test.py A..B OUT | summary OUT.. -- [2026-10-28] EXIT test on FIXED stock-board buys (stock_board.Board as it is now: averaged levels,
'VWAP not sloping down'), library 2 years. Every buy (next open) is played out with every EXIT x STOP combination; profit per trade after 0.2% cost.
STOPS: support = board support x0.998 clamped 0.5-4% under the buy | atr = 0.25 x daily ATR% (clamped 0.5-6%) | fixed2 = 2%.
EXITS: c3 = trade-bot live C3 (sim_2y.sim, arm 2%) | hold = stop only, sell 15:55 | lockB = once +2%, stop = entry + half the best gain |
trailC = once +2%, stop = best - 1.5% | bracket = target +0.5 x ATR% | lockATR = like lockB but armed at +0.25 x ATR%.
Bars: stop checked on the bar low (filled at the stop, or the open if it gapped); target on the high; lock / trail move only after a bar FINISHES."""
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 walk(b, M, bi, P, stop, mode, atrp):
    hi = P; s = stop; tgt = P * (1 + 0.5 * atrp / 100) if mode == "bracket" else None
    for j in range(bi, len(b)):
        x = b[j]
        if x["l"] <= s: return (min(s, x["o"]) if j > bi else s) / P * 100 - 100 - COST
        if tgt and x["h"] >= tgt: return (max(tgt, x["o"]) if j > bi else tgt) / P * 100 - 100 - COST
        if M[j] >= 385: return x["c"] / P * 100 - 100 - COST
        hi = max(hi, x["h"])
        if mode == "lockB" and hi >= P * 1.02: s = max(s, P + 0.5 * (hi - P))
        if mode == "trailC" and hi >= P * 1.02: s = max(s, hi * 0.985)
        if mode == "lockATR" and hi >= P * (1 + 0.25 * atrp / 100): s = max(s, P + 0.5 * (hi - P))
    return b[-1]["c"] / P * 100 - 100 - COST
if sys.argv[1] != "summary":
    import v2_bar_replay as R
    import stock_board as SB
    from queue_test import Day
    from sim_2y import sim
    a, b_ = sys.argv[1].split(".."); out = open(sys.argv[2], "w"); nd = 0
    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")); pp = R.OW / f"pm_history/{day}.json.gz"
        pmh = {r["s"]: r.get("pm_high") for r in json.load(gzip.open(pp, "rt"))["rows"]} if pp.exists() else {}
        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("prev_close") 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: continue
            fl = json.loads(fp.read_text()); M = [R.minute(x["t"]) for x in bars]; B = SB.Board(ref["prev_close"], ref["atr14"], bars[0]["o"], pm_high=pmh.get(s))
            D = None; atrp = ref["atr14"] / ref["prev_close"] * 100
            for i, x in enumerate(bars[:-1]):
                t = M[i]
                if t > 135: break
                row = B.update(x, t, fl["buy"][t], fl["sell"][t])
                if not row["buy"]: continue
                bi = i + 1; P = bars[bi]["o"]
                st = {"support": min(max(row["sup"] * 0.998, P * 0.96), P * 0.995), "atr": P * (1 - min(max(0.25 * atrp, 0.5), 6) / 100), "fixed2": P * 0.98}
                res = {}
                for sk, sv in st.items():
                    if sv >= P: continue
                    for mode in ("hold", "lockB", "trailC", "bracket", "lockATR"):
                        res[f"{mode}|{sk}"] = round(walk(bars, M, bi, P, sv, mode, atrp), 3)
                    if D is None: D = Day(bars, M, fl, ref)
                    pl, j, why = sim(D, bi, P, sv, 2.0, "C3"); res[f"c3|{sk}"] = round(pl, 3)
                out.write(json.dumps(dict(day=day, sym=s, t=t, pid=B.buys[-1]["pid"], atr=round(atrp, 2), res=res)) + "\n")
        del d; R.REF._CACHE.clear(); nd += 1; out.flush(); print(day, nd, flush=True)
    out.close(); print("BEXIT_DONE")
else:
    X = [json.loads(l) for f in sys.argv[2:] for l in open(f)]
    keys = sorted({k for x in X for k in x["res"]})
    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 if k in z["res"]])
        if not len(v): return None
        w, l = v[v > 0], v[v <= 0]
        return dict(n=len(v), avg=v.mean(), win=(v > 0).mean(), aw=w.mean() if len(w) else 0, al=l.mean() if len(l) else 0, tot=v.sum())
    print(f"{len(X)} board buys {X[0]['day']}..{X[-1]['day']}; profit per trade after {COST}% cost; year 1 < 2025-10-01 <= year 2\n")
    rows = []
    for k in keys:
        a1, a2 = st(Y(1), k), st(Y(2), k)
        if a1 and a2: rows.append((min(a1["avg"], a2["avg"]), k, a1, a2))
    print(f"{'exit | stop':20} | {'YEAR 1: avg/trade  win  avg win / avg loss   total':52} | {'YEAR 2: avg/trade  win  avg win / avg loss   total':52}")
    for w, k, a1, a2 in sorted(rows, key=lambda r: -r[0]):
        g = lambda a: f"{a['avg']:+.3f}%  {a['win']:3.0%}  {a['aw']:+.2f}% / {a['al']:+.2f}%  {a['tot']:+8.1f}%"
        print(f"{k:20} | n {a1['n']:5} {g(a1):45} | n {a2['n']:5} {g(a2)}")
    print("\nbest 4 by quarter (avg per trade %):")
    qs = sorted({x["day"][:4] + "Q" + str((int(x["day"][5:7]) - 1) // 3 + 1) for x in X})
    print(f"{'':20} " + " ".join(f"{q:>8}" for q in qs))
    for w, k, a1, a2 in sorted(rows, key=lambda r: -r[0])[:4] + [r for r in rows if r[1] == "c3|support"]:
        vals = []
        for q in qs:
            Z = [x for x in X if x["day"][:4] + "Q" + str((int(x["day"][5:7]) - 1) // 3 + 1) == q]; s_ = st(Z, k)
            vals.append(f"{s_['avg']:+8.3f}" if s_ else "       -")
        print(f"{k:20} " + " ".join(vals))
    print("BEXIT_SUMMARY_DONE")
