# ===== ZAI BATCH 7 — z.ai groups B/C/D, 27 rule cards (ideas 9-36, skip 27 CVD) — paste this WHOLE cell into ONE Colab cell =====
# (or:  !wget -q -O zai_batch7.py https://osom-boba.pages.dev/colab/zai_batch7.py   then   %run zai_batch7.py)
#
# COMMON: same loaders as specialists_batch6 (BTC 1h 2013+, ETH 1h 2017+, hosted at osom-boba.pages.dev/colab/).
#   4h and 1d are resampled from that 1h file (signals lift back to 1h so market fills are the NEXT 1h open).
#   15m cards load hosted btc_15m_full.csv.gz / eth_15m_full.csv.gz (Binance spot, 2017-08+),
#   same columns as the 1h files, and fill at the next 15m open. Costs 0.12%/side
#   (FEE 0.0007 + SLIP 0.0005), 1% risk per trade standalone (notional <= 1x), stop-first when a bar touches
#   stop and target, trades with a stop < 1.5% from the fill are SKIPPED, stops wider than 10% are moved to
#   10% (CAP10). One position at a time per card. Stop-orders fill at the level (or the open if gapped through).
# CARDS: B09 break-reclaim fade (15m) | B10 two-step false break (1h) | B11 double rejection (1h) |
#   B12 inside-bar chain (1h) | B13 wick-magnet retest (4h) | B14 PDH/PDL sweep (15m) | B15 open drive (1h) |
#   B16 balance breakout (4h) | B17 descending pressure (1h) | B18 prior-week sweep (4h) | B19 pinch break (1h) |
#   B20 engulf at extreme (1h) | C21 volume climax fade (15m) | C22 dry-up breakout (1h) | C23 thin breakout fade (1h) |
#   C24 absorption shelf (15m) | C25 momentum exhaustion (1h) | C26 HVN rejection (1h) | C28 climax chain (4h) |
#   D29 NR7 break (1d) | D30 TTM squeeze (1h) | D31 ATR-regime breakout (1d) | D32 vol-spike fade (15m) |
#   D33 3-bar contraction (1h) | D34 weekly squeeze (1d) | D35 ATR-band reversion (1h) | D36 big-bar follow-through (1d).
#   Idea 27 (CVD) is omitted. Each card has its own pre-declared placebo (printed at the end).
# REPORT per card, BTC and ETH (2017+ headline): trades, trades/yr, win%, PF, ret%, maxDD, MAR, avg R, blocks
#   (ret/PF/n for 2013-16, 2017-20, 2021-23, 2024+, 2026), placebo PF/ret, daily-realised corr with K8.
# VERDICT (pre-declared, same as batch 6): KEEP if (1) BTC 2017+ PF >= 1.3 with >= 30 trades, (2) PF beats its
#   placebo by >= 0.3, (3) 2017-20 and 2021+ both positive, (4) ETH PF >= 1.1, (5) corr with K8 < 0.3.
#   WATCH if exactly one fails, else DROP. KEEPs get a +-20% parameter robustness check. Ranked table + plain words at the end.
# Smoke on the box only:  python3 zai_batch7.py --smoke
import os, io, gzip, time, warnings, math, sys, zipfile
from dataclasses import dataclass
from datetime import datetime, timezone
from pathlib import Path
from typing import Literal
from urllib.error import HTTPError, URLError
from urllib.request import urlopen, Request
import numpy as np
import pandas as pd
warnings.filterwarnings("ignore")
pd.set_option("display.width", 230); pd.set_option("display.max_columns", 40); pd.set_option("display.max_rows", 300)

T0 = time.time()
H1 = 3_600_000; D1 = 24 * H1; H4 = 4 * H1; H12 = 12 * H1; M15 = 900_000
FEE, SLIP = 0.0007, 0.0005
COST = FEE + SLIP
RISK = 0.01
MAX_NOTIONAL = 1.0
STOP_MIN, STOP_CAP = 0.015, 0.10
SITE = "https://osom-boba.pages.dev/colab/"
OUT_DIR = Path("/content") if Path("/content").exists() else Path(".")
BUCKETS = [("2013-16", "2013-01-01", "2017-01-01"), ("2017-20", "2017-01-01", "2021-01-01"),
           ("2021-23", "2021-01-01", "2024-01-01"), ("2024+", "2024-01-01", "2100-01-01"),
           ("2026", "2026-01-01", "2027-01-01")]
HEADLINE_START = "2017-01-01"
UA = "osom-zai-batch7/1.0"
VISION_SPOT = "https://data.binance.vision/data/spot/monthly/klines/{sym}/{tf}/{sym}-{tf}-{yyyy}-{mm:02d}.zip"

# ---------------------------------------------------------------------------------------------
# DATA
# ---------------------------------------------------------------------------------------------
def _fetch(url, timeout=120):
    with urlopen(Request(url, headers={"User-Agent": UA}), timeout=timeout) as r:
        b = r.read()
    if url.endswith(".gz") and b[:2] == b"\x1f\x8b":
        b = gzip.decompress(b)
    return pd.read_csv(io.BytesIO(b))

def _time_to_ms(t):
    """Per-value unit detection to milliseconds.

    Binance vision monthly 15m zips switched from ms to µs in 2025-01. Converting a
    mixed frame with a single max() (old _norm) treated 2017-2024 millisecond bars as
    microseconds too, divided them by 1000 (Jan 1970) and left only 2025+ trades, which
    all landed in the 2024+ bucket.
    """
    x = pd.to_numeric(t, errors="coerce").astype("float64")
    return np.where(x > 1e17, x / 1e6, np.where(x > 1e14, x / 1e3, np.where(x > 1e11, x, x * 1e3))).astype("int64")

