"""r11_wf_collect.py A..B OUT -- [2026-10-27] every signal of the CURRENT r11_setup (default settings, as charted on FMC 10/16) on the 2-year
library (old-score top 30, quote flow), 15-min cooldown per stock; each signal played out ALONE with the live C3 exit (sim_2y, 0.2% cost;
stop = setup stop or support x0.998, clamped 0.5-4%). Readings at the signal bar for the walk-forward filter test:
minute, above the day's low %, position in the day's range, vs open %, vs prev close %."""
import gzip, json, sys
from pathlib import Path
HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE)); sys.path.insert(0, "/var/www/screener/trade/reports/playbook"); sys.path.insert(0, "/var/www/screener/trade")
import v2_bar_replay as R
import r11_setup
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"))
    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) < 60: continue
        fl = json.loads(fp.read_text()); D = Day(bars, [R.minute(x["t"]) for x in bars], fl, ref); last = -99; lo = 1e9; hi = 0
        for i in range(len(bars) - 1):
            m = D.m[i]; lo = min(lo, bars[i]["l"]); hi = max(hi, bars[i]["h"])
            if m >= 345: break
            if m - last < 15: continue
            ok, info = r11_setup.check(bars[:i + 1], fl, ref, m, None)
            if not ok: continue
            last = m; c = bars[i]["c"]; P = bars[i + 1]["o"]
            sup = info.get("stop") or (info.get("support") or c * 0.99) * 0.998; stop = min(max(sup, P * 0.96), P * 0.995)
            pl, j, why = sim(D, i + 1, P, stop, 2.0, "C3")
            out.write(json.dumps(dict(day=day, sym=s, m=m, pl=round(pl, 3), why=why, above_low=round((c / lo - 1) * 100, 3),
                                      pos=round((c - lo) / (hi - lo), 3) if hi > lo else 0.5, vs_open=round((c / bars[0]["o"] - 1) * 100, 3),
                                      vs_pc=round((c / ref["prev_close"] - 1) * 100, 3), atr=round(ref["atr14"] / ref["prev_close"] * 100, 2))) + "\n")
    del d; R.REF._CACHE.clear(); nd += 1; out.flush(); print(day, nd, flush=True)
out.close(); print("R11WF_DONE")
