"""watch_exit6.py collect A..B OUT | analyze OUT.. -- [2026-10-28] the user: a BOARD-WATCHING exit for the v2 buys (6 months). The board keeps
running after the buy; every version: +2% target, a hard stop (-2%, or -3% where named), 15:55 close; the WATCH rules only decide an EARLY sale
(checked on a finished bar, sold at the next open). Profit per trade after 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
VARS = {"A plain: +2% target / -2% stop": dict(stop=2.0, w=()),
        "B sell when a bar closes below VWAP": dict(stop=2.0, w=("below_vwap",)),
        "C sell when the VWAP line stops rising (2 bars)": dict(stop=2.0, w=("vwap_flat2",)),
        "D B or C": dict(stop=2.0, w=("below_vwap", "vwap_flat2")),
        "E below VWAP AND at least -0.5%": dict(stop=2.0, w=("below_vwap_losing",)),
        "F sell when a bar closes below board support": dict(stop=2.0, w=("below_sup",)),
        "G slow drop: still under the buy after 15 min": dict(stop=2.0, w=("slow15",)),
        "H all watch rules (B,C,F,G) + hard stop -3%": dict(stop=3.0, w=("below_vwap", "vwap_flat2", "below_sup", "slow15")),
        "I B + G, hard stop -3%": dict(stop=3.0, w=("below_vwap", "slow15"))}
if sys.argv[1] == "collect":
    import v2_bar_replay as R
    import stock_board as SB
    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")); 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), vpm=ref.get("vol_per_min"), rule="v2", vwap2="rising")
            trades = []
            for i, x in enumerate(bars[:-1]):
                t = M[i]
                r = B.update(x, t, fl["buy"][t], fl["sell"][t]); vw = B.vw_hist
                line_up = len(vw) >= 4 and vw[-1] >= vw[-4] * 1.0002 and vw[-1] >= vw[-2]
                nxt = bars[i + 1]
                for tr in trades:
                    for k, st in tr["v"].items():
                        if st is not None: continue
                        cfg = VARS[k]; P = tr["P"]
                        if i < tr["bi"]: continue
                        # this bar (i) is a finished bar after/at the buy bar: hard stop / target on its range first
                        if x["l"] <= P * (1 - cfg["stop"] / 100):
                            tr["v"][k] = (min(P * (1 - cfg["stop"] / 100), x["o"]) if i > tr["bi"] else P * (1 - cfg["stop"] / 100)) / P * 100 - 100 - COST; continue
                        if x["h"] >= P * 1.02:
                            tr["v"][k] = 2.0 - COST; continue
                        if t >= 385:
                            tr["v"][k] = x["c"] / P * 100 - 100 - COST; continue
                        w = cfg["w"]; c = x["c"]
                        tr["flat"][k] = tr["flat"][k] + 1 if not line_up else 0
                        sell = (("below_vwap" in w and c < B.R.vwap) or ("vwap_flat2" in w and tr["flat"][k] >= 2) or
                                ("below_vwap_losing" in w and c < B.R.vwap and c <= P * 0.995) or ("below_sup" in w and c < r["sup"]) or
                                ("slow15" in w and t - tr["t"] >= 15 and c < P))
                        if sell: tr["v"][k] = nxt["o"] / P * 100 - 100 - COST
                if r["buy"] and t <= 135:
                    trades.append(dict(t=t, bi=i + 1, P=nxt["o"], v={k: None for k in VARS}, flat={k: 0 for k in VARS}))
            last = bars[-1]
            for tr in trades:
                res = {k: (v if v is not None else last["c"] / tr["P"] * 100 - 100 - COST) for k, v in tr["v"].items()}
                out.write(json.dumps(dict(day=day, sym=s, t=tr["t"], res={k: round(v, 3) for k, v in res.items()})) + "\n")
        del d; R.REF._CACHE.clear()
    out.close(); print("WEX_DONE")
else:
    X = [json.loads(l) for f in sys.argv[2:] for l in open(f)]
    H = lambda h: [x for x in X if (x["day"] < "2026-07-28") == (h == 1)]
    print(f"{len(X)} v2 buys (VWAP rising), 6 months; profit per trade after {COST}% cost; first 3 months | last 3 months\n")
    for k in VARS:
        cells = []
        for h in (1, 2):
            v = np.array([x["res"][k] for x in H(h)]); w_, l_ = v[v > 0], v[v <= 0]
            cells.append(f"{v.mean():+.3f}% win {np.mean(v > 0):3.0%} avg win {w_.mean() if len(w_) else 0:+.2f} / loss {l_.mean() if len(l_) else 0:+.2f}")
        print(f"   {k:50} first 3m {cells[0]} | last 3m {cells[1]}")
    print("WEX_ANALYSIS_DONE")