def _norm(df):
    cols = {c.lower().strip(): c for c in df.columns}
    def pick(*names):
        for n in names:
            if n in cols: return cols[n]
        return None
    tc = pick("time", "timestamp_ms", "timestamp", "open_time", "open_time_utc", "date", "datetime", "unix", "ts")
    o, h, l, c = pick("open"), pick("high"), pick("low"), pick("close", "adj close", "price")
    v = pick("volume", "volume_btc", "vol", "volume btc", "volume_base", "volume usd", "volume_usd")
    if None in (tc, o, h, l, c): return None
    t = df[tc]
    if pd.api.types.is_numeric_dtype(t):
        tms = _time_to_ms(t)
    else:
        num = pd.to_numeric(t, errors="coerce")
        if float(num.notna().mean()) > 0.8:
            tms = _time_to_ms(num)
        else:
            tms = (pd.to_datetime(t, utc=True, errors="coerce").astype("datetime64[ns, UTC]").astype("int64") // 1_000_000).values
    out = pd.DataFrame({"time": tms, "open": pd.to_numeric(df[o], errors="coerce"), "high": pd.to_numeric(df[h], errors="coerce"),
                        "low": pd.to_numeric(df[l], errors="coerce"), "close": pd.to_numeric(df[c], errors="coerce"),
                        "volume": pd.to_numeric(df[v], errors="coerce") if v else 0.0,
                        "source": df[cols["source"]].astype(str).values if "source" in cols else "csv"})
    out = out.dropna(subset=["time", "open", "high", "low", "close"])
    out = out[(out.high > 0) & (out.low > 0)].sort_values("time").drop_duplicates("time").reset_index(drop=True)
    out["volume"] = out["volume"].fillna(0.0)
    return out if len(out) > 100 else None

def _bar_ms(df):
    return int(pd.Series(np.diff(df["time"].values)).median())

def _starts_before(d, day):
    return d["time"].iloc[0] <= pd.Timestamp(day, tz="UTC").value // 1_000_000

def load_asset(kind):
    """kind 'btc' or 'eth'. 1h data required."""
    env = os.environ.get("OSOM_DATA_FILE" if kind == "btc" else "OSOM_ETH_FILE")
    if env: return _norm(pd.read_csv(env)), env
    cands = sorted(Path("/content").glob("*.csv*")) if Path("/content").exists() else []
    for p in [p for p in cands if f"{kind}_1h_full" in p.name] + \
             [p for p in [Path(f"/workspace/specdata/{kind}_1h_full.csv.gz"), Path(f"/workspace/osom10/deploy/colab/{kind}_1h_full.csv.gz")] if p.exists()]:
        try:
            d = _norm(pd.read_csv(p) if not str(p).endswith(".gz") else pd.read_csv(p))
        except Exception:
            d = None
        if d is not None: return d, str(p)
    def is_mine(p):
        n = p.name.lower()
        if "funding" in n or "summary" in n or "daily" in n: return False
        return ("eth" in n) if kind == "eth" else ("eth" not in n)
    short = []
    for p in cands:
        if not is_mine(p) or f"{kind}_1h_full" in p.name: continue
        try: d = _norm(pd.read_csv(p))
        except Exception: d = None
        if d is None or _bar_ms(d) > H1: continue
        if _starts_before(d, "2015-01-01" if kind == "btc" else "2018-01-01"): return d, str(p)
        short.append((p, d))
    url = SITE + f"{kind}_1h_full.csv.gz"
    try:
        print(f"Downloading {url} ...")
        d = _norm(_fetch(url))
        if d is not None: return d, url
    except Exception as e:
        print(f"  hosted {kind} failed: {e}")
    if short:
        p, d = max(short, key=lambda x: len(x[1])); print(f"  using shorter local file {p}"); return d, str(p)
    return None, None

def load_funding():
    cands = []
    if Path("/content").exists():
        cands = [p for p in sorted(Path("/content").glob("*.csv*")) if "funding" in p.name.lower() and "eth" not in p.name.lower()]
    frames = []
    for p in cands:
        try: frames.append(pd.read_csv(p))
        except Exception: pass
    try:
        frames.append(_fetch(SITE + "btc_funding_8h.csv"))
    except Exception as e:
        print(f"  hosted funding failed: {e}")
    out = []
    for f in frames:
        cl = {c.lower(): c for c in f.columns}
        tc = next((cl[c] for c in ("time", "timestamp_ms", "calc_time", "fundingtime", "funding_time") if c in cl), None)
        fc = next((cl[c] for c in ("funding", "funding_rate", "last_funding_rate", "fundingrate") if c in cl), None)
        if tc is None or fc is None: continue
        t = pd.to_numeric(f[tc], errors="coerce")
        out.append(pd.DataFrame({"time": (t // H1 * H1), "funding": pd.to_numeric(f[fc], errors="coerce")}).dropna())
    if not out: return None
    fd = pd.concat(out).drop_duplicates("time", keep="last").sort_values("time")
    return fd

def _cache_dir():
    for p in (Path("/content/zai_batch7_data"), Path("/tmp/zai_batch7_data"), Path("./zai_batch7_data")):
        try:
            p.mkdir(parents=True, exist_ok=True)
            return p
        except Exception:
            continue
    p = Path("./zai_batch7_data"); p.mkdir(parents=True, exist_ok=True); return p

def _month_range(start="2017-08", end=None):
    if end is None:
        now = datetime.now(timezone.utc)
        end = f"{now.year}-{now.month:02d}"
    y, m = map(int, start.split("-"))
    ey, em = map(int, end.split("-"))
    while (y, m) <= (ey, em):
        yield y, m
        m += 1
        if m == 13:
            y, m = y + 1, 1

def _zip_first_csv(blob: bytes) -> pd.DataFrame:
    with zipfile.ZipFile(io.BytesIO(blob)) as z:
        name = next(n for n in z.namelist() if n.lower().endswith(".csv"))
        with z.open(name) as f:
            raw = f.read()
    peek = raw.split(b"\n", 1)[0].decode("utf-8", "replace").lower()
    if "open" in peek and "time" in peek:
        return pd.read_csv(io.BytesIO(raw))
    return pd.read_csv(io.BytesIO(raw), header=None)

def download_15m(kind, start="2017-08", progress=True):
    """Binance spot 15m for BTCUSDT or ETHUSDT, cached. Used only by the six 15m cards."""
    sym = "BTCUSDT" if kind == "btc" else "ETHUSDT"
    cache = _cache_dir()
    outp = cache / f"{sym}_15m_{start.replace('-', '')}_now.csv.gz"
    if outp.exists() and outp.stat().st_size > 1000:
        d = _norm(pd.read_csv(outp))
        if d is not None and len(d) > 1000:
            if progress: print(f"  {kind} 15m cache {outp.name}: {len(d):,} bars")
            return d
    frames = []
    last_y = None
    for y, m in _month_range(start):
        url = VISION_SPOT.format(sym=sym, tf="15m", yyyy=y, mm=m)
        dest = cache / "zips" / f"{sym}-15m-{y}-{m:02d}.zip"
        dest.parent.mkdir(parents=True, exist_ok=True)
        try:
            if dest.exists() and dest.stat().st_size > 0:
                blob = dest.read_bytes()
            else:
                blob = urlopen(Request(url, headers={"User-Agent": UA}), timeout=60).read()
                dest.write_bytes(blob)
        except HTTPError as e:
            if e.code == 404:
                continue
            if progress: print(f"  {sym} 15m {y}-{m:02d} HTTP {e.code}")
            continue
        except Exception as e:
            if progress: print(f"  {sym} 15m {y}-{m:02d} failed: {e}")
            continue
        try:
            raw = _zip_first_csv(blob)
        except Exception:
            continue
        cols = [str(c).strip().lower() for c in raw.columns]
        raw.columns = cols
        if "open_time" not in raw.columns and cols[0] not in ("open_time", "0"):
            raw.columns = ["open_time", "open", "high", "low", "close", "volume"] + list(raw.columns[6:])
        else:
            raw = raw.rename(columns={raw.columns[0]: "open_time", raw.columns[1]: "open", raw.columns[2]: "high",
                                      raw.columns[3]: "low", raw.columns[4]: "close", raw.columns[5]: "volume"})
        use = raw[["open_time", "open", "high", "low", "close", "volume"]].copy()
        ot = use["open_time"]
        if np.issubdtype(ot.dtype, np.number) or pd.to_numeric(ot, errors="coerce").notna().mean() > 0.8:
            use["time"] = _time_to_ms(ot)
        else:
            use["time"] = pd.to_datetime(ot, utc=True).astype("int64") // 1_000_000
        for c in ("open", "high", "low", "close", "volume"):
            use[c] = pd.to_numeric(use[c], errors="coerce")
        frames.append(use)
        if progress and y != last_y:
            print(f"  {sym} 15m {y} ...", flush=True); last_y = y
    if not frames:
        return None
    d = _norm(pd.concat(frames, ignore_index=True))
    if d is None: return None
    try:
        d.to_csv(outp, index=False, compression="gzip")
    except Exception:
        pass
    if progress: print(f"  {kind} 15m downloaded: {len(d):,} bars")
    return d

def load_15m(kind):
    """Hosted 15m first (full file, or year-range parts if a file was over 25 MB), then vision fallback."""
    full_name = f"{kind}_15m_full.csv.gz"
    part_names = [f"{kind}_15m_2017_2021.csv.gz", f"{kind}_15m_2022_now.csv.gz"]
    bases = []
    if Path("/content").exists():
        bases.append(Path("/content"))
    bases += [Path("/workspace/osom10/deploy/colab"), Path("."), _cache_dir()]
    for base in bases:
        p = base / full_name
        if p.exists() and p.stat().st_size > 1000:
            try:
                d = _norm(pd.read_csv(p))
            except Exception:
                d = None
            if d is not None and len(d) > 1000:
                print(f"  {kind} 15m local {p}: {len(d):,} bars")
                return d, str(p)
        parts = []
        for name in part_names:
            q = base / name
            if q.exists() and q.stat().st_size > 1000:
                try:
                    dd = _norm(pd.read_csv(q))
                except Exception:
                    dd = None
                if dd is not None and len(dd):
                    parts.append(dd)
        if parts:
            d = pd.concat(parts, ignore_index=True).sort_values("time").drop_duplicates("time").reset_index(drop=True)
            print(f"  {kind} 15m local parts in {base}: {len(d):,} bars")
            return d, str(base)
    url = SITE + full_name
    try:
        print(f"Downloading {url} ...")
        d = _norm(_fetch(url))
        if d is not None and len(d) > 1000:
            return d, url
    except Exception as e:
        print(f"  hosted {kind} 15m full failed: {e}")
    frames, urls = [], []
    for name in part_names:
        url = SITE + name
        try:
            print(f"Downloading {url} ...")
            d = _norm(_fetch(url))
            if d is not None and len(d):
                frames.append(d); urls.append(url)
        except Exception as e:
            print(f"  hosted {name} failed: {e}")
    if frames:
        d = pd.concat(frames, ignore_index=True).sort_values("time").drop_duplicates("time").reset_index(drop=True)
        return d, " + ".join(urls)
    print(f"  falling back to Binance vision year-by-year for {kind} 15m")
    d = download_15m(kind)
    return (d, "binance.vision/spot/15m") if d is not None else (None, None)

def ms(s):
    return pd.Timestamp(s, tz="UTC").value // 1_000_000

def fix_eth_bar(e):
    t = ms("2017-08-22 04:00"); k = np.where(e["time"].values == t)[0]
    if not len(k) or k[0] == 0 or k[0] >= len(e) - 1:
        print("ETH bar 2017-08-22 04:00 UTC not in this file -> no fix"); return e
    i = k[0]; pc = e["close"].iloc[i - 1]; b = e.iloc[i][["open", "high", "low", "close"]].astype(float).to_dict()
    if abs(b["open"] / pc - 1) < 0.2 and b["low"] / pc > 0.8:
        print("ETH bar 2017-08-22 04:00 UTC looks sane -> no fix"); return e
    e = e.copy(); lo = min(pc, b["close"], e["low"].iloc[i - 1], e["low"].iloc[i + 1]); hi = max(b["high"], pc, b["close"])
    for col, v in (("open", pc), ("low", lo), ("high", hi)): e.iloc[i, e.columns.get_loc(col)] = v
    print(f"DATA FIX: ETH 1h 2017-08-22 04:00 UTC O {b['open']:.2f} L {b['low']:.2f} -> O {pc:.2f} (prior close) L {lo:.2f} H {hi:.2f}")
    return e

def prepared_from_1h(d):
    """Normalized 1h frame (time in ms) -> rule-card prepared frame + last_i identity."""
    out = pd.DataFrame({
        "ts": pd.to_datetime(d["time"].values.astype("int64"), unit="ms", utc=True),
        "open": d["open"].values.astype(float), "high": d["high"].values.astype(float),
        "low": d["low"].values.astype(float), "close": d["close"].values.astype(float),
        "volume": d["volume"].values.astype(float),
    })
    out = prepare(out)
    out["last_i"] = np.arange(len(out))
    out["time"] = d["time"].values.astype("int64")
    return out

def resample_prepared(d, period_ms):
    """Resample a normalized 1h frame to 4h/1d, keeping last_i into the 1h series."""
    T = d["time"].values.astype("int64")
    g = T // period_ms
    r = pd.DataFrame({"g": g, "open": d["open"].values, "high": d["high"].values, "low": d["low"].values,
                      "close": d["close"].values, "volume": d["volume"].values, "i": np.arange(len(d))})
    a = r.groupby("g").agg(open=("open", "first"), high=("high", "max"), low=("low", "min"),
                           close=("close", "last"), volume=("volume", "sum"), last_i=("i", "max"))
    a["time"] = a.index.values * period_ms
    # drop a trailing incomplete group (last group shorter than expected and ending at file end)
    expected = max(1, period_ms // H1)
    counts = r.groupby("g").size()
    if len(a):
        last_g = a.index[-1]
        if int(counts.loc[last_g]) < expected:
            a = a.iloc[:-1]
    out = pd.DataFrame({
        "ts": pd.to_datetime(a["time"].values.astype("int64"), unit="ms", utc=True),
        "open": a["open"].values.astype(float), "high": a["high"].values.astype(float),
        "low": a["low"].values.astype(float), "close": a["close"].values.astype(float),
        "volume": a["volume"].values.astype(float),
        "last_i": a["last_i"].values.astype(int),
        "time": a["time"].values.astype("int64"),
    })
    return prepare(out)

def prepared_from_15m(d):
    out = pd.DataFrame({
        "ts": pd.to_datetime(d["time"].values.astype("int64"), unit="ms", utc=True),
        "open": d["open"].values.astype(float), "high": d["high"].values.astype(float),
        "low": d["low"].values.astype(float), "close": d["close"].values.astype(float),
        "volume": d["volume"].values.astype(float),
        "time": d["time"].values.astype("int64"),
    })
    return prepare(out)
def _sma(x: np.ndarray, n: int) -> np.ndarray:
    s = pd.Series(x)
    return s.rolling(n, min_periods=n).mean().to_numpy()

def _ema(x: np.ndarray, n: int) -> np.ndarray:
    return pd.Series(x).ewm(span=n, adjust=False, min_periods=n).mean().to_numpy()

def _rma(x: np.ndarray, n: int) -> np.ndarray:
    return pd.Series(x).ewm(alpha=1 / n, adjust=False, min_periods=n).mean().to_numpy()

def true_range(h, l, c) -> np.ndarray:
    pc = np.roll(c, 1)
    pc[0] = c[0]
    return np.maximum(h - l, np.maximum(np.abs(h - pc), np.abs(l - pc)))

def atr(h, l, c, n=14) -> np.ndarray:
    return _rma(true_range(h, l, c), n)

def rolling_max(x, n) -> np.ndarray:
    return pd.Series(x).rolling(n, min_periods=n).max().to_numpy()

def rolling_min(x, n) -> np.ndarray:
    return pd.Series(x).rolling(n, min_periods=n).min().to_numpy()

def bb_width(x, n=20, k=2.0):
    mid = _sma(x, n)
    sd = pd.Series(x).rolling(n, min_periods=n).std(ddof=0).to_numpy()
    upper, lower = mid + k * sd, mid - k * sd
    return upper, mid, lower, (upper - lower)

def keltner(h, l, c, n=20, k=1.5):
    mid = _ema(c, n)
    a = atr(h, l, c, n)
    return mid + k * a, mid, mid - k * a

def prepare(df: pd.DataFrame) -> pd.DataFrame:
    """Add ATR and UTC calendar helpers. Input needs ts,open,high,low,close,volume."""
    d = df.copy()
    d["ts"] = pd.to_datetime(d["ts"], utc=True)
    d = d.sort_values("ts").drop_duplicates("ts").reset_index(drop=True)
    o, h, l, c, v = (d[k].to_numpy(dtype=float) for k in ("open", "high", "low", "close", "volume"))
    d["atr"] = atr(h, l, c, 14)
    d["rng"] = h - l
    d["date"] = d["ts"].dt.floor("D")
    # ISO week starting Monday 00:00 UTC
    d["week"] = (d["ts"] - pd.to_timedelta(d["ts"].dt.dayofweek, unit="D")).dt.floor("D")
    d["hour"] = d["ts"].dt.hour
    d["dow"] = d["ts"].dt.dayofweek
    return d

def session_levels(df: pd.DataFrame, by: str) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
    """Prior group high/low/open (by='date' or 'week') aligned to each bar."""
    g = df.groupby(by, sort=True).agg(hi=("high", "max"), lo=("low", "min"), op=("open", "first"), cl=("close", "last"))
    prev = g.shift(1)
    mhi = df[by].map(prev["hi"]).to_numpy(dtype=float)
    mlo = df[by].map(prev["lo"]).to_numpy(dtype=float)
    mop = df[by].map(df.groupby(by)["open"].first()).to_numpy(dtype=float)
    return mhi, mlo, mop

# ---------------------------------------------------------------------------
# Signal pack + engine (next-bar open for close-mode; CAP10 / skip <1.5%)
# ---------------------------------------------------------------------------
@dataclass
class Pack:
    """Everything the engine needs for one card on one prepared OHLC frame."""
    long: np.ndarray
    short: np.ndarray
    mode: Literal["close", "stop"] = "close"
    stop_long: np.ndarray | None = None
    stop_short: np.ndarray | None = None
    target_long: np.ndarray | None = None
    target_short: np.ndarray | None = None
    entry_long: np.ndarray | None = None
    entry_short: np.ndarray | None = None
    target_R: float | None = None
    time_stop_bars: int | None = None
    time_stop: Literal["utc_midnight", "end_of_week"] | None = None
    oco: bool = False
    dynamic_target: np.ndarray | None = None
    min_R: float | None = None

@dataclass
class Trade:
    card: str
    side: int
    entry_i: int
    exit_i: int
    entry_ts: pd.Timestamp
    exit_ts: pd.Timestamp
    entry_px: float
    exit_px: float
    stop: float
    target: float
    reason: str
    R: float
    net_R: float
    pnl: float


def _fill_price(level: float, side_is_buy: bool, bar_open: float) -> float:
    if side_is_buy:
        return bar_open if bar_open > level else level
    return bar_open if bar_open < level else level


def _apply_costs(entry_raw: float, exit_raw: float, side: int) -> tuple[float, float, float]:
    if side > 0:
        e = entry_raw * (1 + SLIP)
        x = exit_raw * (1 - SLIP)
        pnl = (x - e) - FEE * e - FEE * x
    else:
        e = entry_raw * (1 - SLIP)
        x = exit_raw * (1 + SLIP)
        pnl = (e - x) - FEE * e - FEE * x
    return e, x, pnl


def _ts_utc(x) -> pd.Timestamp:
    t = pd.Timestamp(x)
    if t.tzinfo is None:
        return t.tz_localize("UTC")
    return t.tz_convert("UTC")


def _search_ts(ts: np.ndarray, when: pd.Timestamp) -> int:
    when = _ts_utc(when)
    key = when.value
    vals = pd.DatetimeIndex(ts)
    if vals.tz is None:
        vals = vals.tz_localize("UTC")
    else:
        vals = vals.tz_convert("UTC")
    return int(np.searchsorted(vals.asi8, key, side="left"))


def _time_expiry_i(ts: np.ndarray, i: int, pack: Pack) -> int:
    n = len(ts)
    if pack.time_stop_bars is not None:
        return min(n - 1, i + pack.time_stop_bars)
    t0 = _ts_utc(ts[i])
    if pack.time_stop == "utc_midnight":
        end = t0.floor("D") + pd.Timedelta(days=1)
        j = _search_ts(ts, end) - 1
        return int(max(i, min(n - 1, j)))
    if pack.time_stop == "end_of_week":
        days = 7 - t0.dayofweek
        end = t0.floor("D") + pd.Timedelta(days=days)
        j = _search_ts(ts, end) - 1
        return int(max(i, min(n - 1, j)))
    return n - 1


def backtest_card(df: pd.DataFrame, pack: Pack, card_id: str) -> list:
    """Bar-by-bar, one position per card. Stop-first if stop and target hit in the same bar.
    Close-mode fills at the NEXT bar open (batch-6 convention). Stop-orders fill at the level
    (or the open if gapped through). Stops < 1.5% are skipped; stops > 10% are capped."""
    n = len(df)
    ts = df["ts"].to_numpy()
    o = df["open"].to_numpy(dtype=float)
    h = df["high"].to_numpy(dtype=float)
    l = df["low"].to_numpy(dtype=float)
    c = df["close"].to_numpy(dtype=float)

    long = np.asarray(pack.long, dtype=bool)
    short = np.asarray(pack.short, dtype=bool)
    stop_l = pack.stop_long if pack.stop_long is not None else np.full(n, np.nan)
    stop_s = pack.stop_short if pack.stop_short is not None else np.full(n, np.nan)
    tgt_l = pack.target_long if pack.target_long is not None else np.full(n, np.nan)
    tgt_s = pack.target_short if pack.target_short is not None else np.full(n, np.nan)
    ent_l = pack.entry_long if pack.entry_long is not None else np.full(n, np.nan)
    ent_s = pack.entry_short if pack.entry_short is not None else np.full(n, np.nan)
    dyn = pack.dynamic_target

    trades: list = []
    pos = None
    pend_l = None
    pend_s = None
    pend_mkt = None

    def close_pos(i, exit_raw, reason):
        nonlocal pos
        e_raw, side, stop, tgt, ei = pos["entry_raw"], pos["side"], pos["stop"], pos["target"], pos["entry_i"]
        r_dist = pos["R"]
        _, _, pnl = _apply_costs(e_raw, exit_raw, side)
        net_r = pnl / r_dist if r_dist > 0 else np.nan
        trades.append(Trade(
            card=card_id, side=side, entry_i=ei, exit_i=i,
            entry_ts=pd.Timestamp(ts[ei]), exit_ts=pd.Timestamp(ts[i]),
            entry_px=e_raw, exit_px=exit_raw, stop=stop, target=tgt,
            reason=reason, R=r_dist, net_R=net_r, pnl=pnl,
        ))
        pos = None

    def manage(i):
        nonlocal pos
        if pos is None:
            return
        side, stop, tgt = pos["side"], pos["stop"], pos["target"]
        if side > 0:
            hit_stop = l[i] <= stop
            hit_tgt = np.isfinite(tgt) and h[i] >= tgt
            if dyn is not None and np.isfinite(dyn[i]) and h[i] >= dyn[i] and dyn[i] > pos["entry_raw"]:
                hit_tgt = True
                tgt_px = dyn[i]
            else:
                tgt_px = tgt if hit_tgt else np.nan
            if hit_stop and hit_tgt:
                close_pos(i, _fill_price(stop, False, o[i]), "SL"); return
            if hit_stop:
                close_pos(i, _fill_price(stop, False, o[i]), "SL"); return
            if hit_tgt:
                close_pos(i, _fill_price(tgt_px, False, o[i]), "TP"); return
        else:
            hit_stop = h[i] >= stop
            hit_tgt = np.isfinite(tgt) and l[i] <= tgt
            if dyn is not None and np.isfinite(dyn[i]) and l[i] <= dyn[i] and dyn[i] < pos["entry_raw"]:
                hit_tgt = True
                tgt_px = dyn[i]
            else:
                tgt_px = tgt if hit_tgt else np.nan
            if hit_stop and hit_tgt:
                close_pos(i, _fill_price(stop, True, o[i]), "SL"); return
            if hit_stop:
                close_pos(i, _fill_price(stop, True, o[i]), "SL"); return
            if hit_tgt:
                close_pos(i, _fill_price(tgt_px, True, o[i]), "TP"); return
        if i >= pos["expiry_i"]:
            close_pos(i, c[i], "time")

    def open_pos(i, side, entry_raw, stop, target):
        nonlocal pos, pend_l, pend_s, pend_mkt
        if not (np.isfinite(entry_raw) and np.isfinite(stop)):
            return
        if side > 0 and stop >= entry_raw: return
        if side < 0 and stop <= entry_raw: return
        r = abs(entry_raw - stop)
        if r <= 0 or (pack.min_R is not None and r < pack.min_R):
            return
        risk_pct = r / entry_raw
        if risk_pct < STOP_MIN:
            return
        if risk_pct > STOP_CAP:
            stop = entry_raw - side * STOP_CAP * entry_raw
            r = abs(entry_raw - stop)
        tgt = target
        if pack.target_R is not None and not np.isfinite(tgt):
            tgt = entry_raw + side * pack.target_R * r
        expiry = _time_expiry_i(ts, i, pack)
        pos = dict(side=side, entry_i=i, entry_raw=float(entry_raw), stop=float(stop),
                   target=float(tgt) if np.isfinite(tgt) else np.nan, R=float(r), expiry_i=expiry)
        pend_l = pend_s = pend_mkt = None

    def maybe_fill_pending(i, pend, side):
        if pend is None:
            return None
        setup_i, level, stop, tgt, expiry = pend
        if i > expiry:
            return None
        if side > 0:
            hit = h[i] >= level
        else:
            hit = l[i] <= level
        if not hit:
            return pend
        fill = _fill_price(level, side > 0, o[i])
        if side > 0 and l[i] <= stop:
            return None
        if side < 0 and h[i] >= stop:
            return None
        open_pos(i, side, fill, stop, tgt)
        return "filled"

    for i in range(n):
        if pos is not None:
            manage(i)
            continue

        if pack.mode == "stop":
            r1 = maybe_fill_pending(i, pend_l, 1)
            if r1 == "filled":
                pend_s = None
                if pos is not None:
                    manage(i)
                continue
            if r1 is None:
                pend_l = None
            r2 = maybe_fill_pending(i, pend_s, -1)
            if r2 == "filled":
                pend_l = None
                if pos is not None:
                    manage(i)
                continue
            if r2 is None:
                pend_s = None

        if pack.mode == "close" and pend_mkt is not None:
            side, stop, tgt = pend_mkt
            pend_mkt = None
            fill = o[i]
            skip = (side > 0 and np.isfinite(stop) and fill <= stop) or (side < 0 and np.isfinite(stop) and fill >= stop)
            if not skip:
                open_pos(i, side, fill, stop, tgt)
                if pos is not None:
                    manage(i)
                    if pos is not None:
                        continue

        if pack.mode == "close":
            if long[i] and not (pack.oco and short[i]):
                pend_mkt = (1, stop_l[i], tgt_l[i])
            elif short[i] and not (pack.oco and long[i]):
                pend_mkt = (-1, stop_s[i], tgt_s[i])
        else:
            if long[i] and np.isfinite(ent_l[i]):
                expiry = _time_expiry_i(ts, i, pack)
                pend_l = (i, float(ent_l[i]), float(stop_l[i]), float(tgt_l[i]) if np.isfinite(tgt_l[i]) else np.nan, expiry)
            if short[i] and np.isfinite(ent_s[i]):
                expiry = _time_expiry_i(ts, i, pack)
                pend_s = (i, float(ent_s[i]), float(stop_s[i]), float(tgt_s[i]) if np.isfinite(tgt_s[i]) else np.nan, expiry)

    if pos is not None:
        close_pos(n - 1, c[-1], "eod")
    return trades


def lift_pack(pack: Pack, last_i: np.ndarray, n_base: int, bar_mult: int, htf_n: int, dyn_1h=None) -> Pack:
    """Map an HTF pack onto the 1h frame: signal lives on the last 1h bar of the HTF bar."""
    li = np.asarray(last_i[:htf_n], dtype=int)
    def bbool(x):
        out = np.zeros(n_base, dtype=bool)
        if x is None: return out
        x = np.asarray(x, dtype=bool)
        m = (li >= 0) & (li < n_base) & (np.arange(len(x)) < len(li))
        idx = np.arange(len(x))[m[:len(x)]]
        out[li[idx]] = x[idx]
        return out
    def bnum(x):
        out = np.full(n_base, np.nan)
        if x is None: return out
        x = np.asarray(x, dtype=float)
        m = (li >= 0) & (li < n_base)
        idx = np.arange(min(len(x), len(li)))
        idx = idx[m[idx]]
        out[li[idx]] = x[idx]
        return out
    ts_bars = pack.time_stop_bars * bar_mult if pack.time_stop_bars is not None else None
    dyn = dyn_1h
    if dyn is None and pack.dynamic_target is not None:
        # expand and ffill so the target is visible on every 1h bar
        dyn = bnum(pack.dynamic_target)
        dyn = pd.Series(dyn).ffill().to_numpy()
    return Pack(long=bbool(pack.long), short=bbool(pack.short), mode=pack.mode,
                stop_long=bnum(pack.stop_long), stop_short=bnum(pack.stop_short),
                target_long=bnum(pack.target_long), target_short=bnum(pack.target_short),
                entry_long=bnum(pack.entry_long), entry_short=bnum(pack.entry_short),
                target_R=pack.target_R, time_stop_bars=ts_bars, time_stop=pack.time_stop,
                oco=pack.oco, dynamic_target=dyn, min_R=pack.min_R)


def scale_pack(pack: Pack, close: np.ndarray, m: float) -> Pack:
    """+-20% robustness: scale stop and target distances from the reference (entry level or close)."""
    def sc(level, ref):
        if level is None: return None
        level = np.asarray(level, dtype=float)
        ref = np.asarray(ref, dtype=float)
        return ref + m * (level - ref)
    ref_l = pack.entry_long if pack.entry_long is not None else close
    ref_s = pack.entry_short if pack.entry_short is not None else close
    tr = pack.target_R * m if pack.target_R is not None else None
    return Pack(long=pack.long, short=pack.short, mode=pack.mode,
                stop_long=sc(pack.stop_long, ref_l), stop_short=sc(pack.stop_short, ref_s),
                target_long=sc(pack.target_long, ref_l), target_short=sc(pack.target_short, ref_s),
                entry_long=pack.entry_long, entry_short=pack.entry_short,
                target_R=tr, time_stop_bars=pack.time_stop_bars, time_stop=pack.time_stop,
                oco=pack.oco, dynamic_target=pack.dynamic_target, min_R=pack.min_R)
# ---------------------------------------------------------------------------
# Rule-card helpers
# ---------------------------------------------------------------------------
def _nan(n):
    return np.full(n, np.nan)

def _false(n):
    return np.zeros(n, dtype=bool)

def _target_from_R(entry, stop, side, R):
    dist = np.abs(entry - stop)
    return entry + side * R * dist

def _close_in_frac(o, h, l, c, lo, hi):
    """True if close is in [lo, hi] of the bar range (e.g. 0.75, 1.0 = top 25%)."""
    rng = np.maximum(h - l, 1e-12)
    frac = (c - l) / rng
    return (frac >= lo) & (frac <= hi)


def build_cards(dfs: dict[str, pd.DataFrame]) -> list[tuple[str, str, str, str, Pack]]:
    """Return a list of (id, group, name, tf, pack).

    Add a new z.ai idea here as a few lines: compute boolean triggers and
    stop/target arrays on the prepared frame, then append a Pack.

    Long/short are exact mirrors unless a card is marked one-way.
    Idea 27 (CVD) is intentionally omitted.
    """
    cards: list[tuple[str, str, str, str, Pack]] = []

    def add(id_, group, name, tf, pack):
        cards.append((id_, group, name, tf, pack))

    def frame(tf) -> pd.DataFrame:
        return dfs[tf]

    # ===== B. Price structure & failed breaks (9-20) =====
    # 9 Break-reclaim fade · 15m
    df = frame("15m")
    n, h, l, c, a = len(df), df.high.to_numpy(), df.low.to_numpy(), df.close.to_numpy(), df.atr.to_numpy()
    pdh, pdl, _ = session_levels(df, "date")
    # bar closes ≤0.25 ATR below the 24h (prior-day) low, NEXT bar closes back above
    broke = c <= (pdl - 0.25 * a)
    long = np.r_[False, (broke[:-1] & (c[1:] > pdl[1:]))]  # pdl of the reclaim bar ≈ same day as break or next
    # use the pdl that was broken: shift pdl with the break
    pdl_at_break = np.r_[np.nan, pdl[:-1]]
    broke_prev = np.r_[False, broke[:-1]]
    long = broke_prev & (c > pdl_at_break)
    wick = np.r_[np.nan, l[:-1]]  # break bar's low
    stop_l = wick - 0.25 * a
    # short mirror: close ≥0.25 ATR above PDH, next close back below
    broke_s = c >= (pdh + 0.25 * a)
    pdh_at_break = np.r_[np.nan, pdh[:-1]]
    short = np.r_[False, broke_s[:-1]] & (c < pdh_at_break)
    wick_s = np.r_[np.nan, h[:-1]]
    stop_s = wick_s + 0.25 * a
    add("B09", "B", "break-reclaim fade", "15m", Pack(
        long=long, short=short, mode="close",
        stop_long=stop_l, stop_short=stop_s, target_R=2, time_stop_bars=16,
    ))

    # 10 Two-step false break · 1h
    df = frame("1h")
    n, o, h, l, c, a = len(df), df.open.to_numpy(), df.high.to_numpy(), df.low.to_numpy(), df.close.to_numpy(), df.atr.to_numpy()
    hi48 = rolling_max(h, 48)
    lo48 = rolling_min(l, 48)
    # previous 48-bar extreme excluding this bar
    prev_hi = np.r_[np.nan, rolling_max(h, 48)[:-1]]
    prev_lo = np.r_[np.nan, rolling_min(l, 48)[:-1]]
    # bar 1: breaks 48-bar high then closes back inside; bar 2 also closes inside
    brk_h = (h > prev_hi) & (c <= prev_hi)
    brk_l = (l < prev_lo) & (c >= prev_lo)
    inside_h = c <= prev_hi
    inside_l = c >= prev_lo
    # second bar also closes inside the ORIGINAL 48-bar high (from bar 1)
    prev_hi_1 = np.r_[np.nan, prev_hi[:-1]]
    prev_lo_1 = np.r_[np.nan, prev_lo[:-1]]
    short = np.r_[False, brk_h[:-1]] & (c <= prev_hi_1)
    long = np.r_[False, brk_l[:-1]] & (c >= prev_lo_1)
    brk_high = np.r_[np.nan, np.where(brk_h, h, np.nan)[:-1]]
    brk_low = np.r_[np.nan, np.where(brk_l, l, np.nan)[:-1]]
    mid_h = 0.5 * (prev_hi_1 + np.r_[np.nan, prev_lo[:-1]])
    mid_l = 0.5 * (prev_lo_1 + np.r_[np.nan, prev_hi[:-1]])
    # mid of the 48-bar range at the breakout bar
    rng_mid = 0.5 * (np.r_[np.nan, prev_hi[:-1]] + np.r_[np.nan, prev_lo[:-1]])
    add("B10", "B", "two-step false break", "1h", Pack(
        long=long, short=short, mode="close",
        stop_long=brk_low - 0.3 * a, stop_short=brk_high + 0.3 * a,
        target_long=rng_mid, target_short=rng_mid, time_stop_bars=24,
    ))

    # 11 Double rejection · 1h
    # Two rejections of the same 48-bar high within 20 bars, 2nd makes a lower high, then close below both rejection lows
    rej = (h > prev_hi) & (c <= prev_hi)
    last_rej_i = np.full(n, -1)
    last_rej_h = _nan(n)
    last_rej_l = _nan(n)
    last_rej_level = _nan(n)
    li = -1
    lh = ll = lv = np.nan
    for i in range(n):
        if rej[i]:
            li, lh, ll, lv = i, h[i], l[i], prev_hi[i]
        last_rej_i[i], last_rej_h[i], last_rej_l[i], last_rej_level[i] = li, lh, ll, lv
    # previous rejection before the most recent one
    prev2_i = np.full(n, -1)
    prev2_h, prev2_l, prev2_lv = _nan(n), _nan(n), _nan(n)
    li = -1
    lh = ll = lv = np.nan
    # walk with a stored previous-previous
    hist = []
    for i in range(n):
        if len(hist) >= 2:
            jh = hist[-2]
            prev2_i[i], prev2_h[i], prev2_l[i], prev2_lv[i] = jh
        if rej[i]:
            hist.append((i, h[i], l[i], prev_hi[i]))
            if len(hist) > 8:
                hist = hist[-8:]
    short = _false(n)
    stop_s = _nan(n)
    tgt_s = _nan(n)
    long = _false(n)
    stop_l = _nan(n)
    tgt_l = _nan(n)
    # short: two rejections of same 48-bar high within 20 bars, 2nd lower high, close below both lows
    for i in range(n):
        if prev2_i[i] < 0 or last_rej_i[i] < 0:
            continue
        if last_rej_i[i] == i:  # just rejected; need close below both lows, may be later
            pass
        # use most recent two rejections
        i2, h2, l2, lv2 = last_rej_i[i], last_rej_h[i], last_rej_l[i], last_rej_level[i]
        i1, h1, l1, lv1 = prev2_i[i], prev2_h[i], prev2_l[i], prev2_lv[i]
        if i2 < 0 or i1 < 0:
            continue
        if i - i2 > 0 and i2 - i1 <= 20 and i - i1 <= 20 + 5:
            if np.isfinite(lv1) and np.isfinite(lv2) and abs(lv1 - lv2) / max(lv1, 1) < 0.002 and h2 < h1 and c[i] < min(l1, l2) and i > i2:
                short[i] = True
                stop_s[i] = max(h1, h2) + 0.3 * a[i]
                tgt_s[i] = prev_lo[i] if np.isfinite(prev_lo[i]) else np.nan
    # long mirror: two rejections of same 48-bar low
    rej_l = (l < prev_lo) & (c >= prev_lo)
    hist = []
    last_i = last_h = last_l = last_lv = None
    prev = []
    store = []
    last_rej = []
    for i in range(n):
        recs = [r for r in last_rej if i - r[0] <= 25]
        if len(recs) >= 2:
            i1, l1, h1, lv1 = recs[-2]
            i2, l2, h2, lv2 = recs[-1]
            if i2 - i1 <= 20 and l2 > l1 and c[i] > max(h1, h2) and i > i2:
                long[i] = True
                stop_l[i] = min(l1, l2) - 0.3 * a[i]
                tgt_l[i] = prev_hi[i]
        if rej_l[i]:
            last_rej.append((i, l[i], h[i], prev_lo[i]))
            if len(last_rej) > 8:
                last_rej = last_rej[-8:]
    # rebuild short similarly with a list (cleaner, overrides earlier)
    short[:] = False
    last_rej_s = []
    for i in range(n):
        recs = [r for r in last_rej_s if i - r[0] <= 25]
        if len(recs) >= 2:
            i1, h1, l1, lv1 = recs[-2]
            i2, h2, l2, lv2 = recs[-1]
            if i2 - i1 <= 20 and h2 < h1 and c[i] < min(l1, l2) and i > i2:
                short[i] = True
                stop_s[i] = max(h1, h2) + 0.3 * a[i]
                tgt_s[i] = prev_lo[i]
        if rej[i]:
            last_rej_s.append((i, h[i], l[i], prev_hi[i]))
            if len(last_rej_s) > 8:
                last_rej_s = last_rej_s[-8:]
    add("B11", "B", "double rejection", "1h", Pack(
        long=long, short=short, mode="close",
        stop_long=stop_l, stop_short=stop_s,
        target_long=tgt_l, target_short=tgt_s, time_stop_bars=32,
    ))

    # 12 Inside-bar chain · 1h · 3 consecutive inside bars → stop-order break of mother high (cancel other side)
    inside = (h <= np.r_[np.nan, h[:-1]]) & (l >= np.r_[np.nan, l[:-1]])
    # three consecutive: i-2,i-1,i all inside
    chain = np.r_[False, False, False, inside[3:] & inside[2:-1] & inside[1:-2]] if n > 3 else _false(n)
    # wait, indices: at bar i (0-based), inside[i] means i is inside i-1.
    # 3 consecutive inside: inside[i-2] & inside[i-1] & inside[i], mother is i-3
    chain = _false(n)
    mother_h, mother_l = _nan(n), _nan(n)
    if n >= 4:
        chain[3:] = inside[1:-2] & inside[2:-1] & inside[3:]
        mother_h[3:] = h[:-3]
        mother_l[3:] = l[:-3]
    height = mother_h - mother_l
    # target 2× mother-bar height, min 1R (R = mother height since stop is the other side)
    # entry at mother high, stop mother low, R = height, target = 2R (= 2× height), already min 1R
    add("B12", "B", "inside-bar chain", "1h", Pack(
        long=chain, short=chain, mode="stop", oco=True,
        entry_long=mother_h, entry_short=mother_l,
        stop_long=mother_l, stop_short=mother_h,
        target_long=mother_h + 2 * height, target_short=mother_l - 2 * height,
        time_stop_bars=12,
    ))

    # 13 Wick-magnet retest · 4h
    df = frame("4h")
    n, h, l, c, a, o = len(df), df.high.to_numpy(), df.low.to_numpy(), df.close.to_numpy(), df.atr.to_numpy(), df.open.to_numpy()
    # prior day's upper/lower wick extremes
    daily = df.groupby("date").agg(hi=("high", "max"), lo=("low", "min"), op=("open", "first"), cl=("close", "last"), atr=("atr", "last"))
    daily["upper_wick"] = daily["hi"] - daily[["op", "cl"]].max(axis=1)
    daily["lower_wick"] = daily[["op", "cl"]].min(axis=1) - daily["lo"]
    daily["prev_hi"] = daily["hi"].shift(1)
    daily["prev_lo"] = daily["lo"].shift(1)
    daily["prev_uw"] = daily["upper_wick"].shift(1)
    daily["prev_lw"] = daily["lower_wick"].shift(1)
    daily["prev_atr"] = daily["atr"].shift(1)
    d_op = df["date"].map(daily["op"]).to_numpy(dtype=float)
    prev_hi = df["date"].map(daily["prev_hi"]).to_numpy(dtype=float)
    prev_lo = df["date"].map(daily["prev_lo"]).to_numpy(dtype=float)
    prev_uw = df["date"].map(daily["prev_uw"]).to_numpy(dtype=float)
    prev_lw = df["date"].map(daily["prev_lw"]).to_numpy(dtype=float)
    prev_atr = df["date"].map(daily["prev_atr"]).to_numpy(dtype=float)
    # prior upper wick ≥1.5 ATR; today's wick touches it and the bar closes back below
    short = (prev_uw >= 1.5 * prev_atr) & (h >= prev_hi) & (c < prev_hi)
    long = (prev_lw >= 1.5 * prev_atr) & (l <= prev_lo) & (c > prev_lo)
    add("B13", "B", "wick-magnet retest", "4h", Pack(
        long=long, short=short, mode="close",
        stop_long=l - 0.3 * a, stop_short=h + 0.3 * a,
        target_long=d_op, target_short=d_op, time_stop_bars=6,  # 1 day on 4h
    ))

    # 14 PDH/PDL sweep · 15m · wick sweeps prior-day low, 15m closes back above; target PDH or 2R, first hit; flat 00:00 UTC
    df = frame("15m")
    n, h, l, c, a = len(df), df.high.to_numpy(), df.low.to_numpy(), df.close.to_numpy(), df.atr.to_numpy()
    pdh, pdl, _ = session_levels(df, "date")
    long = (l < pdl) & (c > pdl)
    short = (h > pdh) & (c < pdh)
    dist_l = np.abs(c - (l - 0.25 * a))
    dist_s = np.abs((h + 0.25 * a) - c)
    tgt_l = np.where(np.isfinite(pdh), np.minimum(pdh, c + 2 * dist_l), c + 2 * dist_l)
    tgt_s = np.where(np.isfinite(pdl), np.maximum(pdl, c - 2 * dist_s), c - 2 * dist_s)
    add("B14", "B", "PDH/PDL sweep", "15m", Pack(
        long=long, short=short, mode="close",
        stop_long=l - 0.25 * a, stop_short=h + 0.25 * a,
        target_long=tgt_l, target_short=tgt_s, time_stop="utc_midnight",
    ))

    # 15 Open drive · 1h · first 1h bar of UTC day engulfs prior bar and closes at its extreme → continuation
    df = frame("1h")
    n, o, h, l, c, a = len(df), df.open.to_numpy(), df.high.to_numpy(), df.low.to_numpy(), df.close.to_numpy(), df.atr.to_numpy()
    first = df["hour"].to_numpy() == 0
    po, ph, pl, pc = np.r_[np.nan, o[:-1]], np.r_[np.nan, h[:-1]], np.r_[np.nan, l[:-1]], np.r_[np.nan, c[:-1]]
    # engulf: this bar's range covers prior bar's range (or body); we require full range engulf
    bull_eng = (l <= pl) & (h >= ph) & (c > o)
    bear_eng = (l <= pl) & (h >= ph) & (c < o)
    top = _close_in_frac(o, h, l, c, 0.75, 1.01)
    bot = _close_in_frac(o, h, l, c, -0.01, 0.25)
    long = first & bull_eng & top
    short = first & bear_eng & bot
    add("B15", "B", "open drive", "1h", Pack(
        long=long, short=short, mode="close",
        stop_long=l, stop_short=h, target_R=2, time_stop_bars=6,
    ))

    # 16 Balance breakout · 4h · 6+ bars fully contained within prior 24h extremes → first close outside the balance edge
    df = frame("4h")
    n, h, l, c, a = len(df), df.high.to_numpy(), df.low.to_numpy(), df.close.to_numpy(), df.atr.to_numpy()
    # prior 24h = previous 6 bars (4h)
    p24h = rolling_max(h, 6)
    p24l = rolling_min(l, 6)
    # for a balance of k=6 bars ending at i-1, those bars must sit inside the 24h range that ended at i-7
    # shift 24h extremes to the start of the 6-bar window
    cap_h = np.r_[[np.nan] * 6, p24h[:-6]]  # 24h extreme as of 6 bars ago
    cap_l = np.r_[[np.nan] * 6, p24l[:-6]]
    win_h = rolling_max(h, 6)
    win_l = rolling_min(l, 6)
    contained = (win_h <= cap_h) & (win_l >= cap_l)  # 6-bar window ending here is inside prior 24h
    # first close outside the balance edge: previous bar was contained, this close outside that window's edge
    bal_h = np.r_[np.nan, win_h[:-1]]
    bal_l = np.r_[np.nan, win_l[:-1]]
    was = np.r_[False, contained[:-1]]
    long = was & (c > bal_h)
    short = was & (c < bal_l)
    height = bal_h - bal_l
    add("B16", "B", "balance breakout", "4h", Pack(
        long=long, short=short, mode="close",
        stop_long=l, stop_short=h,  # beyond breakout bar's extreme
        target_long=c + height, target_short=c - height, time_stop_bars=12,
    ))

    # 17 Descending pressure · 1h · after a 48-bar high: 3 bars each LH/LL, 3rd closes below the 1st's low
    df = frame("1h")
    n, h, l, c, a = len(df), df.high.to_numpy(), df.low.to_numpy(), df.close.to_numpy(), df.atr.to_numpy()
    prev_hi = np.r_[np.nan, rolling_max(h, 48)[:-1]]
    prev_lo = np.r_[np.nan, rolling_min(l, 48)[:-1]]
    # 3-bar pattern ending at i: h[i-2]>h[i-1]>h[i], l[i-2]>l[i-1]>l[i], c[i]<l[i-2], and max of last 48 as of i-3 is a 48-bar high (recent)
    short = _false(n)
    long = _false(n)
    stop_s, stop_l = _nan(n), _nan(n)
    if n >= 4:
        h1, h2, h3 = h[:-3], h[1:-2], h[2:-1]  # wait we need ending at i, so h[i-2],h[i-1],h[i]
        # align to index i (>=2)
        hh0, hh1, hh2 = h[0:-2], h[1:-1], h[2:]
        ll0, ll1, ll2 = l[0:-2], l[1:-1], l[2:]
        cc2 = c[2:]
        after_high = hh0 >= prev_hi[2:]  # first of the 3 is at/after the 48-bar high, or the high is recent
        # "after a 48-bar high": the 48-bar high occurred at or before the first of the 3 bars
        rec = (prev_hi[2:] == rolling_max(h, 48)[2:]) | True
        pat = (hh0 > hh1) & (hh1 > hh2) & (ll0 > ll1) & (ll1 > ll2) & (cc2 < ll0)
        short[2:] = pat
        stop_s[2:] = hh0 + 0.2 * a[2:]
        pat_l = (hh0 < hh1) & (hh1 < hh2) & (ll0 < ll1) & (ll1 < ll2) & (cc2 > hh0)
        long[2:] = pat_l
        stop_l[2:] = ll0 - 0.2 * a[2:]
    add("B17", "B", "descending pressure", "1h", Pack(
        long=long, short=short, mode="close",
        stop_long=stop_l, stop_short=stop_s, target_R=2, time_stop_bars=16,
    ))

    # 18 Prior-week sweep · 4h
    df = frame("4h")
    n, h, l, c, a = len(df), df.high.to_numpy(), df.low.to_numpy(), df.close.to_numpy(), df.atr.to_numpy()
    pwh, pwl, _ = session_levels(df, "week")
    long = (l < pwl) & (c > pwl)
    short = (h > pwh) & (c < pwh)
    add("B18", "B", "prior-week sweep", "4h", Pack(
        long=long, short=short, mode="close",
        stop_long=l - 0.4 * a, stop_short=h + 0.4 * a,
        target_long=pwh, target_short=pwl, time_stop="end_of_week",
    ))

    # 19 Pinch break · 1h · tightest 8-bar average-range window in the last 96 → stop-order break of that window's high
    df = frame("1h")
    n, h, l, c, a = len(df), df.high.to_numpy(), df.low.to_numpy(), df.close.to_numpy(), df.atr.to_numpy()
    rng8 = pd.Series(h - l).rolling(8, min_periods=8).mean().to_numpy()
    # is the window ending here the tightest of windows ending in the last 96 bars?
    tightest = rng8 <= rolling_min(rng8, 96)
    long = short = tightest & np.isfinite(rng8)
    win_h = rolling_max(h, 8)
    win_l = rolling_min(l, 8)
    add("B19", "B", "pinch break", "1h", Pack(
        long=long, short=short, mode="stop", oco=True,
        entry_long=win_h, entry_short=win_l,
        stop_long=win_h + 1 * a,  # 1 ATR beyond break (for a long fill at win_h, stop is below? "1 ATR beyond break level")
        # "1 ATR beyond break level": stop is 1 ATR the other side of the entry? or beyond the break in the fail direction.
        # Beyond the break for a long is below if we got filled on a break of the high? Usually stop is 1 ATR beyond (through) the break, i.e. below entry? 
        # "beyond break" in TTM/contraction cards: stop is 1 ATR beyond the break, meaning if you break up, stop is break - 1 ATR? or the failed-break side?
        # Standard: stop 1 ATR beyond the break level in the opposite direction: long stop = entry - 1 ATR (i.e. 1 ATR beyond/below the break).
        # I'll use: long stop = entry_level - 1 ATR, short stop = entry_level + 1 ATR.
        stop_short=win_l - 1 * a,
        target_R=2, time_stop_bars=10,
    ))
    # fix stop_long: I set stop_long = win_h + 1*a which is WRONG for a long (that's above entry). Correct:
    cards[-1][4].stop_long = win_h - 1 * a
    cards[-1][4].stop_short = win_l + 1 * a

    # 20 Engulf at extreme · 1h · bullish engulfing at the 96-bar low, close in the top 40% of the engulf range
    df = frame("1h")
    n, o, h, l, c, a = len(df), df.open.to_numpy(), df.high.to_numpy(), df.low.to_numpy(), df.close.to_numpy(), df.atr.to_numpy()
    prev_lo = np.r_[np.nan, rolling_min(l, 96)[:-1]]
    prev_hi = np.r_[np.nan, rolling_max(h, 96)[:-1]]
    po, pc = np.r_[np.nan, o[:-1]], np.r_[np.nan, c[:-1]]
    # classic engulfing of prior body
    bull = (c > o) & (pc < po) & (c >= po) & (o <= pc)
    bear = (c < o) & (pc > po) & (c <= po) & (o >= pc)
    top40 = _close_in_frac(o, h, l, c, 0.60, 1.01)
    bot40 = _close_in_frac(o, h, l, c, -0.01, 0.40)
    at_low = l <= prev_lo
    at_high = h >= prev_hi
    long = bull & at_low & top40
    short = bear & at_high & bot40
    add("B20", "B", "engulf at extreme", "1h", Pack(
        long=long, short=short, mode="close",
        stop_long=l - 0.2 * a, stop_short=h + 0.2 * a, target_R=2, time_stop_bars=12,
    ))

    # ===== C. Volume & exhaustion (21-26, 28; skip 27) =====
    # 21 Volume climax fade · 15m
    df = frame("15m")
    n, h, l, c, v, a = len(df), df.high.to_numpy(), df.low.to_numpy(), df.close.to_numpy(), df.volume.to_numpy(), df.atr.to_numpy()
    vsma = _sma(v, 20)
    prev_lo = np.r_[np.nan, rolling_min(l, 96)[:-1]]
    prev_hi = np.r_[np.nan, rolling_max(h, 96)[:-1]]
    climax_v = v >= 3 * vsma
    long = climax_v & _close_in_frac(None, h, l, c, -0.01, 0.25) & (l <= prev_lo)
    short = climax_v & _close_in_frac(None, h, l, c, 0.75, 1.01) & (h >= prev_hi)
    add("C21", "C", "volume climax fade", "15m", Pack(
        long=long, short=short, mode="close",
        stop_long=l - 0.3 * a, stop_short=h + 0.3 * a, target_R=2, time_stop_bars=16,
    ))

    # 22 Dry-up breakout · 1h · rel volume < 0.4 for 6 straight bars → stop-order break of that 6-bar range
    df = frame("1h")
    n, h, l, c, v, a = len(df), df.high.to_numpy(), df.low.to_numpy(), df.close.to_numpy(), df.volume.to_numpy(), df.atr.to_numpy()
    rv = v / np.maximum(_sma(v, 20), 1e-12)
    dry = np.ones(n, dtype=bool)
    for k in range(6):
        dry &= np.r_[[False] * k, rv[k:] < 0.4] if k else (rv < 0.4)
    # simpler:
    dry = pd.Series(rv < 0.4).rolling(6, min_periods=6).min().fillna(0).to_numpy().astype(bool)
    win_h, win_l = rolling_max(h, 6), rolling_min(l, 6)
    add("C22", "C", "dry-up breakout", "1h", Pack(
        long=dry, short=dry, mode="stop", oco=True,
        entry_long=win_h, entry_short=win_l,
        stop_long=win_l, stop_short=win_h,  # opposite side of range
        target_R=2, time_stop_bars=12,
    ))

    # 23 Thin breakout fade · 1h · new 48-bar high on volume < 0.6× SMA20
    df = frame("1h")
    n, h, l, c, v, a = len(df), df.high.to_numpy(), df.low.to_numpy(), df.close.to_numpy(), df.volume.to_numpy(), df.atr.to_numpy()
    vsma = _sma(v, 20)
    prev_hi = np.r_[np.nan, rolling_max(h, 48)[:-1]]
    prev_lo = np.r_[np.nan, rolling_min(l, 48)[:-1]]
    thin = v < 0.6 * vsma
    short = (h > prev_hi) & thin  # fade the thin high (table states this side)
    long = (l < prev_lo) & thin
    mid = 0.5 * (prev_hi + prev_lo)
    add("C23", "C", "thin breakout fade", "1h", Pack(
        long=long, short=short, mode="close",
        stop_long=l - 0.3 * a, stop_short=h + 0.3 * a,
        target_long=mid, target_short=mid, time_stop_bars=16,
    ))

    # 24 Absorption shelf · 15m · 8 bars within 0.5 ATR at the 96-bar high, 8-bar vol sum ≥1.5× normal → break of shelf low
    # Table states the short (fade high). Long is the mirror at the 96-bar low.
    df = frame("15m")
    n, h, l, c, v, a = len(df), df.high.to_numpy(), df.low.to_numpy(), df.close.to_numpy(), df.volume.to_numpy(), df.atr.to_numpy()
    rng8 = rolling_max(h, 8) - rolling_min(l, 8)
    tight = rng8 <= 0.5 * a
    vol8 = pd.Series(v).rolling(8, min_periods=8).sum().to_numpy()
    normal = 8 * _sma(v, 20)
    heavy = vol8 >= 1.5 * normal
    prev_hi = np.r_[np.nan, rolling_max(h, 96)[:-1]]
    prev_lo = np.r_[np.nan, rolling_min(l, 96)[:-1]]
    at_hi = rolling_max(h, 8) >= prev_hi
    at_lo = rolling_min(l, 8) <= prev_lo
    shelf_s = tight & heavy & at_hi
    shelf_l = tight & heavy & at_lo
    sh, sl_ = rolling_max(h, 8), rolling_min(l, 8)
    add("C24", "C", "absorption shelf", "15m", Pack(
        long=shelf_l, short=shelf_s, mode="stop",
        entry_long=sh, entry_short=sl_,  # break of shelf high (long) / shelf low (short)
        stop_long=sl_ - 0.2 * a, stop_short=sh + 0.2 * a,
        target_R=2, time_stop_bars=12,
    ))

    # 25 Momentum exhaustion · 1h · 6 straight closes in one direction, net move ≥3 ATR → fade
    df = frame("1h")
    n, h, l, c, a = len(df), df.high.to_numpy(), df.low.to_numpy(), df.close.to_numpy(), df.atr.to_numpy()
    up = c > np.r_[c[0], c[:-1]]
    dn = c < np.r_[c[0], c[:-1]]
    up6 = pd.Series(up).rolling(6, min_periods=6).min().fillna(0).to_numpy().astype(bool)
    dn6 = pd.Series(dn).rolling(6, min_periods=6).min().fillna(0).to_numpy().astype(bool)
    move = np.abs(c - np.r_[[np.nan] * 6, c[:-6]])
    short = up6 & (move >= 3 * a)  # fade the rally
    long = dn6 & (move >= 3 * a)
    ext_h = rolling_max(h, 6)
    ext_l = rolling_min(l, 6)
    add("C25", "C", "momentum exhaustion", "1h", Pack(
        long=long, short=short, mode="close",
        stop_long=ext_l - 1 * a, stop_short=ext_h + 1 * a, target_R=1.5, time_stop_bars=8,
    ))

    # 26 HVN rejection · 1h · wick touches the close of the highest-volume bar of the last 96 and closes back
    df = frame("1h")
    n, h, l, c, v, a = len(df), df.high.to_numpy(), df.low.to_numpy(), df.close.to_numpy(), df.volume.to_numpy(), df.atr.to_numpy()
    # close of argmax volume in prior 96 bars (exclude current)
    hvn = _nan(n)
    vol = pd.Series(v)
    close_s = pd.Series(c)
    # rolling argmax is slow-ish but n~50k is fine in a python loop
    for i in range(96, n):
        w = v[i - 96:i]
        j = i - 96 + int(np.argmax(w))
        hvn[i] = c[j]
    long = np.isfinite(hvn) & (l <= hvn) & (c > hvn)
    short = np.isfinite(hvn) & (h >= hvn) & (c < hvn)
    add("C26", "C", "HVN rejection", "1h", Pack(
        long=long, short=short, mode="close",
        stop_long=l - 0.3 * a, stop_short=h + 0.3 * a, target_R=2, time_stop_bars=16,
    ))

    # 28 Climax chain · 4h · two consecutive closes ≥80% toward the extreme at a 96-bar extreme, bar-2 vol > bar-1
    df = frame("4h")
    n, h, l, c, v, a = len(df), df.high.to_numpy(), df.low.to_numpy(), df.close.to_numpy(), df.volume.to_numpy(), df.atr.to_numpy()
    top80 = _close_in_frac(None, h, l, c, 0.80, 1.01)
    bot80 = _close_in_frac(None, h, l, c, -0.01, 0.20)
    prev_hi = np.r_[np.nan, rolling_max(h, 96)[:-1]]
    prev_lo = np.r_[np.nan, rolling_min(l, 96)[:-1]]
    short = top80 & np.r_[False, top80[:-1]] & (v > np.r_[np.nan, v[:-1]]) & (h >= prev_hi)
    long = bot80 & np.r_[False, bot80[:-1]] & (v > np.r_[np.nan, v[:-1]]) & (l <= prev_lo)
    add("C28", "C", "climax chain", "4h", Pack(
        long=long, short=short, mode="close",
        stop_long=l - 0.3 * a, stop_short=h + 0.3 * a, target_R=2, time_stop_bars=24,
    ))

    # ===== D. Volatility (29-36) =====
    # 29 NR7 break · 1D
    df = frame("1d")
    n, h, l, c, a = len(df), df.high.to_numpy(), df.low.to_numpy(), df.close.to_numpy(), df.atr.to_numpy()
    tr = true_range(h, l, c)
    nr7 = tr <= rolling_min(tr, 7)
    rng = h - l
    add("D29", "D", "NR7 break", "1d", Pack(
        long=nr7, short=nr7, mode="stop", oco=True,
        entry_long=h, entry_short=l,
        stop_long=l, stop_short=h,
        target_long=h + 2 * rng, target_short=l - 2 * rng,  # 2× NR7 range
        time_stop_bars=3,
    ))

    # 30 TTM squeeze · 1h · BB(20,2) inside KC(20,1.5) for ≥6 bars → stop-order break of the 6-bar extreme
    df = frame("1h")
    n, h, l, c, a = len(df), df.high.to_numpy(), df.low.to_numpy(), df.close.to_numpy(), df.atr.to_numpy()
    bu, bm, bl, _ = bb_width(c, 20, 2)
    ku, km, kl = keltner(h, l, c, 20, 1.5)
    sq = (bu < ku) & (bl > kl)
    sq6 = pd.Series(sq).rolling(6, min_periods=6).min().fillna(0).to_numpy().astype(bool)
    ext_h, ext_l = rolling_max(h, 6), rolling_min(l, 6)
    add("D30", "D", "TTM squeeze", "1h", Pack(
        long=sq6, short=sq6, mode="stop", oco=True,
        entry_long=ext_h, entry_short=ext_l,
        stop_long=ext_h - 1 * a, stop_short=ext_l + 1 * a,
        target_R=2, time_stop_bars=12,
    ))

    # 31 ATR-regime breakout · 1D · daily close beyond 10-day extreme ONLY while ATR14 > ATR50
    df = frame("1d")
    n, h, l, c, a = len(df), df.high.to_numpy(), df.low.to_numpy(), df.close.to_numpy(), df.atr.to_numpy()
    atr50 = atr(h, l, c, 50)
    prev_hi = np.r_[np.nan, rolling_max(h, 10)[:-1]]
    prev_lo = np.r_[np.nan, rolling_min(l, 10)[:-1]]
    hot = a > atr50
    long = hot & (c > prev_hi)
    short = hot & (c < prev_lo)
    add("D31", "D", "ATR-regime breakout", "1d", Pack(
        long=long, short=short, mode="close",
        stop_long=c - 1.5 * a, stop_short=c + 1.5 * a, target_R=2, time_stop_bars=5,
    ))

    # 32 Vol-spike fade · 15m · single bar range ≥2.5 ATR at a 96-bar extreme → fade at close; target midpoint
    df = frame("15m")
    n, h, l, c, a = len(df), df.high.to_numpy(), df.low.to_numpy(), df.close.to_numpy(), df.atr.to_numpy()
    spike = (h - l) >= 2.5 * a
    prev_hi = np.r_[np.nan, rolling_max(h, 96)[:-1]]
    prev_lo = np.r_[np.nan, rolling_min(l, 96)[:-1]]
    mid = 0.5 * (h + l)
    short = spike & (h >= prev_hi)
    long = spike & (l <= prev_lo)
    add("D32", "D", "vol-spike fade", "15m", Pack(
        long=long, short=short, mode="close",
        stop_long=l - 0.2 * a, stop_short=h + 0.2 * a,
        target_long=mid, target_short=mid, time_stop_bars=8,
    ))

    # 33 3-bar contraction · 1h · three bars each narrower than the last → stop-order break of bar-3's range
    df = frame("1h")
    n, h, l, c, a = len(df), df.high.to_numpy(), df.low.to_numpy(), df.close.to_numpy(), df.atr.to_numpy()
    rng = h - l
    # bar-3 is the third (narrowest), i.e. current bar; rng[i] < rng[i-1] < rng[i-2]
    contr = _false(n)
    if n >= 3:
        contr[2:] = (rng[2:] < rng[1:-1]) & (rng[1:-1] < rng[:-2])
    add("D33", "D", "3-bar contraction", "1h", Pack(
        long=contr, short=contr, mode="stop", oco=True,
        entry_long=h, entry_short=l,
        stop_long=h - 1 * a, stop_short=l + 1 * a,
        target_R=2, time_stop_bars=10,
    ))

    # 34 Weekly squeeze · 1D · weekly BB width at a 26-week low → stop-order break of 10-day high / stop 10-day low
    df = frame("1d")
    n, h, l, c, a = len(df), df.high.to_numpy(), df.low.to_numpy(), df.close.to_numpy(), df.atr.to_numpy()
    weekly = df.set_index("ts").resample("W-MON", label="left", closed="left").agg(
        open=("open", "first"), high=("high", "max"), low=("low", "min"), close=("close", "last")
    ).dropna()
    _, _, _, wbw = bb_width(weekly["close"].to_numpy(dtype=float), 20, 2)
    weekly = weekly.copy()
    weekly["bbw"] = wbw
    weekly["bbw_low"] = pd.Series(wbw, index=weekly.index).rolling(26, min_periods=26).min()
    weekly["squeeze"] = weekly["bbw"] <= weekly["bbw_low"]
    # map last completed week flag onto each daily bar (use previous completed weekly bar)
    wflag = weekly["squeeze"].shift(1)  # week that just closed
    # align: for a daily bar on date t, use the weekly row whose period contains t or the previous week?
    # "weekly BB width at a 26-week low" is a state: after a weekly close that is at the low, trade the following days.
    squeeze_state = pd.Series(False, index=df.index)
    if len(weekly):
        flag = weekly["squeeze"].fillna(False)
        for t, val in flag.items():
            if not val:
                continue
            close_t = pd.Timestamp(t)
            if close_t.tzinfo is None:
                close_t = close_t.tz_localize("UTC")
            else:
                close_t = close_t.tz_convert("UTC")
            # W-MON left: row at Monday M covers M..M+7 and is known at M+7; trade the following week.
            trade_from = close_t + pd.Timedelta(days=7)
            trade_to = trade_from + pd.Timedelta(days=7)
            mask = (df["ts"] >= trade_from) & (df["ts"] < trade_to)
            squeeze_state.loc[mask] = True
    sq = squeeze_state.to_numpy()
    d10h = rolling_max(h, 10)
    d10l = rolling_min(l, 10)
    add("D34", "D", "weekly squeeze", "1d", Pack(
        long=sq, short=sq, mode="stop", oco=True,
        entry_long=d10h, entry_short=d10l,
        stop_long=d10l, stop_short=d10h,
        target_R=3, time_stop_bars=7,
    ))

    # 35 ATR-band reversion · 1h · close ≥2.2 ATR from EMA20 → fade toward the EMA; stop entry ±1.2 ATR; target EMA touch
    df = frame("1h")
    n, h, l, c, a = len(df), df.high.to_numpy(), df.low.to_numpy(), df.close.to_numpy(), df.atr.to_numpy()
    e20 = _ema(c, 20)
    short = c >= (e20 + 2.2 * a)
    long = c <= (e20 - 2.2 * a)
    add("D35", "D", "ATR-band reversion", "1h", Pack(
        long=long, short=short, mode="close",
        stop_long=c - 1.2 * a, stop_short=c + 1.2 * a,
        target_long=_nan(n), target_short=_nan(n),
        dynamic_target=e20, time_stop_bars=16,
    ))

    # 36 Big-bar follow-through · 1D · daily range ≥2× ATR20, close in top 25% → next-day stop-order break of that high
    df = frame("1d")
    n, h, l, c, a = len(df), df.high.to_numpy(), df.low.to_numpy(), df.close.to_numpy(), df.atr.to_numpy()
    atr20 = atr(h, l, c, 20)
    big = (h - l) >= 2 * atr20
    top = _close_in_frac(None, h, l, c, 0.75, 1.01)
    bot = _close_in_frac(None, h, l, c, -0.01, 0.25)
    # signal on the big bar; stop-order is next day (engine already waits for later bars)
    long = big & top
    short = big & bot
    # stop: that day's low / high
    add("D36", "D", "big-bar follow-through", "1d", Pack(
        long=long, short=short, mode="stop",
        entry_long=h, entry_short=l,
        stop_long=l, stop_short=h,
        target_R=2, time_stop_bars=2,
    ))

    return cards


# ---------------------------------------------------------------------------
# Pre-declared placebos (one per card): same stops/targets/time-stop, key filter removed or inverted.
# ---------------------------------------------------------------------------
PLACEBO = {
    "B09": "PDH/PDL break itself (no next-bar reclaim)",
    "B10": "first close back inside the 48-bar extreme (no 2nd confirmation bar)",
    "B11": "fade a single rejection of the 48-bar extreme (not two)",
    "B12": "stop-order break of a single inside bar (not a 3-bar chain)",
    "B13": "fade the first close through the 20-bar extreme (no wick-magnet retest)",
    "B14": "fade a 15m close through PDH/PDL (no wick back inside)",
    "B15": "first-hour close at the extreme, no engulf of the prior bar",
    "B16": "close outside the prior 24h extremes (no 6-bar contained balance)",
    "B17": "3-bar LH/LL with 3rd close below the 1st low, not after a 48-bar high",
    "B18": "4h close through PWH/PWL (no reclaim)",
    "B19": "stop-order break of an 8-bar window that is not the tightest in 96",
    "B20": "engulfing with extreme close, not at the 96-bar extreme",
    "C21": "extreme-close fade with mid volume (not a volume climax)",
    "C22": "stop-order break of a 6-bar range when volume is not dry",
    "C23": "fade a 48-bar high/low on volume >= 0.6x SMA20 (not thin)",
    "C24": "break of an 8-bar tight shelf not at the 96-bar extreme",
    "C25": "fade 6 straight closes without a >=3 ATR net move",
    "C26": "wick rejection of a mid-volume bar (not the 96-bar HVN)",
    "C28": "two extreme closes at a 96-bar extreme with bar-2 vol <= bar-1",
    "D29": "stop-order break of a 7-bar extreme when the bar is not NR7",
    "D30": "stop-order break of a 6-bar extreme when BB is not inside Keltner",
    "D31": "10-day extreme close when ATR14 <= ATR50 (not the high-ATR regime)",
    "D32": "fade a 96-bar extreme close whose range is not >= 2.5 ATR",
    "D33": "stop-order break of bar-3 when the 3 bars are not each narrower",
    "D34": "stop-order break of the 10-day high/low in a non-squeeze week",
    "D35": "fade a close 1.0 ATR from EMA20 (not 2.2)",
    "D36": "stop-order break of a top-25% close bar whose range is not >= 2x ATR20",
}


def build_placebo_cards(dfs):
    """Same shape as build_cards, with the key filter of each idea removed or inverted."""
    cards = []
    def add(id_, group, name, tf, pack):
        cards.append((id_, group, name, tf, pack))
    def frame(tf):
        return dfs[tf]

    # B09
    df = frame("15m"); n, h, l, c, a = len(df), df.high.to_numpy(), df.low.to_numpy(), df.close.to_numpy(), df.atr.to_numpy()
    pdh, pdl, _ = session_levels(df, "date")
    long = c <= (pdl - 0.25 * a)
    short = c >= (pdh + 0.25 * a)
    add("B09", "B", "break-reclaim fade", "15m", Pack(long=long, short=short, mode="close",
        stop_long=l - 0.25 * a, stop_short=h + 0.25 * a, target_R=2, time_stop_bars=16))

    # B10
    df = frame("1h"); n, h, l, c, a = len(df), df.high.to_numpy(), df.low.to_numpy(), df.close.to_numpy(), df.atr.to_numpy()
    prev_hi = np.r_[np.nan, rolling_max(h, 48)[:-1]]
    prev_lo = np.r_[np.nan, rolling_min(l, 48)[:-1]]
    short = (h > prev_hi) & (c <= prev_hi)
    long = (l < prev_lo) & (c >= prev_lo)
    rng_mid = 0.5 * (prev_hi + prev_lo)
    add("B10", "B", "two-step false break", "1h", Pack(long=long, short=short, mode="close",
        stop_long=l - 0.3 * a, stop_short=h + 0.3 * a, target_long=rng_mid, target_short=rng_mid, time_stop_bars=24))

    # B11 single rejection
    rej = (h > prev_hi) & (c <= prev_hi)
    rej_l = (l < prev_lo) & (c >= prev_lo)
    short = _false(n); long = _false(n); stop_s = _nan(n); stop_l = _nan(n); tgt_s = _nan(n); tgt_l = _nan(n)
    last = -1; last_h = last_l = np.nan
    for i in range(n):
        if last >= 0 and i > last and c[i] < last_l:
            short[i] = True; stop_s[i] = last_h + 0.3 * a[i]; tgt_s[i] = prev_lo[i]
        if rej[i]:
            last, last_h, last_l = i, h[i], l[i]
    last = -1; last_h = last_l = np.nan
    for i in range(n):
        if last >= 0 and i > last and c[i] > last_h:
            long[i] = True; stop_l[i] = last_l - 0.3 * a[i]; tgt_l[i] = prev_hi[i]
        if rej_l[i]:
            last, last_h, last_l = i, h[i], l[i]
    add("B11", "B", "double rejection", "1h", Pack(long=long, short=short, mode="close",
        stop_long=stop_l, stop_short=stop_s, target_long=tgt_l, target_short=tgt_s, time_stop_bars=24))

    # B12 single inside bar
    df = frame("1h"); n, h, l, c, a = len(df), df.high.to_numpy(), df.low.to_numpy(), df.close.to_numpy(), df.atr.to_numpy()
    inside = np.r_[False, (h[1:] <= h[:-1]) & (l[1:] >= l[:-1])]
    mother_h = np.r_[np.nan, h[:-1]]; mother_l = np.r_[np.nan, l[:-1]]
    add("B12", "B", "inside-bar chain", "1h", Pack(long=inside, short=inside, mode="stop", oco=True,
        entry_long=mother_h, entry_short=mother_l, stop_long=mother_l, stop_short=mother_h, target_R=2, time_stop_bars=12))

    # B13 first close through 20-bar extreme
    df = frame("4h"); n, h, l, c, a = len(df), df.high.to_numpy(), df.low.to_numpy(), df.close.to_numpy(), df.atr.to_numpy()
    prev_hi = np.r_[np.nan, rolling_max(h, 20)[:-1]]; prev_lo = np.r_[np.nan, rolling_min(l, 20)[:-1]]
    short = c > prev_hi; long = c < prev_lo
    add("B13", "B", "wick-magnet retest", "4h", Pack(long=long, short=short, mode="close",
        stop_long=l - 0.25 * a, stop_short=h + 0.25 * a, target_R=2, time_stop_bars=8))

    # B14 close through PDH/PDL
    df = frame("15m"); n, h, l, c, a = len(df), df.high.to_numpy(), df.low.to_numpy(), df.close.to_numpy(), df.atr.to_numpy()
    pdh, pdl, _ = session_levels(df, "date")
    long = c < pdl; short = c > pdh
    mid = 0.5 * (pdh + pdl)
    add("B14", "B", "PDH/PDL sweep", "15m", Pack(long=long, short=short, mode="close",
        stop_long=l - 0.2 * a, stop_short=h + 0.2 * a, target_long=mid, target_short=mid, target_R=2, time_stop="utc_midnight"))

    # B15 first hour extreme close, no engulf
    df = frame("1h"); n, o, h, l, c, a = len(df), df.open.to_numpy(), df.high.to_numpy(), df.low.to_numpy(), df.close.to_numpy(), df.atr.to_numpy()
    first = df["hour"].to_numpy() == 0
    top = _close_in_frac(o, h, l, c, 0.75, 1.01); bot = _close_in_frac(o, h, l, c, -0.01, 0.25)
    add("B15", "B", "open drive", "1h", Pack(long=first & top, short=first & bot, mode="close",
        stop_long=l, stop_short=h, target_R=2, time_stop="utc_midnight"))

    # B16 close outside prior 24h extremes (no balance)
    df = frame("4h"); n, h, l, c, a = len(df), df.high.to_numpy(), df.low.to_numpy(), df.close.to_numpy(), df.atr.to_numpy()
    # 6 * 4h = 24h
    prev_hi = np.r_[np.nan, rolling_max(h, 6)[:-1]]; prev_lo = np.r_[np.nan, rolling_min(l, 6)[:-1]]
    add("B16", "B", "balance breakout", "4h", Pack(long=c > prev_hi, short=c < prev_lo, mode="close",
        stop_long=prev_lo, stop_short=prev_hi, target_R=2, time_stop_bars=12))

    # B17 3-bar LH/LL without 48-bar high context
    df = frame("1h"); n, h, l, c, a = len(df), df.high.to_numpy(), df.low.to_numpy(), df.close.to_numpy(), df.atr.to_numpy()
    short = _false(n); long = _false(n)
    if n >= 3:
        short[2:] = (h[2:] < h[1:-1]) & (h[1:-1] < h[:-2]) & (l[2:] < l[1:-1]) & (l[1:-1] < l[:-2]) & (c[2:] < l[:-2])
        long[2:] = (h[2:] > h[1:-1]) & (h[1:-1] > h[:-2]) & (l[2:] > l[1:-1]) & (l[1:-1] > l[:-2]) & (c[2:] > h[:-2])
    add("B17", "B", "descending pressure", "1h", Pack(long=long, short=short, mode="close",
        stop_long=l - 0.3 * a, stop_short=h + 0.3 * a, target_R=2, time_stop_bars=24))

    # B18 close through PWH/PWL
    df = frame("4h"); n, h, l, c, a = len(df), df.high.to_numpy(), df.low.to_numpy(), df.close.to_numpy(), df.atr.to_numpy()
    pwh, pwl, _ = session_levels(df, "week")
    add("B18", "B", "prior-week sweep", "4h", Pack(long=c < pwl, short=c > pwh, mode="close",
        stop_long=l - 0.25 * a, stop_short=h + 0.25 * a, target_R=2, time_stop="end_of_week"))

    # B19 8-bar window that is NOT the tightest in 96
    df = frame("1h"); n, h, l, c, a = len(df), df.high.to_numpy(), df.low.to_numpy(), df.close.to_numpy(), df.atr.to_numpy()
    rng8 = pd.Series(h - l).rolling(8, min_periods=8).mean().to_numpy()
    tight = pd.Series(rng8).rolling(96, min_periods=96).min().to_numpy()
    not_pinch = np.isfinite(rng8) & np.isfinite(tight) & (rng8 > tight * 1.01)
    win_h = rolling_max(h, 8); win_l = rolling_min(l, 8)
    add("B19", "B", "pinch break", "1h", Pack(long=not_pinch, short=not_pinch, mode="stop", oco=True,
        entry_long=win_h, entry_short=win_l, stop_long=win_h - 1 * a, stop_short=win_l + 1 * a, target_R=2, time_stop_bars=10))

    # B20 engulf not at extreme
    df = frame("1h"); n, o, h, l, c, a = len(df), df.open.to_numpy(), df.high.to_numpy(), df.low.to_numpy(), df.close.to_numpy(), df.atr.to_numpy()
    prev_lo = np.r_[np.nan, rolling_min(l, 96)[:-1]]; prev_hi = np.r_[np.nan, rolling_max(h, 96)[:-1]]
    po, pc = np.r_[np.nan, o[:-1]], np.r_[np.nan, c[:-1]]
    bull = (c > o) & (pc < po) & (c >= po) & (o <= pc)
    bear = (c < o) & (pc > po) & (c <= po) & (o >= pc)
    top40 = _close_in_frac(o, h, l, c, 0.60, 1.01); bot40 = _close_in_frac(o, h, l, c, -0.01, 0.40)
    mid = (l > prev_lo) & (h < prev_hi)
    add("B20", "B", "engulf at extreme", "1h", Pack(long=bull & top40 & mid, short=bear & bot40 & mid, mode="close",
        stop_long=l, stop_short=h, target_R=2, time_stop_bars=24))

    # C21 mid volume
    df = frame("15m"); n, h, l, c, v, a = len(df), df.high.to_numpy(), df.low.to_numpy(), df.close.to_numpy(), df.volume.to_numpy(), df.atr.to_numpy()
    vp = pd.Series(v).rolling(100, min_periods=40).rank(pct=True).to_numpy()
    midv = (vp >= 0.40) & (vp <= 0.60)
    top = _close_in_frac(None, h, l, c, 0.80, 1.01); bot = _close_in_frac(None, h, l, c, -0.01, 0.20)
    add("C21", "C", "volume climax fade", "15m", Pack(long=bot & midv, short=top & midv, mode="close",
        stop_long=l - 0.2 * a, stop_short=h + 0.2 * a, target_R=2, time_stop_bars=16))

    # C22 volume not dry
    df = frame("1h"); n, h, l, c, v, a = len(df), df.high.to_numpy(), df.low.to_numpy(), df.close.to_numpy(), df.volume.to_numpy(), df.atr.to_numpy()
    vma = pd.Series(v).rolling(20, min_periods=10).mean().to_numpy()
    rel = v / np.maximum(vma, 1e-12)
    wet = pd.Series(rel).rolling(6, min_periods=6).min().to_numpy() >= 0.4
    win_h = rolling_max(h, 6); win_l = rolling_min(l, 6)
    add("C22", "C", "dry-up breakout", "1h", Pack(long=wet, short=wet, mode="stop", oco=True,
        entry_long=win_h, entry_short=win_l, stop_long=win_l, stop_short=win_h, target_R=2, time_stop_bars=12))

    # C23 not thin
    df = frame("1h"); n, h, l, c, v, a = len(df), df.high.to_numpy(), df.low.to_numpy(), df.close.to_numpy(), df.volume.to_numpy(), df.atr.to_numpy()
    prev_hi = np.r_[np.nan, rolling_max(h, 48)[:-1]]; prev_lo = np.r_[np.nan, rolling_min(l, 48)[:-1]]
    vsma = pd.Series(v).rolling(20, min_periods=10).mean().to_numpy()
    thick = v >= 0.6 * vsma
    add("C23", "C", "thin breakout fade", "1h", Pack(long=(l < prev_lo) & thick, short=(h > prev_hi) & thick, mode="close",
        stop_long=l - 0.25 * a, stop_short=h + 0.25 * a, target_R=2, time_stop_bars=24))

    # C24 shelf not at extreme
    df = frame("15m"); n, h, l, c, v, a = len(df), df.high.to_numpy(), df.low.to_numpy(), df.close.to_numpy(), df.volume.to_numpy(), df.atr.to_numpy()
    prev_hi = np.r_[np.nan, rolling_max(h, 96)[:-1]]; prev_lo = np.r_[np.nan, rolling_min(l, 96)[:-1]]
    rng8 = pd.Series(h).rolling(8).max().to_numpy() - pd.Series(l).rolling(8).min().to_numpy()
    tight = rng8 <= 0.5 * a
    vsum = pd.Series(v).rolling(8, min_periods=8).sum().to_numpy()
    vnorm = pd.Series(v).rolling(96, min_periods=40).sum().to_numpy() / 12.0
    heavy = vsum >= 1.5 * vnorm
    not_hi = h < prev_hi; not_lo = l > prev_lo
    shelf = tight & heavy
    add("C24", "C", "absorption shelf", "15m", Pack(long=shelf & not_lo, short=shelf & not_hi, mode="stop", oco=False,
        entry_long=rolling_min(l, 8), entry_short=rolling_max(h, 8),
        stop_long=rolling_min(l, 8) - 0.25 * a, stop_short=rolling_max(h, 8) + 0.25 * a,
        target_R=2, time_stop_bars=16))

    # C25 6 closes, no 3 ATR move
    df = frame("1h"); n, h, l, c, a = len(df), df.high.to_numpy(), df.low.to_numpy(), df.close.to_numpy(), df.atr.to_numpy()
    up = np.ones(n, bool); dn = np.ones(n, bool)
    for k in range(1, 6):
        up = up & np.r_[[False]*k, c[k:] > c[:-k]]
        dn = dn & np.r_[[False]*k, c[k:] < c[:-k]]
    # "6 straight closes" ending at i: c[i]>c[i-1]>...  simpler: last 6 diffs same sign
    dlt = np.diff(c, prepend=c[0])
    same_up = pd.Series(dlt > 0).rolling(6).sum().to_numpy() == 6
    same_dn = pd.Series(dlt < 0).rolling(6).sum().to_numpy() == 6
    net = c - np.r_[np.full(6, np.nan), c[:-6]]
    short = same_up & (np.abs(net) < 3 * a)
    long = same_dn & (np.abs(net) < 3 * a)
    add("C25", "C", "momentum exhaustion", "1h", Pack(long=long, short=short, mode="close",
        stop_long=l - 0.3 * a, stop_short=h + 0.3 * a, target_R=2, time_stop_bars=16))

    # C26 mid-volume bar, not HVN
    df = frame("1h"); n, h, l, c, v, a = len(df), df.high.to_numpy(), df.low.to_numpy(), df.close.to_numpy(), df.volume.to_numpy(), df.atr.to_numpy()
    # use the close of the median-volume bar of last 96
    mid_c = _nan(n)
    for i in range(96, n):
        w = v[i-96:i]; j = i-96 + int(np.argsort(w)[len(w)//2])
        mid_c[i] = c[j]
    long = (l <= mid_c) & (c > mid_c)
    short = (h >= mid_c) & (c < mid_c)
    add("C26", "C", "HVN rejection", "1h", Pack(long=long, short=short, mode="close",
        stop_long=l - 0.25 * a, stop_short=h + 0.25 * a, target_R=2, time_stop_bars=16))

    # C28 bar-2 vol <= bar-1
    df = frame("4h"); n, h, l, c, v, a = len(df), df.high.to_numpy(), df.low.to_numpy(), df.close.to_numpy(), df.volume.to_numpy(), df.atr.to_numpy()
    prev_hi = np.r_[np.nan, rolling_max(h, 96)[:-1]]; prev_lo = np.r_[np.nan, rolling_min(l, 96)[:-1]]
    top = _close_in_frac(None, h, l, c, 0.80, 1.01); bot = _close_in_frac(None, h, l, c, -0.01, 0.20)
    at_hi = h >= prev_hi; at_lo = l <= prev_lo
    short = _false(n); long = _false(n)
    if n >= 2:
        short[1:] = top[1:] & top[:-1] & at_hi[1:] & (v[1:] <= v[:-1])
        long[1:] = bot[1:] & bot[:-1] & at_lo[1:] & (v[1:] <= v[:-1])
    add("C28", "C", "climax chain", "4h", Pack(long=long, short=short, mode="close",
        stop_long=l - 0.3 * a, stop_short=h + 0.3 * a, target_R=2, time_stop_bars=8))

    # D29 not NR7
    df = frame("1d"); n, h, l, c, a = len(df), df.high.to_numpy(), df.low.to_numpy(), df.close.to_numpy(), df.atr.to_numpy()
    rng = h - l
    nr7 = rng <= pd.Series(rng).rolling(7, min_periods=7).min().to_numpy()
    win_h = rolling_max(h, 7); win_l = rolling_min(l, 7)
    add("D29", "D", "NR7 break", "1d", Pack(long=~nr7, short=~nr7, mode="stop", oco=True,
        entry_long=win_h, entry_short=win_l, stop_long=win_l, stop_short=win_h, target_R=2, time_stop_bars=7))

    # D30 not in squeeze
    df = frame("1h"); n, h, l, c, a = len(df), df.high.to_numpy(), df.low.to_numpy(), df.close.to_numpy(), df.atr.to_numpy()
    bu, bm, bl, bw = bb_width(c, 20, 2)
    ku, km, kl = keltner(h, l, c, 20, 1.5)
    inside = (bu < ku) & (bl > kl)
    squeezed = pd.Series(inside).rolling(6, min_periods=6).sum().to_numpy() >= 6
    win_h = rolling_max(h, 6); win_l = rolling_min(l, 6)
    add("D30", "D", "TTM squeeze", "1h", Pack(long=~squeezed, short=~squeezed, mode="stop", oco=True,
        entry_long=win_h, entry_short=win_l, stop_long=win_h - 1 * a, stop_short=win_l + 1 * a, target_R=2, time_stop_bars=12))

    # D31 ATR14 <= ATR50
    df = frame("1d"); n, h, l, c = len(df), df.high.to_numpy(), df.low.to_numpy(), df.close.to_numpy()
    a14 = atr(h, l, c, 14); a50 = atr(h, l, c, 50)
    prev_hi = np.r_[np.nan, rolling_max(h, 10)[:-1]]; prev_lo = np.r_[np.nan, rolling_min(l, 10)[:-1]]
    quiet = np.isfinite(a14) & np.isfinite(a50) & (a14 <= a50)
    add("D31", "D", "ATR-regime breakout", "1d", Pack(long=quiet & (c > prev_hi), short=quiet & (c < prev_lo), mode="close",
        stop_long=prev_lo, stop_short=prev_hi, target_R=2, time_stop_bars=10))

    # D32 extreme close, range not 2.5 ATR
    df = frame("15m"); n, h, l, c, a = len(df), df.high.to_numpy(), df.low.to_numpy(), df.close.to_numpy(), df.atr.to_numpy()
    prev_hi = np.r_[np.nan, rolling_max(h, 96)[:-1]]; prev_lo = np.r_[np.nan, rolling_min(l, 96)[:-1]]
    small = (h - l) < 2.5 * a
    mid = 0.5 * (prev_hi + prev_lo)
    add("D32", "D", "vol-spike fade", "15m", Pack(long=small & (l <= prev_lo), short=small & (h >= prev_hi), mode="close",
        stop_long=l - 0.25 * a, stop_short=h + 0.25 * a, target_long=mid, target_short=mid, time_stop_bars=16))

    # D33 not contracting
    df = frame("1h"); n, h, l, c, a = len(df), df.high.to_numpy(), df.low.to_numpy(), df.close.to_numpy(), df.atr.to_numpy()
    rng = h - l
    not_contr = _false(n)
    if n >= 3:
        not_contr[2:] = ~((rng[2:] < rng[1:-1]) & (rng[1:-1] < rng[:-2]))
    add("D33", "D", "3-bar contraction", "1h", Pack(long=not_contr, short=not_contr, mode="stop", oco=True,
        entry_long=h, entry_short=l, stop_long=h - 1 * a, stop_short=l + 1 * a, target_R=2, time_stop_bars=10))

    # D34 non-squeeze week (reuse D34 weekly machinery, invert flag)
    df = frame("1d"); n, h, l, c, a = len(df), df.high.to_numpy(), df.low.to_numpy(), df.close.to_numpy(), df.atr.to_numpy()
    weekly = df.set_index("ts").resample("W-MON", label="left", closed="left").agg(
        open=("open", "first"), high=("high", "max"), low=("low", "min"), close=("close", "last")
    ).dropna()
    _, _, _, wbw = bb_width(weekly["close"].to_numpy(dtype=float), 20, 2)
    weekly = weekly.copy()
    weekly["bbw"] = wbw
    weekly["bbw_low"] = pd.Series(wbw, index=weekly.index).rolling(26, min_periods=26).min()
    weekly["squeeze"] = weekly["bbw"] <= weekly["bbw_low"]
    squeeze_state = pd.Series(False, index=df.index)
    if len(weekly):
        flag = weekly["squeeze"].fillna(False)
        for t, val in flag.items():
            if not val:
                continue
            close_t = pd.Timestamp(t)
            close_t = close_t.tz_localize("UTC") if close_t.tzinfo is None else close_t.tz_convert("UTC")
            trade_from = close_t + pd.Timedelta(days=7)
            trade_to = trade_from + pd.Timedelta(days=7)
            mask = (df["ts"] >= trade_from) & (df["ts"] < trade_to)
            squeeze_state.loc[mask] = True
    sq = squeeze_state.to_numpy()
    d10h = rolling_max(h, 10); d10l = rolling_min(l, 10)
    add("D34", "D", "weekly squeeze", "1d", Pack(long=~sq, short=~sq, mode="stop", oco=True,
        entry_long=d10h, entry_short=d10l, stop_long=d10l, stop_short=d10h, target_R=3, time_stop_bars=7))

    # D35 1.0 ATR from EMA20
    df = frame("1h"); n, h, l, c, a = len(df), df.high.to_numpy(), df.low.to_numpy(), df.close.to_numpy(), df.atr.to_numpy()
    e20 = _ema(c, 20)
    add("D35", "D", "ATR-band reversion", "1h", Pack(
        long=c <= (e20 - 1.0 * a), short=c >= (e20 + 1.0 * a), mode="close",
        stop_long=c - 1.2 * a, stop_short=c + 1.2 * a, target_long=_nan(n), target_short=_nan(n),
        dynamic_target=e20, time_stop_bars=16))

    # D36 not a big bar
    df = frame("1d"); n, h, l, c, a = len(df), df.high.to_numpy(), df.low.to_numpy(), df.close.to_numpy(), df.atr.to_numpy()
    atr20 = atr(h, l, c, 20)
    small = (h - l) < 2 * atr20
    top = _close_in_frac(None, h, l, c, 0.75, 1.01); bot = _close_in_frac(None, h, l, c, -0.01, 0.25)
    add("D36", "D", "big-bar follow-through", "1d", Pack(long=small & top, short=small & bot, mode="stop",
        entry_long=h, entry_short=l, stop_long=l, stop_short=h, target_R=2, time_stop_bars=2))

    return cards


# ---------------------------------------------------------------------------
# K8 baseline (same simplification as specialists_batch6) for daily-return correlation
# ---------------------------------------------------------------------------
def set_asset(d):
    global df, N, O, Hh, L, C, V, T, BAR, BPD
    df = d.reset_index(drop=True); N = len(df); BAR = H1; BPD = 24
    O, Hh, L, C, V = (df[k].values.astype("float64") for k in ("open", "high", "low", "close", "volume"))
    T = df["time"].values.astype("int64")

def resample(period):
    g = T // period
    r = pd.DataFrame({"g": g, "open": O, "high": Hh, "low": L, "close": C, "volume": V})
    a = r.groupby("g").agg(open=("open", "first"), high=("high", "max"), low=("low", "min"), close=("close", "last"), volume=("volume", "sum"))
    a["last_i"] = pd.Series(np.arange(N)).groupby(g).max().values
    a["time"] = a.index.values * period
    return a.reset_index()

def to_base(htf, values, period):
    last_closed_g = (T + BAR) // period - 1
    return pd.Series(np.asarray(values, dtype="float64"), index=htf["g"].values).reindex(last_closed_g).values

def wilder(x, n):
    return pd.Series(x).ewm(alpha=1.0 / n, adjust=False).mean().values

def adx(h, l, c, n=14):
    up = np.r_[0, np.diff(h)]; dn = np.r_[0, -np.diff(l)]
    pdm = np.where((up > dn) & (up > 0), up, 0.0); mdm = np.where((dn > up) & (dn > 0), dn, 0.0)
    a = atr(h, l, c, n)
    pdi = 100 * wilder(pdm, n) / a; mdi = 100 * wilder(mdm, n) / a
    dx = 100 * np.abs(pdi - mdi) / np.maximum(pdi + mdi, 1e-12)
    return wilder(dx, n), pdi, mdi

STOP_RULE = None

def run(name, sig, stop_dist, tp_dist=None, max_hold=None, chand_atr=None, chand_mult=None,
        exitL=None, exitS=None, hardL=None, hardS=None, holdL=None, holdS=None, flip=True,
        trail_start=None, trail_drop=None, allow=None):
    eq = 1.0; pos = 0; frac = 0.0; ent = 0.0; stp = np.nan; tp = np.nan; ebar = 0; ext = 0.0; best = 0.0
    eq_ent = 1.0; t_in = 0; i_in = 0
    pend = 0; pend_stop = np.nan; pend_tp = np.nan; pend_exit = False
    curve = np.empty(N); trades = []
    def close_at(px, i):
        nonlocal eq, pos
        eq = eq_ent * (1 + frac * (pos * (px / ent - 1) - 2 * COST))
        trades.append((t_in, T[i], pos, eq / eq_ent - 1, i_in, pos * (px / ent - 1), rp)); pos = 0
    for i in range(N):
        o, h, l, c = O[i], Hh[i], L[i], C[i]
        if pos != 0 and pend_exit: close_at(o, i)
        pend_exit = False
        if STOP_RULE is not None and pend != 0 and pos == 0 and np.isfinite(pend_stop) and pend_stop / o > STOP_RULE[1]:
            if STOP_RULE[0] == "skip": pend = 0
            else: pend_stop = STOP_RULE[1] * o
        if pend != 0 and pos == 0 and np.isfinite(pend_stop) and pend_stop > 0:
            pos = pend; ent = o; rp = pend_stop / o; frac = min(MAX_NOTIONAL, RISK / rp)
            stp = o - pos * pend_stop; tp = o + pos * pend_tp if np.isfinite(pend_tp) else np.nan
            eq_ent = eq; t_in = T[i]; i_in = i; ebar = i; ext = o; best = o
        pend = 0
        if pos != 0:
            hit = None
            if pos > 0:
                if l <= stp: hit = min(o, stp)
                elif np.isfinite(tp) and h >= tp: hit = max(o, tp)
            else:
                if h >= stp: hit = max(o, stp)
                elif np.isfinite(tp) and l <= tp: hit = min(o, tp)
            if hit is not None: close_at(hit, i)
        s = sig[i]; ok = (allow is None) or bool(allow[i])
        if pos != 0:
            curve[i] = eq_ent * (1 + frac * (pos * (c / ent - 1) - COST))
            ext = max(ext, h) if pos > 0 else min(ext, l)
            if chand_atr is not None and np.isfinite(chand_atr[i]):
                ns = ext - pos * chand_mult * chand_atr[i]
                stp = max(stp, ns) if pos > 0 else min(stp, ns)
            best = max(best, c) if pos > 0 else min(best, c)
            hold = (pos > 0 and holdL is not None and bool(holdL[i])) or (pos < 0 and holdS is not None and bool(holdS[i]))
            soft = (pos > 0 and exitL is not None and bool(exitL[i])) or (pos < 0 and exitS is not None and bool(exitS[i]))
            soft |= (flip and s == -pos)
            hard = (max_hold is not None and i - ebar >= max_hold)
            hard |= (pos > 0 and hardL is not None and bool(hardL[i])) or (pos < 0 and hardS is not None and bool(hardS[i]))
            if trail_start is not None and pos * (best / ent - 1) >= trail_start and abs(best - c) / best >= trail_drop \
                    and pos * (c - best) < 0:
                hard = True
            ex = hard or (soft and not hold)
            if ex and flip and s == -pos and ok:
                pend = s; pend_stop = stop_dist[i]; pend_tp = tp_dist[i] if tp_dist is not None else np.nan
            pend_exit = ex
        else:
            curve[i] = eq
            if s != 0 and ok:
                pend = int(s); pend_stop = stop_dist[i] if np.ndim(stop_dist) else stop_dist
                pend_tp = tp_dist[i] if tp_dist is not None else np.nan
    if pos != 0:
        close_at(C[-1], N - 1); curve[-1] = eq
    return {"name": name, "curve": curve, "trades": pd.DataFrame(trades, columns=["t_in", "t_out", "side", "ret", "i_in", "move", "risk"])}

def daily_ret(res):
    cv = pd.Series(res["curve"], index=T // D1)
    d = cv.groupby(level=0).last()
    return d.pct_change().fillna(0.0)

def k8_system(D):
    lp = np.log(C); g12 = T // H12; last_of_g = np.r_[g12[1:] != g12[:-1], True]
    q = 1e-4; lv, sl = lp[0], 0.0; p00, p01, p11 = 1e-2, 0.0, 1e-2
    innov = []; Rv = 1e-3; slope_tmp = np.zeros(N)
    for i in range(N):
        lv_p = lv + sl; sl_p = sl
        a00 = p00 + 2 * p01 + p11 + q; a01 = p01 + p11; a11 = p11 + q
        S = a00 + Rv; v = lp[i] - lv_p; lim = 3 * math.sqrt(S); vc = max(-lim, min(lim, v))
        k0 = a00 / S; k1 = a01 / S
        n_lv = lv_p + k0 * vc; n_sl = sl_p + k1 * vc; slope_tmp[i] = n_sl
        if last_of_g[i]:
            lv, sl = n_lv, n_sl; p00, p01, p11 = (1 - k0) * a00, (1 - k0) * a01, a11 - k1 * a01
            innov.append(v * v)
            if len(innov) > 100: innov.pop(0)
            if len(innov) >= 10: Rv = max(float(np.mean(innov)), 1e-8)
    sgn = np.sign(slope_tmp)
    same8 = pd.Series(sgn).rolling(8).apply(lambda x: x[0] if np.all(x == x[0]) else 0, raw=True).fillna(0).values
    k8dir = pd.Series(np.where(same8 != 0, same8, np.nan)).ffill().fillna(0).values
    chg = np.r_[False, k8dir[1:] != k8dir[:-1]] & (k8dir != 0)
    k8sig = np.zeros(N, "int8"); k8sig[chg] = k8dir[chg].astype("int8")
    H12B = resample(H12); atr12 = to_base(H12B, atr(H12B.high.values, H12B.low.values, H12B.close.values, 14), H12)
    dadx, dpdi, dmdi = adx(D.high.values, D.low.values, D.close.values, 14)
    b_adx, b_pdi, b_mdi = (to_base(D, x, D1) for x in (dadx, dpdi, dmdi))
    blkL = (b_adx > 25) & (b_mdi > b_pdi); blkS = (b_adx > 25) & (b_pdi > b_mdi)
    return dict(dir=k8dir, sig=k8sig, chg=chg, stop=np.fmin(6 * atr12, 0.07 * C), blkL=blkL, blkS=blkS)

def k8_allow(K, sig):
    return ~((sig > 0) & K["blkL"]) & ~((sig < 0) & K["blkS"])

def k8_daily(d_norm):
    set_asset(d_norm)
    D = resample(D1)
    k8 = k8_system(D)
    res = run("K8", k8["sig"], k8["stop"], exitL=k8["dir"] < 0, exitS=k8["dir"] > 0, allow=k8_allow(k8, k8["sig"]))
    return daily_ret(res)


# ---------------------------------------------------------------------------
# Trade stats / compact table (1% risk compounded)
# ---------------------------------------------------------------------------
def fmt(x, nd=1):
    return "-" if x is None or (isinstance(x, float) and not np.isfinite(x)) else f"{x:.{nd}f}"

def _tframe(trades):
    if not trades:
        return pd.DataFrame(columns=["side", "entry_ts", "exit_ts", "net_R", "entry_px", "R"])
    return pd.DataFrame([{
        "side": t.side, "entry_ts": _ts_utc(t.entry_ts), "exit_ts": _ts_utc(t.exit_ts),
        "net_R": t.net_R, "entry_px": t.entry_px, "R": t.R,
    } for t in trades])

def _window(tf, start, end=None):
    if tf is None or len(tf) == 0:
        return tf
    s = pd.Timestamp(start, tz="UTC")
    e = pd.Timestamp(end, tz="UTC") if end else pd.Timestamp("2100-01-01", tz="UTC")
    return tf[(tf["exit_ts"] >= s) & (tf["exit_ts"] < e)]

def tstats(tf):
    if tf is None or len(tf) == 0:
        return dict(tr=0, win=np.nan, pf=np.nan, ret=np.nan, dd=np.nan, avgR=np.nan)
    r = tf["net_R"].astype(float).to_numpy()
    g = r[r > 0].sum(); ls = -r[r < 0].sum()
    pf = (g / ls) if ls > 0 else (np.inf if g > 0 else np.nan)
    # 1% risk, never hits 1x cap after skip<1.5%
    eq = np.cumprod(1.0 + RISK * r)
    eq = np.r_[1.0, eq]
    peak = np.maximum.accumulate(eq)
    dd = 100 * ((eq / peak) - 1).min()
    return dict(tr=int(len(tf)), win=100 * float((r > 0).mean()), pf=float(pf) if np.isfinite(pf) else pf,
                ret=100 * float(eq[-1] - 1), dd=float(dd), avgR=float(np.nanmean(r)))

def daily_from_trades(trades, start=HEADLINE_START):
    tf = _window(_tframe(trades), start)
    if tf is None or len(tf) == 0:
        return pd.Series(dtype=float)
    day = tf.set_index("exit_ts")["net_R"].groupby(lambda x: pd.Timestamp(x).floor("D")).sum()
    # convert net_R-sum to equity daily return: 1% * R
    ret = (RISK * day).rename("ret")
    ret.index = pd.to_datetime(ret.index, utc=True)
    return ret

def idea_row(id_, name, tf, trades, p_trades, k8d):
    tdf = _tframe(trades)
    h = tstats(_window(tdf, HEADLINE_START))
    years = max(0.25, (pd.Timestamp("now", tz="UTC") - pd.Timestamp(HEADLINE_START, tz="UTC")).days / 365.25)
    # tighten years to data span if trades exist
    tw = _window(tdf, HEADLINE_START)
    if tw is not None and len(tw):
        years = max(0.25, (tw["exit_ts"].max() - pd.Timestamp(HEADLINE_START, tz="UTC")).days / 365.25)
    row = {"idea": f"{id_} {name}", "tf": tf, "trades": h["tr"], "tr/yr": round(h["tr"] / years, 1) if h["tr"] else 0,
           "win%": fmt(h["win"], 0), "PF": fmt(h["pf"], 2), "ret%": fmt(h["ret"]), "maxDD%": fmt(h["dd"]),
           "MAR": fmt(h["ret"] / abs(h["dd"]) if h["tr"] and np.isfinite(h["dd"]) and h["dd"] < 0 else np.nan, 2),
           "avgR": fmt(h["avgR"], 2)}
    for b, a_, z in BUCKETS:
        q = tstats(_window(tdf, a_, z)); row[b] = f"{fmt(q['ret'])}/{fmt(q['pf'],2)}/{q['tr']}"
    ph = tstats(_window(_tframe(p_trades), HEADLINE_START))
    row["placebo PF/ret"] = f"{fmt(ph['pf'],2)}/{fmt(ph['ret'])} ({ph['tr']})"
    d = daily_from_trades(trades, HEADLINE_START)
    ck = np.nan
    if k8d is not None and len(d):
        # k8d index is epoch days (T//D1); convert
        k = k8d.copy()
        if not isinstance(k.index, pd.DatetimeIndex):
            k.index = pd.to_datetime(k.index.values * D1, unit="ms", utc=True).floor("D")
        else:
            k.index = pd.to_datetime(k.index, utc=True).floor("D")
        aligned = d.reindex(k.index).fillna(0)
        kk = k.reindex(aligned.index).fillna(0)
        if aligned.std() > 0 and kk.std() > 0:
            ck = float(aligned.corr(kk))
    row["corrK8"] = fmt(ck, 2)
    row["_pf"] = h["pf"]; row["_n"] = h["tr"]; row["_ppf"] = ph["pf"]; row["_pret"] = ph["ret"]; row["_ck"] = ck
    row["_b1"] = tstats(_window(tdf, "2017-01-01", "2021-01-01"))["ret"]
    row["_b2"] = tstats(_window(tdf, "2021-01-01"))["ret"]
    row["_id"] = id_; row["_name"] = name; row["_tf"] = tf
    return row

def show(rows, title):
    print(f"\n=== {title} — 2017+ headline | blocks = ret%/PF/trades ===")
    t = pd.DataFrame(rows)
    if not len(t):
        print("(no rows)"); return
    cols = [k for k in t.columns if not k.startswith("_")]
    with pd.option_context("display.max_colwidth", 44):
        print(t[cols].to_string(index=False))


def resolve_pack(pack, tf, dfs_1h, n_1h, last_i_map):
    """Lift 4h/1d packs onto the 1h frame. 15m and 1h stay native."""
    if tf == "15m":
        return pack, dfs_1h.get("15m")  # caller passes 15m as run frame
    if tf == "1h":
        return pack, dfs_1h["1h"]
    last_i = last_i_map[tf]
    bar_mult = 4 if tf == "4h" else 24
    lifted = lift_pack(pack, last_i, n_1h, bar_mult, len(pack.long))
    return lifted, dfs_1h["1h"]


def build_tf_frames(d_1h, d_15m=None):
    """d_1h is the normalized 1h asset frame."""
    h1 = prepared_from_1h(d_1h)
    out = {"1h": h1, "4h": resample_prepared(d_1h, H4), "1d": resample_prepared(d_1h, D1)}
    if d_15m is not None and len(d_15m) > 200:
        out["15m"] = prepared_from_15m(d_15m)
    return out


def dummy_15m():
    """Tiny dummy so build_cards can construct 15m packs when data is missing. Not used for trading."""
    n = 4000
    ts = pd.date_range("2017-08-01", periods=n, freq="15min", tz="UTC")
    px = 1000 + np.cumsum(np.zeros(n))
    d = pd.DataFrame({"ts": ts, "open": px, "high": px + 1, "low": px - 1, "close": px, "volume": 1.0})
    return prepare(d)


def run_asset(label, d_1h, d_15m, k8d, have_15m):
    t_a = time.time()
    frames = build_tf_frames(d_1h, d_15m if have_15m else None)
    if "15m" not in frames:
        frames["15m"] = dummy_15m()
        have_15m = False
    real = build_cards(frames)
    plac = {c[0]: c for c in build_placebo_cards(frames)}
    last_i_map = {"4h": frames["4h"]["last_i"].to_numpy(), "1d": frames["1d"]["last_i"].to_numpy()}
    n_1h = len(frames["1h"])
    rows = []; packs = {}; run_frames = {}; p_trades = {}; r_trades = {}
    for id_, group, name, tf, pack in real:
        if tf == "15m" and not have_15m:
            rows.append({**idea_row(id_, name, tf, [], [], k8d), "note": "no 15m data"})
            continue
        run_pack, run_df = resolve_pack(pack, tf, {**frames, "15m": frames["15m"]}, n_1h, last_i_map)
        if tf == "15m":
            run_df = frames["15m"]
        tr = backtest_card(run_df, run_pack, id_)
        pp = plac[id_][4]
        p_pack, p_df = resolve_pack(pp, tf, {**frames, "15m": frames["15m"]}, n_1h, last_i_map)
        if tf == "15m":
            p_df = frames["15m"]
        ptr = backtest_card(p_df, p_pack, id_ + "_p")
        rows.append(idea_row(id_, name, tf, tr, ptr, k8d))
        packs[id_] = (run_pack, run_df, name, tf)
        r_trades[id_] = tr; p_trades[id_] = ptr
    print(f"({label}: {len(real)} cards simulated in {time.time()-t_a:.0f}s)")
    return dict(rows=rows, packs=packs, r_trades=r_trades, p_trades=p_trades, frames=frames)


def synthetic_ohlcv(tf, n, seed, start="2017-01-01"):
    rng = np.random.default_rng(seed)
    freq = {"15m": "15min", "1h": "1h", "4h": "4h", "1d": "1D"}[tf]
    ts = pd.date_range(start, periods=n, freq=freq, tz="UTC")
    ret = rng.normal(0, 0.004, n)
    close = 1000 * np.exp(np.cumsum(ret))
    high = close * (1 + np.abs(rng.normal(0, 0.002, n)))
    low = close * (1 - np.abs(rng.normal(0, 0.002, n)))
    open_ = np.r_[close[0], close[:-1]]
    high = np.maximum.reduce([high, open_, close])
    low = np.minimum.reduce([low, open_, close])
    vol = rng.uniform(100, 1000, n)
    # plant a few textbook patterns so most cards can fire
    for i in range(80, n - 40, max(40, n // 12)):
        high[i] = max(high[i], close[i] * 1.02); low[i] = min(low[i], close[i] * 0.98)
        vol[i] = vol[i] * 8
    return prepare(pd.DataFrame({"ts": ts, "open": open_, "high": high, "low": low, "close": close, "volume": vol}))


def run_smoke():
    print("SMOKE: synthetic 15m/1h/4h/1d, no real data")
    dfs = {
        "15m": synthetic_ohlcv("15m", 4000, 1),
        "1h": synthetic_ohlcv("1h", 3000, 2),
        "4h": synthetic_ohlcv("4h", 2000, 3),
        "1d": synthetic_ohlcv("1d", 1500, 4),
    }
    real = build_cards(dfs)
    plac = build_placebo_cards(dfs)
    print(f"  built {len(real)} real cards, {len(plac)} placebos")
    assert len(real) == 27 and len(plac) == 27, (len(real), len(plac))
    ids_r = [c[0] for c in real]; ids_p = [c[0] for c in plac]
    assert ids_r == ids_p, (ids_r, ids_p)
    nfire = 0
    for id_, group, name, tf, pack in real:
        tr = backtest_card(dfs[tf], pack, id_)
        print(f"  {id_} {tf} {name}: {len(tr)} trades")
        nfire += len(tr) > 0
    print(f"SMOKE OK: {len(real)} cards, {nfire} fired at least one trade, {time.time()-T0:.1f}s")


# ---------------------------------------------------------------------------
# LOAD + RUN
# ---------------------------------------------------------------------------
if "--smoke" in sys.argv or os.environ.get("ZAI_BATCH7_SMOKE") == "1":
    run_smoke()
    raise SystemExit(0)

btc, SRC = load_asset("btc")
if btc is None or _bar_ms(btc) > H1:
    raise SystemExit("Batch 7 needs BTC 1h data (hosted btc_1h_full.csv.gz).")
print(f"BTC DATA: {SRC} | {len(btc):,} rows")
print("Computing K8 baseline on BTC 1h ...", flush=True)
K8D = k8_daily(btc)
print(f"  K8 daily returns: {len(K8D):,}")

print("Loading BTC 15m (hosted, for 5 cards) ...", flush=True)
btc15, SRC15 = load_15m("btc")
have15_btc = btc15 is not None and len(btc15) > 2000
if have15_btc:
    print(f"BTC 15m: {SRC15} | {len(btc15):,} rows")
else:
    print("  WARNING: no BTC 15m — B09/B14/C21/C24/D32 will be skipped")

AB = run_asset("BTC", btc, btc15, K8D, have15_btc)
BR = AB["rows"]

ER = []; AE = None
eth, ESRC = load_asset("eth")
if eth is not None and _bar_ms(eth) <= H1:
    eth = fix_eth_bar(eth)
    print(f"ETH DATA: {ESRC} | {len(eth):,} rows")
    print("Computing K8 baseline on ETH 1h ...", flush=True)
    K8E = k8_daily(eth)
    print("Loading ETH 15m (hosted, for 5 cards) ...", flush=True)
    eth15, ESRC15 = load_15m("eth")
    have15_eth = eth15 is not None and len(eth15) > 2000
    if have15_eth:
        print(f"ETH 15m: {ESRC15} | {len(eth15):,} rows")
    else:
        print("  WARNING: no ETH 15m — 15m cards will fail the ETH PF test")
    AE = run_asset("ETH", eth, eth15, K8E, have15_eth)
    ER = AE["rows"]
else:
    print("ETH 1h not available — ETH PF test will fail")

show(BR, "BTC")
if ER: show(ER, "ETH")
print("\nPlacebos:", "; ".join(f"{k} = {v}" for k, v in PLACEBO.items()))

# ---------------------------------------------------------------------------
# VERDICTS
# ---------------------------------------------------------------------------
eth_pf = {r["idea"]: r.get("_pf", np.nan) for r in ER}
VR = []
for r in BR:
    nm = r["idea"]; fails = []
    if r.get("_n", 0) == 0:
        VR.append({"idea": nm, "verdict": "DROP", "fails": r.get("note", "no trades"), "BTC n": 0,
                   "BTC PF": "-", "BTC ret%": "-", "BTC DD%": "-", "ETH PF": fmt(eth_pf.get(nm, np.nan), 2),
                   "placebo PF": "-", "corrK8": "-", "_pf": 0}); continue
    pf, n, ppf, ck = r["_pf"], r["_n"], r["_ppf"], r["_ck"]
    if not (np.isfinite(pf) and pf >= 1.3 and n >= 30): fails.append(f"PF {fmt(pf,2)} / n {n}")
    if not (np.isfinite(ppf) and np.isfinite(pf) and pf - ppf >= 0.3): fails.append(f"placebo {fmt(ppf,2)}")
    if not (np.isfinite(r["_b1"]) and np.isfinite(r["_b2"]) and r["_b1"] > 0 and r["_b2"] > 0):
        fails.append(f"2017-20/2021+ {fmt(r['_b1'])}/{fmt(r['_b2'])}")
    e = eth_pf.get(nm, np.nan)
    if not (np.isfinite(e) and e >= 1.1): fails.append(f"ETH PF {fmt(e,2)}")
    if not (np.isfinite(ck) and ck < 0.3): fails.append(f"corrK8 {fmt(ck,2)}")
    v = "KEEP" if not fails else ("WATCH" if len(fails) == 1 else "DROP")
    VR.append({"idea": nm, "verdict": v, "fails": "; ".join(fails) or "-", "BTC n": n, "BTC PF": fmt(pf, 2),
               "BTC ret%": r["ret%"], "BTC DD%": r["maxDD%"], "ETH PF": fmt(e, 2), "placebo PF": fmt(ppf, 2),
               "corrK8": r["corrK8"], "_pf": pf if np.isfinite(pf) else 0})
VT = pd.DataFrame(VR); VT["_o"] = VT.verdict.map({"KEEP": 0, "WATCH": 1, "DROP": 2}); VT["_pf"] = VT["_pf"].fillna(0)
VT = VT.sort_values(["_o", "_pf"], ascending=[True, False])

ROB = []
for nm in VT[VT.verdict == "KEEP"].idea:
    cid = nm.split(" ")[0]
    if cid not in AB["packs"]:
        continue
    pack, run_df, name, tf = AB["packs"][cid]
    row = {"idea": nm}
    for m in (0.8, 1.2):
        sp = scale_pack(pack, run_df["close"].to_numpy(), m)
        st = tstats(_window(_tframe(backtest_card(run_df, sp, cid + f"_x{m}")), HEADLINE_START))
        row[f"x{m} PF/ret/n"] = f"{fmt(st['pf'],2)}/{fmt(st['ret'])}/{st['tr']}"
        row[f"_ok{m}"] = np.isfinite(st["pf"]) and st["pf"] >= 1.15 and st["ret"] > 0
    row["robust"] = "yes" if row.get("_ok0.8") and row.get("_ok1.2") else "NO"
    ROB.append(row)

print("\n=== RANKED (pre-declared verdict; BTC 2017+) ===")
print(VT[[k for k in VT.columns if not k.startswith("_")]].to_string(index=False))
if ROB:
    RB = pd.DataFrame(ROB); print("\n=== KEEP robustness (+-20% parameters, BTC 2017+) ===")
    print(RB[[k for k in RB.columns if not k.startswith("_")]].to_string(index=False))
print("\n=== PLAIN WORDS ===")
for _, r in VT.iterrows():
    if r.verdict == "KEEP":
        rb = next((x["robust"] for x in ROB if x["idea"] == r.idea), "?")
        print(f"  KEEP  {r.idea}: passes every test (BTC PF {r['BTC PF']}, ETH PF {r['ETH PF']}, placebo {r['placebo PF']}); robust to +-20%: {rb}.")
    elif r.verdict == "WATCH":
        print(f"  WATCH {r.idea}: one miss -> {r.fails}.")
nd = (VT.verdict == "DROP").sum()
drop_ids = VT[VT.verdict == "DROP"].idea.str.split(" ").str[0].unique()
print(f"  DROP  {nd} ideas failed two or more tests: " + ", ".join(drop_ids))
for lst, pref in (("B", "B"), ("C", "C"), ("D", "D")):
    x = VT[VT.idea.str.startswith(pref)]
    pfs = pd.to_numeric(x["BTC PF"], errors="coerce")
    print(f"  GROUP {lst}: {(x.verdict=='KEEP').sum()} KEEP, {(x.verdict=='WATCH').sum()} WATCH, {(x.verdict=='DROP').sum()} DROP | median BTC PF {fmt(pfs.median(),2)}")
print("  Paper-trade any KEEP before it gets money; these are standalone 1%-risk backtests, not basket results.")
pd.DataFrame(BR).to_csv(OUT_DIR / "zai_batch7_btc.csv", index=False)
if ER: pd.DataFrame(ER).to_csv(OUT_DIR / "zai_batch7_eth.csv", index=False)
VT.to_csv(OUT_DIR / "zai_batch7_verdicts.csv", index=False)
print(f"\nWrote zai_batch7_btc/eth/verdicts.csv to {OUT_DIR} | runtime {time.time()-T0:.0f}s")
