"""
dyn_gb_test.py -- [2026-10-23] the user: "a dynamic give back, maybe 2% while the buy share is high, then 1% as it slows down".
No look-ahead: the 5-min buy share is read from the FINISHED minutes before the bar being traded; stop / sells intrabar as live.
A  dynamic ARM (1/4 give-back unchanged): armed at +2% while the 5-min buy share >= th, at +1% when it is under th
     A60 / A55 / A50 = th 60 / 55 / 50%;  A3 = three steps: >= 65% -> +2.5%, >= 55% -> +2%, else +1%
B  dynamic TRAIL (armed at +1%): sell when the price is >= 2% under the peak while the 5-min buy share >= th, >= 1% under it
     when it is under th (and under the last finished close)   B60 / B55 / B50
Reference: GB1 (arm 1%), GB2 (arm 2%). 833 EV3 buys and the 535 kept by N2+N3, 0.2% cost, year 1 / year 2.
"""
import json, sys
import numpy as np
sys.path.insert(0, "/var/www/screener/trade/reports/playbook"); sys.path.insert(0, "/var/www/screener/trade")
import gzip
from collections import defaultdict
import v2_bar_replay as R
import r1b_setup
from exit_pepg import MODS
MODS = {**MODS, "R1B": r1b_setup}
COST = 0.2; SPLIT = "2025-10-01"
VARS = ["GB1", "GB2", "A60", "A55", "A50", "A3", "B60", "B55", "B50"]


def bs5(fl, m):
    B = sum(fl["buy"][max(0, m - 4):m + 1]); S = sum(fl["sell"][max(0, m - 4):m + 1]); return B / (B + S) if B + S else 0.5


def sim(v, bars, mins, fl, bi, P, stop):
    peak = P
    for j in range(bi, len(bars)):
        b = bars[j]
        if b["l"] <= stop:
            return (min(stop, b["o"]) if j > bi else stop) / P * 100 - 100 - COST, "stop", j
        if j > bi:
            gain = peak - P; s5 = bs5(fl, mins[j - 1]); pc = bars[j - 1]["c"]
            if v[0] == "B":
                if gain >= P * 0.01:
                    th = int(v[1:]) / 100
                    lvl = peak * (1 - (0.02 if s5 >= th else 0.01))
                    x = min(lvl, pc * 0.9999)
                    if b["l"] <= x:
                        return min(x, b["o"]) / P * 100 - 100 - COST, "trail", j
            else:
                if v == "GB1": arm = 1.0
                elif v == "GB2": arm = 2.0
                elif v == "A3": arm = 2.5 if s5 >= 0.65 else 2.0 if s5 >= 0.55 else 1.0
                else: arm = 2.0 if s5 >= int(v[1:]) / 100 else 1.0
                if gain >= P * arm / 100:
                    x = min(peak - 0.25 * gain, pc * 0.9999)
                    if b["l"] <= x:
                        return min(x, b["o"]) / P * 100 - 100 - COST, "give-back", j
        peak = max(peak, b["h"])
        if mins[j] >= 385:
            return b["c"] / P * 100 - 100 - COST, "15:55", j
    return bars[-1]["c"] / P * 100 - 100 - COST, "end", len(bars) - 1


nt = {(r["day"], r["sym"], r["m"]): (r["f"]["N2"] or r["f"]["N3"]) for r in json.load(open("/var/www/screener/trade/reports/ev3/notrade.json"))}
trig = defaultdict(list)
for l in open("/var/www/screener/trade/reports/playbook/giveback_2y.jsonl"):
    t = json.loads(l)
    if t["setup"] in ("R1A", "R1B", "R4") or (t["setup"] == "R3" and 6 <= t["atr"] < 10):
        trig[t["day"]].append(t)
rows = []
for day in sorted(trig):
    d = json.load(gzip.open(R.OW / "bars" / f"bars_{day}.json.gz", "rt"))
    for t in trig[day]:
        s = t["sym"]; ref = R.REF.load(day, s); fl = json.loads((R.OW / "flow" / day / f"{s}.json").read_text())
        bars = [b for b in R.bars_of(d["symbols"][s]["bars"]) if 0 <= R.minute(b["t"]) < 390]
        mins = [R.minute(b["t"]) for b in bars]
        ti = next((i for i, m in enumerate(mins) if m == t["m"]), None)
        if ti is None or ti + 1 >= len(bars):
            continue
        bi = ti + 1; P = bars[bi]["o"]
        ok, info = MODS[t["setup"]].check(bars[:ti + 1], fl, ref, t["m"])
        sup = (info or {}).get("support") or P * 0.99
        stop = min(max(sup * 0.998, P * 0.96), P * 0.995)
        r = {"setup": t["setup"], "day": day, "sym": s, "m": t["m"], "nt": nt.get((day, s, t["m"]), False)}
        for v in VARS:
            pl, why, j = sim(v, bars, mins, fl, bi, P, stop)
            r[v] = pl; r[v + "_t"] = mins[j]
        rows.append(r)
    R.REF._CACHE.clear(); del d
json.dump(rows, open("/var/www/screener/trade/reports/ev3/dyn_gb.json", "w"))
for lab, X in (("ALL 833", rows), ("kept by N2+N3", [r for r in rows if not r["nt"]])):
    y = np.array([r["day"] < SPLIT for r in X])
    print(f"\n{lab}: {len(X)} buys, per trade after 0.2% cost (year 1 / year 2)")
    for v in VARS:
        a = np.array([r[v] for r in X])
        print(f"   {v:4} {a.mean():+.3f}% ({a[y].mean():+.3f} / {a[~y].mean():+.3f})  win {np.mean(a > 0):.0%}  total {a.sum():+.1f}%")
    if lab != "ALL 833":
        for st in ("R1A", "R1B", "R3", "R4"):
            Z = [r for r in X if r["setup"] == st]
            print(f"     {st} ({len(Z)}): " + "  ".join(f"{v} {np.mean([r[v] for r in Z]):+.3f}" for v in VARS))
hm = lambda m: f"{9 + (30 + m) // 60}:{(30 + m) % 60:02d}"
for r in rows:
    if (r["sym"], r["day"]) in (("HELP", "2025-07-03"), ("JOBY", "2024-10-23"), ("DERM", "2024-11-05"), ("QUBT", "2025-05-20")):
        print(f"  {r['sym']} {r['day']} m{r['m']}: " + " ".join(f"{v} {r[v]:+.2f}@{hm(r[v + '_t'])}" for v in VARS))
print("DYN_DONE")
