# ===== BATCH 11 — exit / trade-management tests (X1, BE1, Q1, Z2, T1) — paste this WHOLE cell into ONE Colab cell =====
# (or:  !wget -q -O batch11.py https://osom-boba.pages.dev/colab/batch11.py   then   %run batch11.py)
#
# COMMON: same loaders and engines as batch 8/10 (BTC 1h 2013+, ETH 1h 2017+, hosted at
#   osom-boba.pages.dev/colab/). Costs 0.12%/side (FEE 0.0007 + SLIP 0.0005). One position at a
#   time per engine. Stop-first when a bar touches stop and target. Live basket risks: K8 2%;
#   COCO, B1G and S5 3%; C1, C2, V7, R0, MOM30, D34 1%. Engine trades are generated at 1% risk
#   with notional <= 1x; the basket resizes each trade to min(live_risk, risk) of equity.
# ENGINES (reused, not re-invented): K8 / C1 / C2 from batch8.py (C1/C2 = live-engine ports);
#   V7, S5, B1G and the COCO coil-state filter from specialists_batch6.py; COCO itself is the live
#   OCO + one re-arm 3xATR trail from the x7/test10 port of batch-4 sys_oco; R0 is osom6's 600h
#   sweep-and-reclaim (10% stop, 0.5xATR dip wait; default _ok1 gates are off); MOM30 is the
#   mom30.mjs Python port (partial 50% at 2 ATR, rest 3 ATR); D34 is zai_batch7's weekly BB-squeeze
#   → 10-day stop-order break, 3R, 7-day time stop, filled on 1h.
# PROTOCOL: entries stay fixed. Each card is a paired A/B on identical trade IDs vs the CURRENT
#   exit (the 1h path walker below, with the engine's present stop / target / partial / trail).
#   Report per engine and for the basket: trades, win%, avgR, expectancy, PF, ret%, maxDD%, MAR,
#   delta vs baseline, a paired bootstrap (2000 resamples of trade-level deltaR, p-value that the
#   mean delta > 0), and both halves (2017-2020 and 2021-2026) on BTC and on ETH 2017+.
#   Keep a card only if the basket MAR improves, the bootstrap p < 0.1, it holds in both halves,
#   and ETH doesn't contradict (ETH mean deltaR is not significantly < 0). Test each card alone
#   first. Sweeps stay small: pick the best by full-sample BTC basket MAR and also show the
#   roundest/middle value. Then greedily stack the passing cards in rank order, re-testing each
#   one on the new baseline.
# CARDS: (X1) dead-trade time stop on C1, C2, MOM30, B1G, S5, V7, R0 (and K8 daily variant).
#   Exit at market if unrealized < +thr R after N 4H bars. Sweep thr {0.25, 0.5, 0.75} x N
#   {8, 12, 16}. K8: same thr after 6 daily sessions. Also report what the trade would have made
#   after the early exit. (BE1) breakeven overhaul on C1, C2, MOM30: when unrealized >= trigger R,
#   move the stop to entry + buffer x ATR. Sweep trigger {1, 1.5, 2, never} with buffer
#   {0, 0.1, 0.2} ATR, one dimension at a time. Baseline: C1 BE at TP1; C2 and MOM30 have no
#   standalone BE (MOM30 still moves the remainder to entry after its 50% TP1, as today). Also
#   print the share of trades reaching +1R that tag entry before going on to target, split by
#   A2 vol state (weekly BB width percentile vs 3y: COIL <=15, EXP >=80). (Q1) runner handoff
#   for D34 and COCO: at +trigger R close split%, move the stop to BE + 0.3R, trail the rest on
#   a k x ATR20 daily chandelier (replacing D34's 3R cap). Sweep split {30, 40, 50}% x chandelier
#   {2.5, 3, 3.5} x trigger {1.5, 2}R. (Z2) expiry-week protocol on C1, C2: in the window from
#   last Friday -2 to +1 sessions (also test -2..0), take TP1 immediately once >= +1R and tighten
#   trails x 0.8 (sweep 0.7/0.8/0.9); split monthly vs quarterly expiries. Entries unchanged.
#   (T1) chandelier runner: C1 after TP1, C2 after +1.5R; replace the far target with
#   stop = highest high (or lowest low) since entry − k x ATR(14, 4H). Sweep k {2.5, 3, 3.5, 4};
#   the chosen k must work in both halves.
# v2 (2026-11-22): fixed BTC variants walking over ETH price arrays (frame now owns its arrays);
#   adds an identity check (no-op exit == baseline, max|dR|<1e-9) and a -1.5R no-gap sanity check.
# Smoke on the box only:  python3 batch11.py --smoke
# This script refuses to run a real-data backtest outside Colab (use --smoke).
import os, io, gzip, time, warnings, math, sys, calendar, hashlib
from datetime import date, timedelta, datetime, timezone
from pathlib import Path
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", 50); pd.set_option("display.max_rows", 400)

T0 = time.time()
H1 = 3_600_000; D1 = 24 * H1; H4 = 4 * H1; H12 = 12 * H1
FEE, SLIP = 0.0007, 0.0005
COST = FEE + SLIP
RISK = 0.01
MAX_NOTIONAL = 1.0
STOP_MIN, STOP_CAP = 0.015, 0.10
LAG_C2 = 8e-4
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"
HALF_A = ("2017-20", "2017-01-01", "2021-01-01")
HALF_B = ("2021-26", "2021-01-01", "2027-01-01")
UA = "osom-batch11/1.0"
C1_DEFAULTS = dict(don=20, chop=34, chopLen=14, adx=18, adxLen=14, stLen=10, stF=3,
                   htf=12, atrLen=14, sl=1.5, tp1=2.0, tp2=3.5, tp1Frac=0.3)
STOP_RULE = None
MIN_ON = True
MIN_STOP = 0.015
MAX_HOLD = 30 * 24
N_BOOT = 2000
P_KEEP = 0.1
LIVE_RISK = {"K8": 0.02, "COCO": 0.03, "B1G": 0.03, "S5": 0.03,
             "C1": 0.01, "C2": 0.01, "V7": 0.01, "R0": 0.01, "MOM30": 0.01, "D34": 0.01}
LIVE_ENGINES = list(LIVE_RISK)
A2_STATES = ["COIL", "EXPANSION", "NORMAL"]
CHAND = None
FT = FC = None
RNG = np.random.default_rng(0)
X1_ENG = {"C1", "C2", "MOM30", "B1G", "S5", "V7", "R0", "K8"}
BE1_ENG = {"C1", "C2", "MOM30"}
Q1_ENG = {"D34", "COCO"}
Z2_ENG = {"C1", "C2"}
T1_ENG = {"C1", "C2"}
HOLD_MAX = 10 ** 9

# ==== engines (copied read-only from batch10.py) ====

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 _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):
        t = pd.to_numeric(t).astype("float64")
        mx = t.max()
        ms = np.where(mx > 1e17, t / 1e6, np.where(mx > 1e14, t / 1e3, np.where(mx > 1e11, t, t * 1e3)))
        tms = ms.astype("int64")
    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 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 _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 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)

# ==== b8_c12.py ====
def fmt(x, nd=1):
    return "-" if x is None or (isinstance(x, float) and not np.isfinite(x)) else f"{x:.{nd}f}"

# ---------------------------------------------------------------------------
# C1 / C2 live-engine ports (signals.mjs computeC1 + __o4Calc cf)
# ---------------------------------------------------------------------------
def rma_seeded(x, n):
    """JS rma(): SMA of the first n finite values, then Wilder. Skips non-finite."""
    o = np.full(len(x), np.nan)
    s = 0.0; cnt = 0; v = np.nan
    for i, xi in enumerate(x):
        if not np.isfinite(xi):
            continue
        if np.isnan(v):
            s += xi; cnt += 1
            if cnt == n:
                v = s / n
                o[i] = v
        else:
            v = (v * (n - 1) + xi) / n
            o[i] = v
    return o

def tr_arr(h, l, c):
    tr = np.asarray(h - l, dtype=float)
    if len(h) > 1:
        tr[1:] = np.maximum.reduce([h[1:] - l[1:], np.abs(h[1:] - c[:-1]), np.abs(l[1:] - c[:-1])])
    return tr

def adx_arr(h, l, c, n):
    up = np.zeros(len(h)); dn = np.zeros(len(h))
    if len(h) > 1:
        up[1:] = h[1:] - h[:-1]
        dn[1:] = l[:-1] - l[1:]
    pdm = np.where((up > dn) & (up > 0), up, 0.0)
    mdm = np.where((dn > up) & (dn > 0), dn, 0.0)
    t = rma_seeded(tr_arr(h, l, c), n)
    p = rma_seeded(pdm, n); m = rma_seeded(mdm, n)
    dx = np.full(len(h), np.nan)
    with np.errstate(invalid="ignore", divide="ignore"):
        pp = 100.0 * p / t; mm = 100.0 * m / t
        ok = np.isfinite(pp) & np.isfinite(mm)
        dx[ok] = np.where(pp[ok] + mm[ok] != 0, 100.0 * np.abs(pp[ok] - mm[ok]) / (pp[ok] + mm[ok]), 0.0)
    return rma_seeded(dx, n)

def chop_arr_tr(h, l, c, n):
    """C1 Chop: TR-sum window, JS starts at i=n (window i-n+1..i)."""
    t = tr_arr(h, l, c)
    o = np.full(len(h), np.nan)
    logn = math.log10(n) if n > 1 else np.nan
    for i in range(n, len(h)):
        sl = 0.0; hi = -np.inf; lo = np.inf
        for j in range(i - n + 1, i + 1):
            sl += t[j]; hi = max(hi, h[j]); lo = min(lo, l[j])
        o[i] = 100.0 * math.log10(sl / (hi - lo)) / logn if hi > lo and sl > 0 else np.nan
    return o

def supertrend_dir(h, l, c, n, f):
    a = rma_seeded(tr_arr(h, l, c), n)
    direc = np.zeros(len(h), dtype=np.int8)
    U = D = np.nan; d = 1
    for i in range(len(h)):
        if not np.isfinite(a[i]):
            continue
        hl = (h[i] + l[i]) / 2
        up = hl - f * a[i]; dn = hl + f * a[i]
        if np.isnan(U):
            U, D = up, dn; direc[i] = d; continue
        pc2 = c[i - 1]; U1, D12 = U, D
        U = max(up, U1) if pc2 > U1 else up
        D = min(dn, D12) if pc2 < D12 else dn
        if d == -1 and c[i] > D12: d = 1
        elif d == 1 and c[i] < U1: d = -1
        direc[i] = d
    return direc

def bucket_ohlcv(t, o, h, l, c, v, hh, complete_only=False, drop_partial_last=False):
    W = hh * H1
    rows = []
    k = None; cur = None
    for i in range(len(t)):
        g = int(t[i] // W)
        if g != k:
            if cur is not None:
                rows.append(cur)
            k = g
            cur = [g * W, float(o[i]), float(h[i]), float(l[i]), float(c[i]), float(v[i]) if v is not None else 0.0, 1]
        else:
            cur[2] = max(cur[2], float(h[i]))
            cur[3] = min(cur[3], float(l[i]))
            cur[4] = float(c[i])
            cur[5] += float(v[i]) if v is not None else 0.0
            cur[6] += 1
    if cur is not None:
        rows.append(cur)
    if not rows:
        return {k: np.array([]) for k in ("time", "open", "high", "low", "close", "volume", "n")}
    a = np.array(rows, dtype=float)
    if complete_only:
        m = a[:, 6] == hh
        a = a[m]
    elif drop_partial_last and len(a) and a[-1, 6] < hh:
        a = a[:-1]
    return dict(time=a[:, 0].astype("int64"), open=a[:, 1], high=a[:, 2], low=a[:, 3],
                close=a[:, 4], volume=a[:, 5], n=a[:, 6].astype(int))

def _norm_d(d):
    """Always return numpy arrays so later steps don't depend on Series vs Index accessors."""
    vol = d["volume"] if (isinstance(d, dict) and "volume" in d) or (hasattr(d, "columns") and "volume" in d.columns) else None
    n = len(d["time"])
    return dict(time=np.asarray(d["time"], dtype="int64"),
                open=np.asarray(d["open"], dtype=float), high=np.asarray(d["high"], dtype=float),
                low=np.asarray(d["low"], dtype=float), close=np.asarray(d["close"], dtype=float),
                volume=np.asarray(vol, dtype=float) if vol is not None else np.zeros(n))

def c1_signals(D, p=None, relax=False):
    p = {**C1_DEFAULTS, **(p or {})}
    t, o, h, l, c, v = D["time"], D["open"], D["high"], D["low"], D["close"], D["volume"]
    B = bucket_ohlcv(t, o, h, l, c, v, 4, complete_only=True)
    bo, bh, bl, bc, bt = B["open"], B["high"], B["low"], B["close"], B["time"]
    nb = len(bc)
    atrb = rma_seeded(tr_arr(bh, bl, bc), p["atrLen"])
    chop = chop_arr_tr(bh, bl, bc, p["chopLen"])
    adx = adx_arr(bh, bl, bc, p["adxLen"])
    HB = bucket_ohlcv(t, o, h, l, c, v, p["htf"], complete_only=True)
    stv = supertrend_dir(HB["high"], HB["low"], HB["close"], p["stLen"], p["stF"]) if len(HB["time"]) else np.array([], dtype=np.int8)
    hclose = HB["time"] + p["htf"] * H1
    sig = np.zeros(nb, dtype=np.int8)
    uu = -1
    for k in range(p["don"], nb):
        mclose = int(bt[k] + 4 * H1)
        while uu + 1 < len(hclose) and hclose[uu + 1] <= mclose:
            uu += 1
        if not np.isfinite(atrb[k]) or uu < 0:
            continue
        if not relax and not stv[uu]:
            continue
        g = bh[k - p["don"]:k].max(); f = bl[k - p["don"]:k].min()
        y = True if relax else ((chop[k] < p["chop"]) and (adx[k] >= p["adx"]))
        st_ok_l = True if relax else (stv[uu] == 1)
        st_ok_s = True if relax else (stv[uu] == -1)
        if bc[k] > g and bc[k] > bo[k] and y and st_ok_l: sig[k] = 1
        elif bc[k] < f and bc[k] < bo[k] and y and st_ok_s: sig[k] = -1
    return dict(B=B, sig=sig, atr=atrb)

def _c1_trades(D, p=None, relax=False):
    p = {**C1_DEFAULTS, **(p or {})}
    R = c1_signals(D, p, relax=relax)
    B, sig, atrb = R["B"], R["sig"], R["atr"]
    t, o, h, l, c = D["time"], D["open"], D["high"], D["low"], D["close"]
    n = len(c); bt = B["time"]; nb = len(bt)
    pos_of = {int(tt): i for i, tt in enumerate(t)}
    trades = []; S = 0
    while S < nb:
        x = int(sig[S])
        if not x:
            S += 1; continue
        kt = int(bt[S + 1] if S + 1 < nb else bt[S] + 4 * H1)
        L0 = pos_of.get(kt)
        if L0 is None:
            S += 1; continue
        w = float(o[L0]); M = float(atrb[S])
        if not np.isfinite(M) or M <= 0:
            S += 1; continue
        Cstop = w - x * p["sl"] * M; T = w + x * p["tp1"] * M; E = w + x * p["tp2"] * M
        A = 1.0; fills = []; stage = 0; P = L0; done = False
        while P < n:
            hb, lb, ob = h[P], l[P], o[P]
            Fe = lb <= Cstop if x > 0 else hb >= Cstop
            Ye = stage == 0 and (hb >= T if x > 0 else lb <= T)
            Me = hb >= E if x > 0 else lb <= E
            if Fe:
                fills.append((A, min(Cstop, ob) if x > 0 else max(Cstop, ob), P)); A = 0; done = True; break
            if stage == 0 and Ye:
                fills.append((p["tp1Frac"], max(T, ob) if x > 0 else min(T, ob), P))
                A = 1 - p["tp1Frac"]; stage = 1; Cstop = w
                if ((lb <= w) if x > 0 else (hb >= w)) and P > L0:
                    fills.append((A, w, P)); A = 0; done = True; break
                if Me:
                    fills.append((A, max(E, ob) if x > 0 else min(E, ob), P)); A = 0; done = True; break
                P += 1; continue
            if stage == 1 and Me:
                fills.append((A, max(E, ob) if x > 0 else min(E, ob), P)); A = 0; done = True; break
            P += 1
        sl0 = w - x * p["sl"] * M
        if not done:
            break
        Z = fills[-1][2]
        trades.append(_trade_from_fills("C1", x, t[L0], t[Z], w, sl0, fills, t, L0, Z))
        he = t[Z] + H1; se = S + 1
        while se < nb and bt[se] + 4 * H1 < he:
            se += 1
        S = se
    return trades

def _trade_from_fills(src, side, t_in, t_out, entry, stop, fills, t_arr, ei, xi):
    """fills: list of (weight, px, bar_i). Cost 0.12%/side on entry + each exit notional."""
    ret = -COST
    for w, px, _ in fills:
        ret += w * (side * (px / entry - 1.0) - COST * px / entry)
    risk = abs(entry - stop) / entry if entry else np.nan
    net_R = ret / risk if (np.isfinite(risk) and risk > 0) else np.nan
    why = "SL"
    if len(fills) > 1:
        last = fills[-1][1]
        why = "BE" if abs(last - entry) / entry < 1e-9 else "TP2"
        if len(fills) == 1:
            why = "TP1"
    else:
        px = fills[0][1]
        if side > 0 and px >= entry: why = "TP"
        elif side < 0 and px <= entry: why = "TP"
        else: why = "SL"
    return dict(src=src, side=int(side), t_in=int(t_in), t_out=int(t_out), entry=float(entry),
                exit=float(fills[-1][1]), stop=float(stop), risk=float(risk) if np.isfinite(risk) else np.nan,
                net_R=float(net_R) if np.isfinite(net_R) else np.nan, ret=float(ret), why=why,
                weight=1.0, ei=int(ei), xi=int(xi))

def c2_trades(D, relax_chop=False, delay_bars=0, sl_mult=1.5, tp_mult=3.0):
    """Faithful __o4Calc cf book. Entry at next 4h open, LAG_C2 on fill, SL 1.5 / TP 3 ATR, stop-first.
    delay_bars shifts the signal later (placebo). relax_chop drops the Chop<30 mask."""
    t, o, h, l, c, v = D["time"], D["open"], D["high"], D["low"], D["close"], D["volume"]
    B = bucket_ohlcv(t, o, h, l, c, v, 4, complete_only=False, drop_partial_last=True)
    n = len(B["time"])
    if n < 40:
        return []
    o4, h4, l4, c4, v4 = B["open"], B["high"], B["low"], B["close"], B["volume"]
    # JS ema: seed x[0], alpha=2/(sp+1)
    def ema(x, sp):
        a = 2.0 / (sp + 1.0); r = np.empty(n); u = x[0]
        for i in range(n):
            u = a * x[i] + (1 - a) * u; r[i] = u
        return r
    e9, e21 = ema(c4, 9), ema(c4, 21)
    atrb = rma_seeded(tr_arr(h4, l4, c4), 14)
    def roll(x, w, fn):
        r = np.full(n, np.nan)
        for i in range(w - 1, n):
            sl = x[i - w + 1:i + 1]
            if not np.isfinite(sl).all():
                continue
            r[i] = sl.max() if fn == "max" else sl.min() if fn == "min" else sl.mean() if fn == "mean" else sl.sum()
        return r
    def sh(x):
        r = np.full(n, np.nan); r[1:] = x[:-1]; return r
    atrS, volS = roll(atrb, 20, "mean"), roll(v4, 20, "mean")
    ph10, pl10 = sh(roll(h4, 10, "max")), sh(roll(l4, 10, "min"))
    ph20, pl20 = sh(roll(h4, 20, "max")), sh(roll(l4, 20, "min"))
    hn, ln, as14 = roll(h4, 14, "max"), roll(l4, 14, "min"), roll(atrb, 14, "sum")
    with np.errstate(invalid="ignore", divide="ignore"):
        dlt = hn - ln
        ch = 100.0 * np.log10(as14 / dlt) / math.log10(14)
        chm = (ch < 30) & np.isfinite(ch) & (dlt != 0)
    if relax_chop:
        chm = np.isfinite(atrb)
    # Votes must be combined as integers. On NumPy 2 / Python 3.13, numpy.bool
    # addition saturates (True+True is True, not 2), which zeroed every C2 trade.
    rg = h4 - l4
    bd = c4 - o4
    cl = np.divide(c4 - l4, rg, out=np.full(n, np.nan), where=rg != 0)
    chh = np.divide(h4 - c4, rg, out=np.full(n, np.nan), where=rg != 0)
    av = (atrb > atrS) & np.isfinite(atrS)
    mask = chm & np.isfinite(atrb)
    g2l = (c4 > ph20) & av & mask
    g2s = (c4 < pl20) & av & mask
    b6l = (c4 > ph10) & np.isfinite(volS) & (v4 > volS * 1.5) & mask
    b6s = (c4 < pl10) & np.isfinite(volS) & (v4 > volS * 1.5) & mask
    d3l = (bd > atrb) & (e9 > e21) & (cl >= 0.75) & np.isfinite(volS) & (v4 > volS) & mask
    d3s = (-bd > atrb) & (e9 < e21) & (chh >= 0.75) & np.isfinite(volS) & (v4 > volS) & mask
    m9l = (c4 > e9) & (e9 > e21) & av & (cl >= 0.5) & mask
    m9s = (c4 < e9) & (e9 < e21) & av & (chh >= 0.5) & mask
    L = ((g2l | b6l).astype(np.int16) + d3l.astype(np.int16) + m9l.astype(np.int16)) >= 2
    S = ((g2s | b6s).astype(np.int16) + d3s.astype(np.int16) + m9s.astype(np.int16)) >= 2
    if delay_bars > 0:
        L = np.r_[np.zeros(delay_bars, dtype=bool), L[:-delay_bars]]
        S = np.r_[np.zeros(delay_bars, dtype=bool), S[:-delay_bars]]
    i0 = 0
    while i0 < n and not np.isfinite(atrb[i0]):
        i0 += 1
    trades = []; ip = False; pl = ps = False
    side = ei = 0; raw = sl = tp = 0.0
    xc = True
    for i in range(i0, n - 1):
        ls, ss = bool(L[i]), bool(S[i])
        if not ip:
            el = ls and not pl and not (xc and ss)
            es = ss and not ps and not (xc and ls)
            if el != es:
                side = 1 if el else -1
                raw = float(o4[i + 1])
                ep = raw * (1.0 + side * LAG_C2)
                sl = ep - side * atrb[i] * sl_mult
                tp = ep + side * atrb[i] * tp_mult
                ei = i + 1; ip = True
        pl, ps = ls, ss
        if ip:
            xp = why = None
            if side == 1:
                if l4[i + 1] <= sl: xp, why = sl, "SL"
                elif h4[i + 1] >= tp: xp, why = tp, "TP"
            else:
                if h4[i + 1] >= sl: xp, why = sl, "SL"
                elif l4[i + 1] <= tp: xp, why = tp, "TP"
            if xp is not None:
                entry = raw * (1.0 + side * LAG_C2)
                # map 4h times
                t_in = int(B["time"][ei]); t_out = int(B["time"][i + 1])
                risk = abs(entry - sl) / entry
                ret = -COST + (side * (xp / entry - 1.0) - COST * xp / entry)
                net_R = ret / risk if risk > 0 else np.nan
                trades.append(dict(src="C2", side=int(side), t_in=t_in, t_out=t_out, entry=float(entry),
                                   exit=float(xp), stop=float(sl), risk=float(risk), net_R=float(net_R),
                                   ret=float(ret), why=why, weight=1.0, ei=int(ei), xi=int(i + 1)))
                ip = False
    return trades


# ==== b6_map.py ====
def sig_to_base(htf, sig):
    out = np.zeros(N, dtype="int8"); idx = htf["last_i"].values; s = np.asarray(sig); m = s != 0
    out[idx[m]] = s[m]; return out

def at_base(htf, values):
    out = np.full(N, np.nan); out[htf["last_i"].values] = np.asarray(values, dtype="float64"); return out

# ==== b6_day.py ====
def build_day(fund=None):
    D = resample(D1); D["dt"] = pd.to_datetime(D["time"], unit="ms"); D["year"] = D.dt.dt.year
    D["atr"] = atr(D.high.values, D.low.values, D.close.values, 20)
    D["atr14"] = atr(D.high.values, D.low.values, D.close.values, 14)
    if fund is not None:
        f = fund.copy(); f["g"] = f["time"] // D1
        fd = f.groupby("g").funding.sum()
        s7 = fd.rolling(7, min_periods=5).sum()
        z = (s7 - s7.rolling(90, min_periods=60).mean()) / s7.rolling(90, min_periods=60).std()
        D["fz"] = z.reindex(D["g"].values).values
    else:
        D["fz"] = np.nan
    return D


# ==== b6_states.py ====
def market_states(D):
    h, l, c, o, v = D.high.values, D.low.values, D.close.values, D.open.values, D.volume.values
    n = len(D)
    a20p = pd.Series(D["atr"]).shift(1).values; a14 = D["atr14"].values
    pc = np.r_[np.nan, c[:-1]]
    tr = np.nanmax(np.vstack([h - l, np.abs(h - pc), np.abs(l - pc)]), axis=0)
    rk = lambda x: pd.Series(x).rolling(365, min_periods=200).rank(pct=True).values
    atrp_pct = rk(a14 / c)
    rng7_pct = rk((pd.Series(h).rolling(7).max() - pd.Series(l).rolling(7).min()).values / c)
    sma20 = pd.Series(c).rolling(20).mean().values
    bbw_pct = rk(pd.Series(c).rolling(20).std().values / sma20)
    er10 = (np.abs(pd.Series(c).diff(10)) / pd.Series(c).diff().abs().rolling(10).sum()).values
    lv = pd.Series(np.log(np.maximum(v, 1e-9)))
    vz = ((lv - lv.rolling(60, min_periods=30).mean().shift(1)) / lv.rolling(60, min_periods=30).std().shift(1)).values
    vz = np.where(v > 0, vz, np.nan)
    voldry = (pd.Series(v).rolling(7).mean() / pd.Series(v).rolling(90, min_periods=60).mean()).values
    wick_up = h - np.maximum(o, c); wick_dn = np.minimum(o, c) - l
    # QUAKE
    shock = (tr >= 2.5 * a20p) | ((tr >= 1.8 * a20p) & (vz >= 2.5)) | (np.maximum(wick_up, wick_dn) >= 1.5 * a20p)
    sdir = np.sign(c - o); sdir = np.where(sdir == 0, np.sign(c - pc), sdir)
    quake = np.zeros(n, bool); qdir = np.zeros(n)
    last = -99; ld = 0
    for i in range(n):
        if shock[i]: last, ld = i, sdir[i]
        if i - last <= 2: quake[i] = True; qdir[i] = ld
    # RIDE
    hi20 = pd.Series(h).rolling(20).max().shift(1).values; lo20 = pd.Series(l).rolling(20).min().shift(1).values
    brk_up5 = pd.Series(c > hi20).rolling(5).max().fillna(0).values > 0
    brk_dn5 = pd.Series(c < lo20).rolling(5).max().fillna(0).values > 0
    a_up = a14 > np.r_[np.full(5, np.nan), a14[:-5]]
    ride_up = (er10 >= 0.40) & a_up & (c > sma20) & brk_up5
    ride_dn = (er10 >= 0.40) & a_up & (c < sma20) & brk_dn5
    # EXHAUST
    run15 = c - np.r_[np.full(15, np.nan), c[:-15]]
    upr = pd.Series(run15 >= 5 * a20p).rolling(3).max().fillna(0).values > 0
    dnr = pd.Series(run15 <= -5 * a20p).rolling(3).max().fillna(0).values > 0
    rng = h - l
    tr3 = pd.Series(tr).rolling(3).mean().values; tr10p = pd.Series(tr).shift(3).rolling(10).mean().values
    contr = tr3 < 0.5 * tr10p
    fz = D["fz"].values
    ex_up = upr & (((c - sma20) >= 3.5 * a20p) | ((wick_up >= 0.5 * rng) & (rng >= 1.5 * a20p)) | contr | (fz >= 2))
    ex_dn = dnr & (((sma20 - c) >= 3.5 * a20p) | ((wick_dn >= 0.5 * rng) & (rng >= 1.5 * a20p)) | contr | (fz <= -2))
    # COIL
    cnt = (atrp_pct <= 0.25).astype(int) + (rng7_pct <= 0.20).astype(int) + (bbw_pct <= 0.20).astype(int) + (voldry <= 0.8).astype(int)
    coil = (cnt >= 3) & (er10 < 0.35)
    st = np.full(n, "CHOP", dtype=object); sd = np.zeros(n)
    st[coil] = "COIL"
    st[ride_up | ride_dn] = "RIDE"; sd[ride_up] = 1; sd[ride_dn & ~ride_up] = -1
    exm = ex_up | ex_dn
    st[exm] = "EXHAUST"; sd[ex_up] = 1; sd[ex_dn & ~ex_up] = -1
    st[quake] = "QUAKE"; sd[quake] = qdir[quake]
    warm = ~np.isfinite(atrp_pct) | ~np.isfinite(a20p)
    st[warm] = "WARMUP"; sd[warm] = 0
    rpct = pd.Series((hi20 - lo20) / pc).rolling(365, min_periods=200).rank(pct=True).values
    brk = (rpct <= 0.30) & ((c > hi20) | (c < lo20))
    brk3 = brk | np.r_[False, brk[:-1]] | np.r_[False, False, brk[:-2]]
    D["state"] = st; D["sdir"] = sd; D["brk3"] = brk3
    return D

# ==== b6_v7s5.py ====
def v7_system(D):
    tp_ = (Hh + L + C) / 3; vv = np.maximum(V, 1e-9)
    vw = lambda n: (pd.Series(tp_ * vv).rolling(n).sum() / pd.Series(vv).rolling(n).sum()).values
    s24 = (C - vw(24)) / C; s168 = (C - vw(168)) / C
    p24 = pd.Series(s24).rolling(500, min_periods=300).rank(pct=True).values * 100
    p168 = pd.Series(s168).rolling(500, min_periods=300).rank(pct=True).values * 100
    p24p = np.r_[np.nan, p24[:-1]]
    lo168 = pd.Series(p168 <= 20).rolling(6).max().fillna(0).values > 0
    hi168 = pd.Series(p168 >= 80).rolling(6).max().fillna(0).values > 0
    longv = (p24p < 10) & (p24 >= 10) & lo168; shortv = (p24p > 90) & (p24 <= 90) & hi168
    hh = pd.Series(Hh).rolling(200).max().values; ll = pd.Series(L).rolling(200).min().values
    posr = (C - ll) / np.maximum(hh - ll, 1e-9); mid = (posr >= 0.35) & (posr <= 0.65)
    s200 = D.close.rolling(200).mean().values
    bear = to_base(D, ((D.close.values < s200) & (s200 < np.r_[np.full(20, np.nan), s200[:-20]])).astype(float), D1) == 1
    sig = np.zeros(N, "int8"); sig[longv & ~mid & ~bear] = 1; sig[shortv & ~mid] = -1
    return sig

def s5_b1(D):
    dh, dl, dc = D.high.values, D.low.values, D.close.values
    datr = D["atr"].values; datr_prior = pd.Series(datr).shift(1).values; b_datr = to_base(D, datr, D1)
    pc = np.r_[np.nan, dc[:-1]]
    tr = np.nanmax(np.vstack([dh - dl, np.abs(dh - pc), np.abs(dl - pc)]), axis=0)
    posc = (dc - dl) / np.maximum(dh - dl, 1e-9); big = tr >= 2.2 * datr_prior
    s = np.zeros(len(D), "int8"); s[big & (posc >= 0.85)] = 1; s[big & (posc <= 0.15)] = -1
    sd = np.maximum(np.where(s > 0, dc - dl, dh - dc), datr)
    S5 = dict(sig=sig_to_base(D, s), stop_dist=at_base(D, sd), chand_atr=b_datr, chand_mult=3.0, max_hold=15 * 24)
    n = 7
    rngb = (pd.Series(dh).rolling(n).max() - pd.Series(dl).rolling(n).min()) / pd.Series(dc)
    pct = rngb.rolling(365, min_periods=200).rank(pct=True).shift(1).values
    hi = pd.Series(dh).rolling(n).max().shift(1).values; lo = pd.Series(dl).rolling(n).min().shift(1).values
    s = np.zeros(len(D), "int8"); s[(pct <= 0.20) & (dc > hi)] = 1; s[(pct <= 0.20) & (dc < lo)] = -1
    sd = np.maximum(np.where(s > 0, dc - lo, hi - dc), datr)
    B1 = dict(sig=sig_to_base(D, s), stop_dist=at_base(D, sd), chand_atr=b_datr, chand_mult=3.0, max_hold=30 * 24)
    return S5, B1

# ==== x7_coil.py ====
def coil_setups(D, P, placebo=False, heights=None):
    st = D["state"].values; n = len(D); out = []; last = -10**9
    hi = D.high.values; lo = D.low.values; cl = D.close.values; at = D["atr"].values; li = D["last_i"].values
    N_, M_ = int(P["N"]), int(P["M"])
    for d in range(N_, n):
        if d - last < M_: continue
        ok = (st[d] == "COIL") if not placebo else (st[d] not in ("COIL", "WARMUP"))
        if not ok or not np.isfinite(at[d]): continue
        i0 = li[d] + 1
        if i0 >= N - 2: continue
        if placebo:
            hp = heights[RNG.integers(0, len(heights))]
            bh, bl = cl[d] * (1 + hp / 2), cl[d] * (1 - hp / 2)
        else:
            bh, bl = hi[d - N_ + 1:d + 1].max(), lo[d - N_ + 1:d + 1].min()
        out.append(dict(d=d, i0=i0, i1=min(N - 1, i0 + M_ * 24), bh=bh, bl=bl, A=at[d], t=T[i0]))
        last = d
    return out

# ==== x7_coco.py ====
def sim_leg(i0, side, entry, stop, tp=np.nan, trail=None, exh=None, fill_bar_stopentry=False, chand=None):
    """Walk 1h bars from i0 (entry bar). Returns (exit_i, exit_px, kind, frac, stop0)."""
    if STOP_RULE is not None and abs(entry - stop) / entry > STOP_RULE[1]:
        if STOP_RULE[0] == "skip": return None
        stop = entry - side * STOP_RULE[1] * entry
    stop0 = stop; risk = abs(entry - stop) / entry
    if MIN_ON and risk < MIN_STOP: return None      # TEST 1 rule: skip trades with a stop < 1.5% (after CAP10)
    if risk <= 0: return None
    frac = min(MAX_NOTIONAL, RISK / risk); ext = entry
    end = min(N - 1, i0 + MAX_HOLD)
    for i in range(i0, end + 1):
        o, h, l, c = O[i], Hh[i], L[i], C[i]
        first = (i == i0)
        if side > 0:
            if l <= stop:
                return i, (stop if first else min(o, stop)), ("stop" if stop == stop0 else "trail"), frac, stop0
            if np.isfinite(tp) and h >= tp and not (first and fill_bar_stopentry):
                return i, (tp if first else max(o, tp)), "tp", frac, stop0
        else:
            if h >= stop:
                return i, (stop if first else max(o, stop)), ("stop" if stop == stop0 else "trail"), frac, stop0
            if np.isfinite(tp) and l <= tp and not (first and fill_bar_stopentry):
                return i, (tp if first else min(o, tp)), "tp", frac, stop0
        if trail is not None and np.isfinite(chand[i]):
            ext = max(ext, h) if side > 0 else min(ext, l)
            ns = ext - side * trail * chand[i]
            stop = max(stop, ns) if side > 0 else min(stop, ns)
        if exh is not None and exh[i] and i + 1 <= N - 1:
            return i + 1, O[i + 1], "exh", frac, stop0
        if i == end:
            return i, c, "time", frac, stop0
    return end, C[end], "time", frac, stop0

def booked(i_in, i_out, side, entry, px, frac, tag="", stop0=np.nan):
    return (T[i_in], T[i_out], side, frac * (side * (px / entry - 1) - 2 * COST), tag, side * (px / entry - 1), abs(entry - stop0) / entry)

def first_touch(i, bh, bl):
    up = Hh[i] >= bh; dn = L[i] <= bl
    if up and dn: return 1 if (bh - O[i]) <= (O[i] - bl) else -1
    return 1 if up else (-1 if dn else 0)

def engine_trades(res):
    t = res["trades"]; return [(a, b, c, d, "", m, r) for a, b, c, d, m, r in zip(t.t_in, t.t_out, t.side, t.ret, t.move, t.risk)]

# =============================================================================================
# TEST 1 additions (Kubu)
# =============================================================================================
EQ0 = 10_000.0; RISK_COCO = 0.03; LEV = 3.0; LIQ_MOVE = 1.0 / LEV - 0.005; MIN_FRAC = 0.25; N_PLAC = 10
FT = None; FC = None; CHAND = None

def fix_eth_bar_exact(e):
    """ETH 1h 2017-08-22 04:00 UTC: open 144.21 -> 280.00, low -> 279.96 (values given by OSOM)."""
    t = ms("2017-08-22 04:00"); k = np.where(e["time"].values == t)[0]
    if not len(k): print("ETH bad bar not in file -> no fix"); return e
    i = k[0]
    if abs(e["open"].iloc[i] - 144.21) > 1.0: print("ETH 2017-08-22 04:00 open is not 144.21 -> no fix"); return e
    e = e.copy(); e.iloc[i, e.columns.get_loc("open")] = 280.00; e.iloc[i, e.columns.get_loc("low")] = 279.96
    e.iloc[i, e.columns.get_loc("high")] = max(e["high"].iloc[i], 280.00)
    print("DATA FIX: ETH 2017-08-22 04:00 UTC open 144.21 -> 280.00, low -> 279.96"); return e

def set_funding(fund):
    global FT, FC
    if fund is None or not len(fund): FT = None; FC = None; return
    f = fund.dropna().sort_values("time"); FT = f["time"].values.astype("int64"); FC = np.r_[0.0, np.cumsum(f["funding"].values)]

def fund_sum(ti, to):
    """sum of funding rates settled in (t_in, t_out] (position open at the settlement). Longs pay positive funding."""
    if FT is None: return np.zeros(len(ti))
    return FC[np.searchsorted(FT, to, side="right")] - FC[np.searchsorted(FT, ti, side="right")]

def sys_coco(S, trail):
    """Bobo's batch-4 sys_oco(S, 'opp', 'trail3', rearm=True) with the trail multiple as a parameter."""
    tr = []
    for s in S:
        bh, bl, A = s["bh"], s["bl"], s["A"]; i = s["i0"]; i1 = s["i1"]
        side = 0
        while i <= i1:
            side = first_touch(i, bh, bl)
            if side: break
            i += 1
        if not side: continue
        e_prev_px = np.nan
        for attempt in range(2):
            e = max(O[i], bh) if side > 0 else min(O[i], bl)
            if attempt == 1: e = max(e_prev_px, bh) if side > 0 else min(e_prev_px, bl)
            stp = bl if side > 0 else bh
            if side * (e - stp) <= 0: stp = e - side * 0.5 * A
            r = sim_leg(i, side, e, stp, np.nan, trail, None, fill_bar_stopentry=True, chand=CHAND)
            if r is None: break
            j, px, kind, frac, s0 = r
            tr.append(booked(i, j, side, e, px, frac, kind, s0))
            if not (kind == "stop" and j <= i1): break
            side = -side; k = j; e_prev_px = px; found = False      # opposite stop-entry live from the stop bar (one re-arm)
            while k <= i1:
                if (side > 0 and Hh[k] >= bh) or (side < 0 and L[k] <= bl): found = True; break
                k += 1
            if not found: break
            if k > j: e_prev_px = O[k]
            i = k
    return tr

# ==== b8_days.py ====
def _dayofweek(ts):
    return ts.dt.dayofweek if isinstance(ts, pd.Series) else ts.dayofweek

def _floor_day(ts):
    return ts.dt.floor("D") if isinstance(ts, pd.Series) else ts.floor("D")

# ---------------------------------------------------------------------------
# Killa crash-week / crash-day

# ==== b8_exp.py ====
def last_friday_expiries(start="2013-01-01", end=None):
    end = end or datetime.now(timezone.utc).strftime("%Y-%m-%d")
    y0, m0 = [int(x) for x in start.split("-")[:2]]
    y1, m1 = [int(x) for x in end.split("-")[:2]]
    out = []
    y, m = y0, m0
    while (y, m) <= (y1, m1):
        last = calendar.monthrange(y, m)[1]
        d = date(y, m, last)
        while d.weekday() != 4:
            d -= timedelta(days=1)
        out.append(pd.Timestamp(year=d.year, month=d.month, day=d.day, hour=8, tz="UTC"))
        m += 1
        if m == 13:
            y, m = y + 1, 1
    return out

# ==== b8_stats.py ====
def _tframe(trades):
    if not trades:
        return pd.DataFrame(columns=["side", "t_in", "t_out", "net_R", "weight", "src", "why"])
    return pd.DataFrame([{
        "side": t["side"], "t_in": int(t["t_in"]), "t_out": int(t["t_out"]),
        "net_R": float(t["net_R"]) if np.isfinite(t.get("net_R", np.nan)) else np.nan,
        "weight": float(t.get("weight", 1.0)), "src": t.get("src", ""), "why": t.get("why", ""),
        "entry_ts": pd.Timestamp(int(t["t_in"]), unit="ms", tz="UTC"),
        "exit_ts": pd.Timestamp(int(t["t_out"]), unit="ms", tz="UTC"),
    } 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, netR=np.nan, ddR=np.nan)
    wR = (tf["weight"] * tf["net_R"]).astype(float).to_numpy()
    wR = wR[np.isfinite(wR)]
    if len(wR) == 0:
        return dict(tr=len(tf), win=np.nan, pf=np.nan, ret=np.nan, dd=np.nan, avgR=np.nan, netR=np.nan, ddR=np.nan)
    g = wR[wR > 0].sum(); ls = -wR[wR < 0].sum()
    pf = (g / ls) if ls > 0 else (np.inf if g > 0 else np.nan)
    eq = np.cumprod(1.0 + RISK * wR)
    eq = np.r_[1.0, eq]
    peak = np.maximum.accumulate(eq)
    dd = 100 * ((eq / peak) - 1).min()
    cs = np.cumsum(wR); pk = np.maximum.accumulate(cs)
    ddR = float((cs - pk).min()) if len(cs) else np.nan
    return dict(tr=int(len(tf)), win=100 * float((wR > 0).mean()), pf=float(pf) if np.isfinite(pf) else pf,
                ret=100 * float(eq[-1] - 1), dd=float(dd), avgR=float(np.nanmean(wR)),
                netR=float(np.nansum(wR)), ddR=ddR)

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)
    s = tf.assign(R=tf["weight"] * tf["net_R"]).set_index("exit_ts")["R"].groupby(lambda x: pd.Timestamp(x).floor("D")).sum()
    s.index = pd.to_datetime(s.index, utc=True)
    return (RISK * s).rename("ret")

def idea_row(name, trades, p_trades, k8d):
    tdf = _tframe(trades)
    h = tstats(_window(tdf, HEADLINE_START))
    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)
    else:
        years = max(0.25, (pd.Timestamp("now", tz="UTC") - pd.Timestamp(HEADLINE_START, tz="UTC")).days / 365.25)
    row = {"idea": name, "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"]),
           "netR": fmt(h["netR"], 1), "maxDD_R": fmt(h["ddR"], 1),
           "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):
        k = k8d.copy()
        if not isinstance(k.index, pd.DatetimeIndex):
            k.index = _floor_day(pd.to_datetime(np.asarray(k.index) * D1, unit="ms", utc=True))
        else:
            k.index = _floor_day(pd.to_datetime(k.index, utc=True))
        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["_ck"] = ck
    row["_b1"] = tstats(_window(tdf, "2017-01-01", "2021-01-01"))["ret"]
    row["_b2"] = tstats(_window(tdf, "2021-01-01"))["ret"]
    row["_h"] = h
    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", 48):
        print(t[cols].to_string(index=False))


# ==== tail1.py ====
# ---------------------------------------------------------------------------
# Extra helpers (COCO / V7 / S5 / B1G / R0 / MOM30 / D34)
# ---------------------------------------------------------------------------
def load_etf():
    """Daily US spot BTC ETF net flows from the hosted Farside extract (flow_usd in USD)."""
    cands = []
    if Path("/content").exists():
        cands += sorted(Path("/content").glob("*etf_flow*"))
    for p in [Path("/workspace/osom10/deploy/colab/btc_etf_flows.csv.gz"),
              Path("/tmp/batch10/btc_etf_flows.csv.gz"),
              Path("btc_etf_flows.csv.gz")]:
        if p.exists() and p not in cands:
            cands.append(p)
    frames = []
    for p in cands:
        try:
            frames.append(pd.read_csv(p))
        except Exception:
            pass
    if not frames:
        try:
            print(f"Downloading {SITE}btc_etf_flows.csv.gz ...")
            frames.append(_fetch(SITE + "btc_etf_flows.csv.gz"))
        except Exception as e:
            print(f"  hosted ETF flows failed: {e}")
            return None
    out = []
    for f in frames:
        cl = {c.lower().strip(): c for c in f.columns}
        dc = next((cl[c] for c in ("date", "day", "time") if c in cl), None)
        if dc is None:
            continue
        d = pd.to_datetime(f[dc], utc=True, errors="coerce")
        if "flow_usd" in cl:
            v = pd.to_numeric(f[cl["flow_usd"]], errors="coerce")
            if np.nanmax(np.abs(v.values)) < 1e6 and "flow_usdm" in cl:
                v = pd.to_numeric(f[cl["flow_usdm"]], errors="coerce") * 1_000_000.0
        elif "flow_usdm" in cl:
            v = pd.to_numeric(f[cl["flow_usdm"]], errors="coerce") * 1_000_000.0
        elif "total" in cl:
            v = pd.to_numeric(f[cl["total"]], errors="coerce") * 1_000_000.0
        else:
            continue
        out.append(pd.DataFrame({"date": d.dt.floor("D"), "flow_usd": v}).dropna())
    if not out:
        return None
    e = pd.concat(out).drop_duplicates("date", keep="last").sort_values("date").reset_index(drop=True)
    return e

def funding_3s(fund):
    """3-settlement (24h) funding sum, indexed by settlement time, plus 1y percentile."""
    if fund is None or not len(fund):
        return None
    f = fund.dropna().sort_values("time").copy()
    f["s3"] = f["funding"].rolling(3, min_periods=3).sum()
    # ~3 * 365 = 1095 settlements in a year of 8h prints
    f["pct"] = f["s3"].rolling(3 * 365, min_periods=3 * 90).rank(pct=True)
    return f

def fund_at(f3, t_ms, field="pct"):
    if f3 is None or not len(f3):
        return np.nan
    i = int(np.searchsorted(f3["time"].values, t_ms, side="right") - 1)
    if i < 0:
        return np.nan
    return float(f3[field].iloc[i])

def _sma_safe(x, n):
    return pd.Series(x).rolling(int(n), min_periods=int(n)).mean().to_numpy()

R0_DEFAULTS = dict(len=600, holdDays=10, stop=10, dipMA=4800, dipSlope=720, x=0.5, h=12)

def _wilder_ema(tr, alpha):
    out = np.empty(len(tr)); out[0] = tr[0]
    for i in range(1, len(tr)):
        out[i] = alpha * tr[i] + (1 - alpha) * out[i - 1]
    return out

def _true_range(h, l, c):
    tr = h - l
    pc = np.r_[np.nan, c[:-1]]
    tr2 = np.fmax(tr, np.fmax(np.abs(h - pc), np.abs(l - pc)))
    tr2[0] = h[0] - l[0]
    return tr2

def _open_trade(side, ei, entry, stop, n, close, why="open"):
    return dict(side=side, ei=ei, xi=n - 1, entry=entry, exit=close[n - 1], stop=stop,
                fills=[(1.0, close[n - 1])], ret=side * (close[n - 1] / entry - 1) - 2 * COST, why=why)

def osom_r0(D, p=None):
    """osom6 R0: 600h sweep-and-reclaim, 10-day hold, 10% stop, 0.5xATR dip wait (up to 12h)."""
    p = {**R0_DEFAULTS, **(p or {})}
    o, h, l, c = D["open"].values, D["high"].values, D["low"].values, D["close"].values
    n = len(c); W, hold = int(p["len"]), int(p["holdDays"] * 24)
    ph = pd.Series(h).rolling(W).max().shift(1).to_numpy(); pl = pd.Series(l).rolling(W).min().shift(1).to_numpy()
    s = np.zeros(n, int); a = 0; left = 0
    for w in range(n):
        M = 0
        if w >= W:
            if h[w] > ph[w] and c[w] < ph[w]: M = -1
            elif l[w] < pl[w] and c[w] > pl[w]: M = 1
        if M and M != a: a = M; left = hold
        elif M: left = hold
        elif left > 0:
            left -= 1
            if left == 0: a = 0
        s[w] = a
    ma = _sma_safe(c, int(p["dipMA"])) if p["dipMA"] else np.full(n, np.nan)
    sl_ = int(p["dipSlope"])
    def dip(w):
        return p["dipMA"] > 0 and c[w] < ma[w] and w >= sl_ and ma[w] < ma[w - sl_]
    v = p["stop"] / 100
    base = []; y = 0; ent = 0.0; ei = 0; k = 0
    for w in range(n - 1):
        if y:
            M = ent * (1 - y * v)
            if (l[w] <= M) if y > 0 else (h[w] >= M):
                base.append((y, ei, w, min(M, o[w]) if y > 0 else max(M, o[w]), "stop")); y = 0
        if s[w] != k:
            M = s[w]; k = M
            if M == 0:
                if y: base.append((y, ei, w + 1, o[w + 1], "time")); y = 0
            elif M != y:
                if y: base.append((y, ei, w + 1, o[w + 1], "flip")); y = 0
                if M > 0 and dip(w):
                    pass
                else:
                    y = M; ent = o[w + 1]; ei = w + 1
    if y: base.append((y, ei, None, None, "open"))
    tr = _true_range(h, l, c); atrv = _wilder_ema(tr, 0.08)
    trades = []
    for (S, vI, xI, xP, why0) in base:
        closed = xI is not None; yI = xI if closed else n
        lvl = o[vI] - S * p["x"] * atrv[vI - 1]
        wI = -1
        for P in range(vI, min(vI + int(p["h"]), yI)):
            if S * (c[P] - lvl) <= 0:
                if P + 1 < yI and P + 1 < n: wI = P + 1
                break
        if wI < 0: continue
        Cpx = o[wI]; Tstop = Cpx * (1 - S * v); E = -1; A_ = xP; why = why0
        if not np.isfinite(Tstop): continue
        for P in range(wI, yI):
            if (l[P] <= Tstop) if S > 0 else (h[P] >= Tstop):
                E = P; A_ = min(Tstop, o[P]) if S > 0 else max(Tstop, o[P]); why = "stop"; break
        if E >= 0 or closed:
            xi = E if E >= 0 else xI
            trades.append(dict(side=S, ei=wI, xi=min(xi, n - 1), entry=Cpx, exit=A_, stop=Tstop, why=why))
        else:
            trades.append(_open_trade(S, wI, Cpx, Tstop, n, c))
    return trades

def bb_width(x, n=20, k=2.0):
    s = pd.Series(x)
    mid = s.rolling(n, min_periods=n).mean()
    sd = s.rolling(n, min_periods=n).std(ddof=0)
    up, lo = mid + k * sd, mid - k * sd
    w = (up - lo) / mid.replace(0, np.nan)
    return up.to_numpy(), mid.to_numpy(), lo.to_numpy(), w.to_numpy()

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

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

def _fill_stop_level(level, side_is_buy, bar_open):
    if side_is_buy:
        return bar_open if bar_open > level else level
    return bar_open if bar_open < level else level

def d34_trades():
    """zai_batch7 D34 on the current set_asset 1h frame: weekly BB squeeze → 10-day stop break, 3R, 7d."""
    D = resample(D1)
    ts = pd.to_datetime(D["time"].values, unit="ms", utc=True)
    df = D.copy(); df["ts"] = ts
    h, l = df.high.to_numpy(), df.low.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, d10l = rolling_max(h, 10), rolling_min(l, 10)
    # map daily signal onto the last 1h bar of each day (batch7 lift_pack)
    last_i = D["last_i"].values.astype(int)
    long = np.zeros(N, bool); short = np.zeros(N, bool)
    ent_l = np.full(N, np.nan); ent_s = np.full(N, np.nan)
    stp_l = np.full(N, np.nan); stp_s = np.full(N, np.nan)
    for di, li in enumerate(last_i):
        if 0 <= li < N and sq[di]:
            long[li] = short[li] = True
            ent_l[li], ent_s[li] = d10h[di], d10l[di]
            stp_l[li], stp_s[li] = d10l[di], d10h[di]
    return _stop_oco_bt(ent_l, ent_s, stp_l, stp_s, long, short, target_R=3, time_bars=7 * 24, src="D34")

def _stop_oco_bt(ent_l, ent_s, stp_l, stp_s, long, short, target_R=3, time_bars=7 * 24, src="D34"):
    trades = []; pos = None; pend_l = None; pend_s = None
    def close_pos(i, exit_raw, reason, pos_):
        e, side, stop = pos_["entry"], pos_["side"], pos_["stop"]
        move = side * (exit_raw / e - 1)
        risk = abs(e - stop) / e
        net = (move - 2 * COST) / risk if risk > 0 else np.nan
        trades.append(dict(src=src, side=int(side), t_in=int(T[pos_["ei"]]), t_out=int(T[i]),
                           entry=float(e), exit=float(exit_raw), stop=float(stop),
                           risk=float(risk), move=float(move), net_R=float(net) if np.isfinite(net) else np.nan,
                           weight=1.0, why=reason))
    def maybe_fill(i, pend, side):
        if pend is None:
            return None
        level, stop, expiry, setup_i = pend
        if i > expiry:
            return None
        hit = (Hh[i] >= level) if side > 0 else (L[i] <= level)
        if not hit:
            return pend
        fill = _fill_stop_level(level, side > 0, O[i])
        if side > 0 and L[i] <= stop:
            return None
        if side < 0 and Hh[i] >= stop:
            return None
        if not (np.isfinite(fill) and np.isfinite(stop)):
            return None
        if (side > 0 and stop >= fill) or (side < 0 and stop <= fill):
            return None
        r = abs(fill - stop) / fill
        if r < STOP_MIN:
            return None
        if r > STOP_CAP:
            stop = fill - side * STOP_CAP * fill
            r = abs(fill - stop) / fill
        tgt = fill + side * target_R * abs(fill - stop)
        return dict(side=side, ei=i, entry=float(fill), stop=float(stop), target=float(tgt), expiry=expiry)
    for i in range(N):
        if pos is not None:
            side, stop, tgt = pos["side"], pos["stop"], pos["target"]
            if side > 0:
                hit_s, hit_t = L[i] <= stop, Hh[i] >= tgt
                if hit_s:
                    close_pos(i, _fill_stop_level(stop, False, O[i]), "SL", pos); pos = None; continue
                if hit_t:
                    close_pos(i, _fill_stop_level(tgt, True, O[i]), "TP", pos); pos = None; continue
            else:
                hit_s, hit_t = Hh[i] >= stop, L[i] <= tgt
                if hit_s:
                    close_pos(i, _fill_stop_level(stop, True, O[i]), "SL", pos); pos = None; continue
                if hit_t:
                    close_pos(i, _fill_stop_level(tgt, False, O[i]), "TP", pos); pos = None; continue
            if i >= pos["expiry"]:
                close_pos(i, C[i], "time", pos); pos = None
            continue
        r1 = maybe_fill(i, pend_l, 1)
        if isinstance(r1, dict):
            pos = r1; pend_l = pend_s = None; continue
        if r1 is None:
            pend_l = None
        r2 = maybe_fill(i, pend_s, -1)
        if isinstance(r2, dict):
            pos = r2; pend_l = pend_s = None; continue
        if r2 is None:
            pend_s = None
        if long[i] and np.isfinite(ent_l[i]):
            pend_l = (float(ent_l[i]), float(stp_l[i]), min(N - 1, i + time_bars), i)
        if short[i] and np.isfinite(ent_s[i]):
            pend_s = (float(ent_s[i]), float(stp_s[i]), min(N - 1, i + time_bars), i)
    if pos is not None:
        close_pos(N - 1, C[-1], "eod", pos)
    return trades

def mom30_trades(bars_df):
    """Weighted-PnL wrap of the mom30.mjs port (partial 50% at tp1)."""
    bars = [dict(time=int(r.time), open=float(r.open), high=float(r.high),
                 low=float(r.low), close=float(r.close), volume=float(r.volume))
            for r in bars_df.itertuples(index=False)]
    P = dict(chop=30, atrLen=14, satrLen=20, mom=5, sl=1.8, tp1=2.0, tp2=3.0, tp1Frac=0.5, cap=0.10, minStop=0.015)
    B = []
    cur = None; k = -1
    for b in bars:
        g = int(b["time"] // H4)
        if g != k:
            if cur and cur["n"] == 4:
                B.append(cur)
            k = g
            cur = dict(time=g * H4, open=b["open"], high=b["high"], low=b["low"], close=b["close"], volume=b["volume"], n=1)
        else:
            cur["high"] = max(cur["high"], b["high"]); cur["low"] = min(cur["low"], b["low"])
            cur["close"] = b["close"]; cur["volume"] += b["volume"]; cur["n"] += 1
    if cur and cur["n"] == 4:
        B.append(cur)
    if len(B) < 40:
        return []
    # Wilder ATR / chop (same as mom30_ref)
    tr = np.zeros(len(B)); tr[0] = B[0]["high"] - B[0]["low"]
    for i in range(1, len(B)):
        pc = B[i - 1]["close"]; b = B[i]
        tr[i] = max(b["high"] - b["low"], abs(b["high"] - pc), abs(b["low"] - pc))
    atr = np.full(len(B), np.nan); v = np.nan; s = c = 0
    for i, x in enumerate(tr):
        if not np.isfinite(x):
            continue
        if np.isnan(v):
            s += x; c += 1
            if c == P["atrLen"]:
                v = s / P["atrLen"]; atr[i] = v
        else:
            v = (v * (P["atrLen"] - 1) + x) / P["atrLen"]; atr[i] = v
    satr = pd.Series(atr).rolling(P["satrLen"], min_periods=P["satrLen"]).mean().to_numpy()
    chop = np.full(len(B), np.nan)
    nch = P["atrLen"]
    for i in range(nch - 1, len(B)):
        sl = tr[i - nch + 1:i + 1]
        if not np.isfinite(sl).all():
            continue
        hi = max(B[j]["high"] for j in range(i - nch + 1, i + 1))
        lo = min(B[j]["low"] for j in range(i - nch + 1, i + 1))
        if hi > lo:
            chop[i] = 100 * math.log10(sl.sum() / (hi - lo)) / math.log10(nch)
    t1 = [b["time"] for b in bars]; n1 = len(bars)
    def at_time(t):
        lo, hi = 0, n1 - 1
        while lo < hi:
            m = (lo + hi + 1) >> 1
            if t1[m] <= t: lo = m
            else: hi = m - 1
        return lo
    trades = []; i = 0
    while i < len(B):
        a4, sa, ch = atr[i], satr[i], chop[i]
        sdir = 0
        if np.isfinite(a4) and np.isfinite(sa) and np.isfinite(ch) and i >= P["mom"]:
            cl, op, c5 = B[i]["close"], B[i]["open"], B[i - P["mom"]]["close"]
            if ch < P["chop"] and a4 > sa:
                if cl > c5 and cl > op: sdir = 1
                elif cl < c5 and cl < op: sdir = -1
        if not sdir:
            i += 1; continue
        ft = B[i]["time"] + H4
        j0 = at_time(ft)
        if t1[j0] != ft:
            i += 1; continue
        e = bars[j0]["open"]
        if not (np.isfinite(e) and e > 0):
            i += 1; continue
        raw_dist = P["sl"] * a4; raw_pct = raw_dist / e
        if raw_pct < P["minStop"]:
            i += 1; continue
        dist = min(raw_dist, P["cap"] * e)
        sl0 = e - sdir * dist
        tp1 = e + sdir * P["tp1"] * a4
        tp2 = e + sdir * P["tp2"] * a4
        sp, w, legs, stage, why = sl0, 1.0, [], 0, None
        def fill_stop(px, b):
            return min(px, b["open"]) if sdir > 0 else max(px, b["open"])
        def fill_tp(px, b):
            return max(px, b["open"]) if sdir > 0 else min(px, b["open"])
        closed = False
        for j in range(j0, n1):
            b = bars[j]
            hitS = b["low"] <= sp if sdir > 0 else b["high"] >= sp
            hit1 = stage == 0 and (b["high"] >= tp1 if sdir > 0 else b["low"] <= tp1)
            hit2 = b["high"] >= tp2 if sdir > 0 else b["low"] <= tp2
            if hitS:
                legs.append((w, fill_stop(sp, b), t1[j])); w = 0; why = "BE" if stage else "SL"; closed = True; break
            if stage == 0 and hit1:
                px1 = fill_tp(tp1, b)
                legs.append((P["tp1Frac"], px1, t1[j]))
                w = 1 - P["tp1Frac"]; stage = 1; sp = e
                if hit2:
                    legs.append((w, fill_tp(tp2, b), t1[j])); w = 0; why = "TP2"; closed = True; break
                continue
            if stage == 1 and hit2:
                legs.append((w, fill_tp(tp2, b), t1[j])); w = 0; why = "TP2"; closed = True; break
        if not closed or not legs:
            break
        move = sum(ww * sdir * (px / e - 1) for ww, px, _ in legs)
        risk = abs(e - sl0) / e
        net = (move - 2 * COST) / risk if risk > 0 else np.nan
        trades.append(dict(src="MOM30", side=int(sdir), t_in=int(t1[j0]), t_out=int(legs[-1][2]),
                           entry=float(e), exit=float(legs[-1][1]), stop=float(sl0),
                           risk=float(risk), move=float(move), net_R=float(net) if np.isfinite(net) else np.nan,
                           weight=1.0, why=why))
        tEnd = legs[-1][2] + H1
        ii = i + 1
        while ii < len(B) and B[ii]["time"] + H4 < tEnd:
            ii += 1
        i = ii
    return trades

def _finite(x):
    try:
        return x is not None and np.isfinite(x)
    except TypeError:
        return False

def _as_trade(src, side, t_in, t_out, entry, exit_px, stop, move=None, risk=None, net_R=None, why=""):
    if risk is None or not _finite(risk) or risk <= 0:
        if _finite(entry) and entry > 0 and _finite(stop):
            risk = abs(entry - stop) / entry
        else:
            return None
    if move is None or not _finite(move):
        if not (_finite(entry) and entry > 0 and _finite(exit_px)):
            return None
        move = side * (exit_px / entry - 1)
    if net_R is None or not _finite(net_R):
        net_R = (move - 2 * COST) / risk if risk > 0 else np.nan
    if not _finite(entry) or entry <= 0:
        entry = 1.0
        exit_px = 1.0 + (move if side >= 0 else -move)
        stop = 1.0 - side * risk
    return dict(src=src, side=int(side), t_in=int(t_in), t_out=int(t_out),
                entry=float(entry), exit=float(exit_px) if _finite(exit_px) else np.nan,
                stop=float(stop) if _finite(stop) else np.nan,
                risk=float(risk), move=float(move), net_R=float(net_R) if _finite(net_R) else np.nan,
                weight=1.0, why=why)

def trades_from_run(src, res):
    t = res["trades"]; out = []
    if t is None or not len(t):
        return out
    for r in t.itertuples(index=False):
        tr = _as_trade(src, r.side, r.t_in, r.t_out, None, None, None, move=r.move, risk=r.risk, why="")
        # entry is unknown here; reconstruct from risk + stop distance is not needed for R/basket
        if tr:
            # recover a dummy entry of 1.0 so later code can recompute frac from risk/move only
            tr["entry"] = 1.0; tr["exit"] = 1.0 + r.move if r.side > 0 else 1.0 - r.move
            tr["stop"] = 1.0 - r.side * r.risk
            out.append(tr)
    return out

def trades_from_tuples(src, rows):
    out = []
    for x in rows:
        # (t_in, t_out, side, ret, kind, move, risk)
        t_in, t_out, side, ret, kind, move, risk = x
        tr = _as_trade(src, side, t_in, t_out, 1.0, 1.0 + side * move if side else np.nan,
                       1.0 - side * risk if risk else np.nan, move=move, risk=risk, why=str(kind))
        if tr:
            out.append(tr)
    return out

def trades_from_c12(src, rows):
    out = []
    for t in rows:
        tr = _as_trade(src, t["side"], t["t_in"], t["t_out"], t.get("entry"), t.get("exit", t.get("entry")),
                       t.get("stop"), move=t.get("move"), risk=t.get("risk"), net_R=t.get("net_R"), why=t.get("why", ""))
        if tr:
            out.append(tr)
    return out

def trades_from_r0(rows):
    out = []
    for t in rows:
        ei, xi = t["ei"], t["xi"]
        tr = _as_trade("R0", t["side"], T[ei], T[xi], t["entry"], t["exit"], t["stop"], why=t.get("why", ""))
        if tr:
            out.append(tr)
    return out

# ==== tail2.py ====
# ---------------------------------------------------------------------------
# Run all live engines on the current 1h frame
# ---------------------------------------------------------------------------
def run_engines(d_1h, fund=None):
    global STOP_RULE, CHAND
    set_asset(d_1h)
    D = build_day(fund)
    D = market_states(D)
    CHAND = to_base(D, D["atr"].values, D1)
    out = {}
    prev = STOP_RULE
    STOP_RULE = ("cap", 0.10)
    try:
        k8 = k8_system(D)
        out["K8"] = trades_from_run("K8", run("K8", k8["sig"], k8["stop"],
                                              exitL=k8["dir"] < 0, exitS=k8["dir"] > 0,
                                              allow=k8_allow(k8, k8["sig"])))
        out["V7"] = trades_from_run("V7", run("V7", v7_system(D), 0.10 * C,
                                              trail_start=0.20, trail_drop=0.15))
        S5P, B1P = s5_b1(D)
        out["S5"] = trades_from_run("S5", run("S5", S5P["sig"], S5P["stop_dist"],
                                              chand_atr=S5P["chand_atr"], chand_mult=3.0, max_hold=S5P["max_hold"]))
        out["B1G"] = trades_from_run("B1G", run("B1G", B1P["sig"], B1P["stop_dist"],
                                               chand_atr=B1P["chand_atr"], chand_mult=3.0, max_hold=B1P["max_hold"]))
        S = coil_setups(D, dict(N=7, M=10))
        out["COCO"] = trades_from_tuples("COCO", sys_coco(S, 3.0))
    finally:
        STOP_RULE = prev
    Dn = _norm_d(d_1h)
    out["C1"] = trades_from_c12("C1", _c1_trades(Dn))
    out["C2"] = trades_from_c12("C2", c2_trades(Dn))
    out["R0"] = trades_from_r0(osom_r0(d_1h))
    out["MOM30"] = mom30_trades(d_1h)
    out["D34"] = d34_trades()
    return out, D

# ---------------------------------------------------------------------------
# Daily calendar + A1 / A2 state labels
# ---------------------------------------------------------------------------
def daily_index(D):
    """Completed 1D bars with time = day start (ms)."""
    t = D["time"].values.astype("int64")
    return t, pd.to_datetime(t, unit="ms", utc=True)

def kaufman_er(c, n=10):
    num = np.abs(pd.Series(c).diff(n))
    den = pd.Series(c).diff().abs().rolling(n, min_periods=n).sum()
    return (num / den.replace(0, np.nan)).to_numpy()

def label_A1(D):
    h, l, c = D.high.values, D.low.values, D.close.values
    adx14, _, _ = adx(h, l, c, 14)
    er10 = kaufman_er(c, 10)
    adx_s = pd.Series(adx14).rolling(3, min_periods=3).mean().to_numpy()
    er_s = pd.Series(er10).rolling(3, min_periods=3).mean().to_numpy()
    a14 = atr(h, l, c, 14)
    a100 = atr(h, l, c, 100)
    ratio = a14 / np.where(a100 > 0, a100, np.nan)
    st = np.full(len(D), "OTHER", dtype=object)
    exp = np.isfinite(ratio) & (ratio >= 1.5)
    # TREND / RANGE / CHOP on the non-override bars first, then EXPANSION override
    trend = (adx_s >= 25) & (er_s >= 0.30)
    rng = (adx_s < 20) & (er_s < 0.15)
    chop = (adx_s < 20) & (er_s >= 0.15)
    st[np.isfinite(adx_s) & np.isfinite(er_s) & trend] = "TREND"
    st[np.isfinite(adx_s) & np.isfinite(er_s) & rng] = "RANGE"
    st[np.isfinite(adx_s) & np.isfinite(er_s) & chop] = "CHOP"
    st[exp] = "EXPANSION"
    return st, dict(adx=adx_s, er=er_s, atr_ratio=ratio)

def label_A2(D):
    h, l, c = D.high.values, D.low.values, D.close.values
    a14 = atr(h, l, c, 14)
    a100 = atr(h, l, c, 100)
    Dv = a14 / np.where(a100 > 0, a100, np.nan)
    # weekly BB(20,2) width, percentile vs trailing 3y (~156 weeks)
    ts = pd.to_datetime(D["time"].values, unit="ms", utc=True)
    w = pd.DataFrame({"open": D.open.values, "high": h, "low": l, "close": c}, index=ts)
    weekly = w.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)
    wpct = pd.Series(wbw, index=weekly.index).rolling(156, min_periods=52).rank(pct=True) * 100.0
    # map last completed week onto each daily bar (week row at Monday M is known at M+7)
    w_pct_d = np.full(len(D), np.nan)
    if len(weekly):
        w_idx = weekly.index
        w_val = wpct.to_numpy()
        # for a daily bar at t, use the last weekly row with (index + 7d) <= t  (completed week)
        known = w_idx + pd.Timedelta(days=7)
        ki = known.asi8 if hasattr(known, "asi8") else pd.DatetimeIndex(known).asi8
        di = ts.asi8
        j = np.searchsorted(ki, di, side="right") - 1
        ok = j >= 0
        w_pct_d[ok] = w_val[np.clip(j[ok], 0, len(w_val) - 1)]
    st = np.full(len(D), "NORMAL", dtype=object)
    coil = np.isfinite(w_pct_d) & np.isfinite(Dv) & (w_pct_d <= 15) & (Dv <= 1.0)
    exp = (np.isfinite(w_pct_d) & (w_pct_d >= 80)) | (np.isfinite(Dv) & (Dv >= 1.6))
    st[np.isfinite(w_pct_d) | np.isfinite(Dv)] = "NORMAL"
    st[coil] = "COIL"
    st[exp & ~coil] = "EXPANSION"
    return st, dict(w_pct=w_pct_d, D=Dv)


# ---------------------------------------------------------------------------
# Batch 11: TradeSpec collection, 1h path walker, paired A/B, cards, stack
# ---------------------------------------------------------------------------

def t_to_i(t):
    i = int(np.searchsorted(T, int(t), side="left"))
    if 0 <= i < N and int(T[i]) == int(t):
        return i
    return None


def make_spec(src, side, ei, entry, stop0, risk, kind, atr_entry=np.nan,
              tp1=np.nan, tp2=np.nan, tp1_frac=0.0, be_at_tp1=False,
              max_hold=HOLD_MAX, chand_k=0.0, v7=False, cap_r=np.nan,
              time_stop=None, fill_bar_stopentry=False):
    if not (np.isfinite(entry) and entry > 0 and np.isfinite(risk) and risk > 0 and ei is not None):
        return None
    if not np.isfinite(stop0):
        stop0 = entry - side * risk * entry
    return dict(
        src=src, side=int(side), ei=int(ei), t_in=int(T[int(ei)]),
        entry=float(entry), stop0=float(stop0), risk=float(risk),
        kind=kind, atr_entry=float(atr_entry) if np.isfinite(atr_entry) else float("nan"),
        tp1=float(tp1) if np.isfinite(tp1) else float("nan"),
        tp2=float(tp2) if np.isfinite(tp2) else float("nan"),
        tp1_frac=float(tp1_frac or 0.0), be_at_tp1=bool(be_at_tp1),
        max_hold=int(max_hold if max_hold is not None else HOLD_MAX),
        chand_k=float(chand_k or 0.0), v7=bool(v7),
        cap_r=float(cap_r) if np.isfinite(cap_r) else float("nan"),
        time_stop=int(time_stop) if time_stop else None,
        fill_bar_stopentry=bool(fill_bar_stopentry),
        tid=f"{src}|{int(T[int(ei)])}|{int(side)}|{int(ei)}",
        a2="NORMAL",
    )


def specs_from_run(src, res, kind, max_hold=HOLD_MAX, chand_k=0.0, v7=False):
    out = []
    t = res["trades"]
    if t is None or not len(t):
        return out
    for r in t.itertuples():
        ei = int(r.i_in)
        entry = float(O[ei]); side = int(r.side); risk = float(r.risk)
        sp = make_spec(src, side, ei, entry, entry - side * risk * entry, risk,
                       kind=kind, max_hold=max_hold, chand_k=chand_k, v7=v7,
                       atr_entry=abs(entry - (entry - side * risk * entry)))
        if sp:
            out.append(sp)
    return out


def collect_coco_specs(S, trail):
    """Baseline sim_leg decides the one re-arm; each booked entry is its own TradeSpec."""
    out = []
    for s in S:
        bh, bl, A = s["bh"], s["bl"], s["A"]; i = s["i0"]; i1 = s["i1"]
        side = 0
        while i <= i1:
            side = first_touch(i, bh, bl)
            if side:
                break
            i += 1
        if not side:
            continue
        e_prev_px = np.nan
        for attempt in range(2):
            e = max(O[i], bh) if side > 0 else min(O[i], bl)
            if attempt == 1:
                e = max(e_prev_px, bh) if side > 0 else min(e_prev_px, bl)
            stp = bl if side > 0 else bh
            if side * (e - stp) <= 0:
                stp = e - side * 0.5 * A
            r = sim_leg(i, side, e, stp, np.nan, trail, None, fill_bar_stopentry=True, chand=CHAND)
            if r is None:
                break
            j, px, kind, frac, s0 = r
            risk = abs(e - s0) / e if e else np.nan
            sp = make_spec("COCO", side, i, e, s0, risk, kind="coco", atr_entry=float(A),
                           max_hold=MAX_HOLD, chand_k=float(trail), fill_bar_stopentry=True)
            if sp:
                out.append(sp)
            if not (kind == "stop" and j <= i1):
                break
            side = -side; k = j; e_prev_px = px; found = False
            while k <= i1:
                if (side > 0 and Hh[k] >= bh) or (side < 0 and L[k] <= bl):
                    found = True; break
                k += 1
            if not found:
                break
            if k > j:
                e_prev_px = O[k]
            i = k
    return out


def collect_c1_specs(Dn):
    p = C1_DEFAULTS
    out = []
    for t in _c1_trades(Dn):
        ei, entry, stop, side = t.get("ei"), t["entry"], t["stop"], t["side"]
        if ei is None:
            ei = t_to_i(t["t_in"])
        if ei is None:
            continue
        M = abs(entry - stop) / p["sl"] if p["sl"] else np.nan
        sp = make_spec("C1", side, ei, entry, stop, abs(entry - stop) / entry, kind="c1",
                       atr_entry=M, tp1=entry + side * p["tp1"] * M, tp2=entry + side * p["tp2"] * M,
                       tp1_frac=p["tp1Frac"], be_at_tp1=True)
        if sp:
            out.append(sp)
    return out


def collect_c2_specs(Dn):
    out = []
    for t in c2_trades(Dn):
        ei = t_to_i(t["t_in"])
        if ei is None:
            continue
        entry, stop, side = t["entry"], t["stop"], t["side"]
        M = abs(entry - stop) / 1.5
        sp = make_spec("C2", side, ei, entry, stop, abs(entry - stop) / entry, kind="c2",
                       atr_entry=M, tp2=entry + side * 3.0 * M)
        if sp:
            out.append(sp)
    return out


def collect_mom30_specs(d):
    rows = mom30_trades(d)
    t, o, h, l, c, v = d["time"].values, d["open"].values, d["high"].values, d["low"].values, d["close"].values, d["volume"].values
    B = bucket_ohlcv(t, o, h, l, c, v, 4, complete_only=True)
    atrb = rma_seeded(tr_arr(B["high"], B["low"], B["close"]), 14)
    t2a = {int(B["time"][i] + H4): float(atrb[i]) for i in range(len(B["time"])) if np.isfinite(atrb[i])}
    out = []
    for trow in rows:
        ei = t_to_i(trow["t_in"])
        if ei is None:
            continue
        entry, stop, side = trow["entry"], trow["stop"], trow["side"]
        a4 = t2a.get(int(trow["t_in"]))
        if a4 is None or not np.isfinite(a4) or a4 <= 0:
            a4 = abs(entry - stop) / 1.8
        sp = make_spec("MOM30", side, ei, entry, stop, abs(entry - stop) / entry, kind="mom30",
                       atr_entry=a4, tp1=entry + side * 2.0 * a4, tp2=entry + side * 3.0 * a4,
                       tp1_frac=0.5, be_at_tp1=True)
        if sp:
            out.append(sp)
    return out


def collect_r0_specs(d):
    out = []
    for t in osom_r0(d):
        ei = t["ei"]
        entry, stop, side = t["entry"], t["stop"], t["side"]
        risk = abs(entry - stop) / entry if entry else np.nan
        sp = make_spec("R0", side, ei, entry, stop, risk, kind="r0",
                       atr_entry=abs(entry - stop), max_hold=10 * 24)
        if sp:
            out.append(sp)
    return out


def collect_d34_specs():
    rows = d34_trades()
    out = []
    for t in rows:
        ei = t_to_i(t["t_in"])
        if ei is None:
            continue
        entry, stop, side = t["entry"], t["stop"], t["side"]
        risk = abs(entry - stop) / entry if entry else np.nan
        sp = make_spec("D34", side, ei, entry, stop, risk, kind="d34",
                       atr_entry=abs(entry - stop), cap_r=3.0, time_stop=7 * 24,
                       tp2=entry + side * 3.0 * abs(entry - stop), max_hold=7 * 24)
        if sp:
            out.append(sp)
    return out


def collect_specs(d_1h, fund=None):
    """Generate the fixed entry set (baseline engine exits decide one-at-a-time sequencing)."""
    global STOP_RULE, CHAND
    set_asset(d_1h)
    D = build_day(fund)
    D = market_states(D)
    CHAND = to_base(D, D["atr"].values, D1)
    specs = []
    k8dir = np.zeros(N, dtype=float)
    prev = STOP_RULE
    STOP_RULE = ("cap", 0.10)
    try:
        k8 = k8_system(D)
        k8dir = np.asarray(k8["dir"], dtype=float)
        specs += specs_from_run("K8", run("K8", k8["sig"], k8["stop"],
                                          exitL=k8["dir"] < 0, exitS=k8["dir"] > 0,
                                          allow=k8_allow(k8, k8["sig"])), kind="k8")
        specs += specs_from_run("V7", run("V7", v7_system(D), 0.10 * C,
                                          trail_start=0.20, trail_drop=0.15), kind="v7", v7=True)
        S5P, B1P = s5_b1(D)
        specs += specs_from_run("S5", run("S5", S5P["sig"], S5P["stop_dist"],
                                          chand_atr=S5P["chand_atr"], chand_mult=3.0,
                                          max_hold=S5P["max_hold"]),
                                kind="s5", max_hold=S5P["max_hold"], chand_k=3.0)
        specs += specs_from_run("B1G", run("B1G", B1P["sig"], B1P["stop_dist"],
                                           chand_atr=B1P["chand_atr"], chand_mult=3.0,
                                           max_hold=B1P["max_hold"]),
                                kind="b1g", max_hold=B1P["max_hold"], chand_k=3.0)
        S = coil_setups(D, dict(N=7, M=10))
        specs += collect_coco_specs(S, 3.0)
    finally:
        STOP_RULE = prev
    Dn = _norm_d(d_1h)
    specs += collect_c1_specs(Dn)
    specs += collect_c2_specs(Dn)
    specs += collect_r0_specs(d_1h)
    specs += collect_mom30_specs(d_1h)
    specs += collect_d34_specs()
    F = make_frame(D, k8dir)
    for sp in specs:
        sp["a2"] = a2_at(F, sp["ei"])
    return specs, F, D


def make_frame(D, k8dir):
    H4B = resample(H4)
    atr4 = to_base(H4B, atr(H4B.high.values, H4B.low.values, H4B.close.values, 14), H4)
    atrd20 = to_base(D, D["atr"].values, D1)
    close_4h = ((T + H1) % H4) == 0
    close_d = ((T + H1) % D1) == 0
    a2, a2m = label_A2(D)
    last_i = D["last_i"].values.astype(int)
    # expiry session offset relative to last-Friday 08:00 UTC (date difference in UTC days)
    t0 = int(T[0]); t1 = int(T[-1])
    start = pd.Timestamp(t0, unit="ms", tz="UTC").strftime("%Y-%m-%d")
    end = pd.Timestamp(t1, unit="ms", tz="UTC").strftime("%Y-%m-%d")
    exps = last_friday_expiries(start, end)
    # day_ms -> (best offset, quarterly flag) for bars in [-7, +3] of some expiry
    exp_map = {}
    for ts in exps:
        ed = int(pd.Timestamp(year=ts.year, month=ts.month, day=ts.day, tz="UTC").value // 1_000_000)
        q = ts.month in (3, 6, 9, 12)
        for off in range(-7, 4):
            day = ed + off * D1
            prev = exp_map.get(day)
            if prev is None or abs(off) < abs(prev[0]):
                exp_map[day] = (off, q)
    exp_off = np.full(N, np.nan)
    exp_q = np.zeros(N, dtype=bool)
    day_key = (T // D1) * D1
    for i in range(N):
        rec = exp_map.get(int(day_key[i]))
        if rec is not None:
            exp_off[i] = rec[0]
            exp_q[i] = rec[1]
    kd = np.zeros(N, dtype=float)
    if k8dir is not None and len(k8dir) == N:
        kd = np.asarray(k8dir, dtype=float)
    return dict(atr4=atr4, atrd20=atrd20, close_4h=close_4h, close_d=close_d,
                a2=a2, a2m=a2m, last_i=last_i, exp_off=exp_off, exp_q=exp_q,
                k8dir=kd, D=D,
                # FIX (batch11 v2): the frame owns its asset's price arrays. walk_spec reads the
                # module globals O/Hh/L/C/T/N; v1 left them pointing at whichever asset was
                # collected LAST (ETH), so every BTC variant walked BTC entries over ETH prices.
                px=dict(df=df, N=N, O=O, Hh=Hh, L=L, C=C, V=V, T=T, BAR=BAR, BPD=BPD))


def use_frame(F):
    """Point the module-level price arrays at F's asset before any path walk."""
    global df, N, O, Hh, L, C, V, T, BAR, BPD
    px = F["px"]
    df, N, O, Hh, L, C, V, T, BAR, BPD = (px[k] for k in ("df", "N", "O", "Hh", "L", "C", "V", "T", "BAR", "BPD"))


def a2_at(F, ei):
    last_i = F["last_i"]
    j = int(np.searchsorted(last_i, ei, side="left")) - 1
    if j < 0 or j >= len(F["a2"]):
        return "NORMAL"
    return str(F["a2"][j])


class Pol:
    """Exit policy. Missing fields mean 'use the engine's current exit'."""

    def __init__(self, name="baseline", x1_thr=None, x1_n=12,
                 be_mode="baseline", be_trig=1.5, be_buf=0.1,
                 q1=None, z2=None, t1k=None):
        self.name = name
        self.x1_thr = x1_thr          # R threshold or None
        self.x1_n = x1_n              # 4H bars (K8 always uses 6 daily sessions)
        self.be_mode = be_mode        # baseline | off | rule
        self.be_trig = be_trig
        self.be_buf = be_buf
        self.q1 = q1                  # dict(split, chand, trig) or None
        self.z2 = z2                  # dict(lo, hi, tighten) or None
        self.t1k = t1k                # chandelier k or None

    def copy(self, name=None, **kw):
        d = dict(name=name or self.name, x1_thr=self.x1_thr, x1_n=self.x1_n,
                 be_mode=self.be_mode, be_trig=self.be_trig, be_buf=self.be_buf,
                 q1=None if self.q1 is None else dict(self.q1),
                 z2=None if self.z2 is None else dict(self.z2),
                 t1k=self.t1k)
        d.update(kw)
        return Pol(**d)


BASE_POL = Pol(name="baseline")


def _fill_stop(side, stop, o, first, fill_bar_stopentry):
    if first and fill_bar_stopentry:
        return float(stop)
    return float(min(o, stop) if side > 0 else max(o, stop))


def _fill_tp(side, level, o):
    return float(max(o, level) if side > 0 else min(o, level))


def walk_spec(sp, pol, F):
    """Walk one TradeSpec under a policy. Returns a result dict (tid-aligned)."""
    side = sp["side"]; entry = sp["entry"]; stop = float(sp["stop0"])
    risk = sp["risk"]; ei = sp["ei"]; src = sp["src"]
    rpx = risk * entry
    atr_e = sp["atr_entry"] if np.isfinite(sp["atr_entry"]) and sp["atr_entry"] > 0 else rpx
    tp1, tp2 = sp["tp1"], sp["tp2"]
    tp1_frac = sp["tp1_frac"]
    w = 1.0
    realized = 0.0
    cost = COST
    ext = entry
    best_c = entry
    stage = 0
    t1_on = False
    q1_on = False
    be_rule_on = False
    x1_fired = False
    z2_part = False
    why = "eod"
    xo = N - 1
    xp = float(C[-1])
    end = min(N - 1, ei + int(sp["max_hold"]))
    if sp["time_stop"] is not None:
        end = min(end, ei + int(sp["time_stop"]))
    n4 = 0
    nd = 0
    close_4h, close_d = F["close_4h"], F["close_d"]
    atr4, atrd20 = F["atr4"], F["atrd20"]
    k8dir = F["k8dir"]
    exp_off = F["exp_off"]
    pend_exit = False
    pend_why = None
    cap_r = sp["cap_r"]
    if pol.q1 is not None and src in Q1_ENG:
        cap_r = np.nan  # Q1 replaces D34's 3R cap
        tp2 = np.nan

    def book(frac, px, i, tag):
        nonlocal w, realized, cost, why, xo, xp, exit_gap
        if frac <= 0:
            return
        exit_gap = bool(gap_bar) and i > ei
        realized += frac * side * (px / entry - 1.0)
        cost += COST * frac * (px / entry)
        w -= frac
        why = tag
        xo, xp = i, px

    def in_z2(i):
        if pol.z2 is None or src not in Z2_ENG:
            return False
        off = exp_off[i]
        return np.isfinite(off) and pol.z2["lo"] <= off <= pol.z2["hi"]

    gap_bar = False
    exit_gap = False
    for i in range(ei, end + 1):
        o, h, l, c = O[i], Hh[i], L[i], C[i]
        first = (i == ei)
        # this bar opened through the current stop (only possible after the entry bar)
        gap_bar = (not first) and bool((o <= stop) if side > 0 else (o >= stop))
        if pend_exit and not first:
            book(w, o, i, pend_why or "time")
            w = 0
            break

        # ---- stop first (intrabar) ----
        hit_stop = (l <= stop) if side > 0 else (h >= stop)
        if hit_stop:
            book(w, _fill_stop(side, stop, o, first, sp["fill_bar_stopentry"]), i,
                 "X1" if x1_fired else ("BE" if (be_rule_on or stage) and abs(stop - entry) / entry < 0.002 else "SL"))
            w = 0
            break

        # unrealized R on the favourable extreme this bar
        ext_px = h if side > 0 else l
        ur_hi = side * (ext_px / entry - 1.0) / risk
        ur_c = side * (c / entry - 1.0) / risk

        # BE1 rule (full remaining position)
        if (pol.be_mode == "rule" and src in BE1_ENG and not be_rule_on
                and np.isfinite(pol.be_trig) and ur_hi >= pol.be_trig):
            buf = (pol.be_buf if np.isfinite(pol.be_buf) else 0.0) * atr_e
            ns = entry + side * buf
            stop = max(stop, ns) if side > 0 else min(stop, ns)
            be_rule_on = True
            # same-bar stop at the new BE?
            hit_be = (l <= stop) if side > 0 else (h >= stop)
            if hit_be:
                book(w, _fill_stop(side, stop, o, False, False), i, "BE")
                w = 0
                break

        # Z2 accelerated partial at +1R while in the expiry window
        z2_now = in_z2(i)
        if (pol.z2 is not None and src in Z2_ENG and not z2_part and z2_now and ur_hi >= 1.0 and w > 0):
            frac = tp1_frac if tp1_frac > 0 else 0.30
            lvl = entry + side * 1.0 * rpx
            book(min(w, frac), _fill_tp(side, lvl, o), i, "Z2")
            z2_part = True
            if tp1_frac > 0 and stage == 0:
                stage = 1
                if sp["be_at_tp1"] and pol.be_mode == "baseline":
                    stop = entry
            if w <= 1e-15:
                w = 0
                break

        # engine TP1 (C1 / MOM30), skipped if Z2 already took the partial this trade
        if stage == 0 and tp1_frac > 0 and np.isfinite(tp1) and not z2_part:
            hit1 = (h >= tp1) if side > 0 else (l <= tp1)
            if hit1:
                book(min(w, tp1_frac), _fill_tp(side, tp1, o), i, "TP1")
                stage = 1
                if sp["be_at_tp1"] and (pol.be_mode == "baseline" or src == "MOM30"):
                    # C1: only in baseline mode; MOM30: remainder-to-entry is the existing partial mechanic
                    if src == "MOM30" or pol.be_mode == "baseline":
                        stop = entry
                if src == "C1" and pol.be_mode == "baseline":
                    stop = entry
                if pol.t1k is not None and src == "C1":
                    t1_on = True
                    tp2 = np.nan
                if w <= 1e-15:
                    w = 0
                    break
                # same-bar BE after TP1
                hit_be = (l <= stop) if side > 0 else (h >= stop)
                if hit_be and i > ei:
                    book(w, _fill_stop(side, stop, o, False, False), i, "BE")
                    w = 0
                    break

        # T1 activation for C2 at +1.5R
        if pol.t1k is not None and src == "C2" and not t1_on and ur_hi >= 1.5:
            t1_on = True
            tp2 = np.nan

        # C1 T1 also if TP1 already taken on a prior bar
        if pol.t1k is not None and src == "C1" and stage >= 1:
            t1_on = True
            tp2 = np.nan

        # Q1 trigger
        if pol.q1 is not None and src in Q1_ENG and not q1_on and ur_hi >= pol.q1["trig"] and w > 0:
            frac = float(pol.q1["split"])
            lvl = entry + side * pol.q1["trig"] * rpx
            book(min(w, frac), _fill_tp(side, lvl, o), i, "Q1")
            q1_on = True
            ns = entry + side * 0.3 * rpx  # BE + 0.3R
            stop = max(stop, ns) if side > 0 else min(stop, ns)
            if w <= 1e-15:
                w = 0
                break
            hit_be = (l <= stop) if side > 0 else (h >= stop)
            if hit_be:
                book(w, _fill_stop(side, stop, o, False, False), i, "BE")
                w = 0
                break

        # far target (disabled once T1 / Q1 runner is on, or Q1 policy on D34)
        far = tp2
        if t1_on or q1_on:
            far = np.nan
        if np.isfinite(cap_r) and not q1_on and not t1_on:
            far_cap = entry + side * cap_r * rpx
            if not np.isfinite(far):
                far = far_cap
        if np.isfinite(far):
            hit_f = (h >= far) if side > 0 else (l <= far)
            if hit_f:
                book(w, _fill_tp(side, far, o), i, "TP2" if stage else "TP")
                w = 0
                break

        # ---- close: update extremes and trails ----
        ext = max(ext, h) if side > 0 else min(ext, l)
        best_c = max(best_c, c) if side > 0 else min(best_c, c)
        tight = 1.0
        if z2_now and pol.z2 is not None and (t1_on or q1_on or sp["chand_k"]):
            tight = float(pol.z2["tighten"])

        chand_k = 0.0
        atrv = np.nan
        if t1_on and pol.t1k is not None:
            chand_k = float(pol.t1k)
            atrv = atr4[i]
        elif q1_on and pol.q1 is not None:
            chand_k = float(pol.q1["chand"])
            atrv = atrd20[i]
        elif sp["chand_k"]:
            chand_k = float(sp["chand_k"])
            atrv = atrd20[i]
        if chand_k and np.isfinite(atrv) and atrv > 0:
            ns = ext - side * chand_k * tight * atrv
            stop = max(stop, ns) if side > 0 else min(stop, ns)

        # X1 dead-trade clock at 4H close (or 6 daily sessions for K8)
        if pol.x1_thr is not None and src in X1_ENG and w > 0:
            if src == "K8":
                if close_d[i]:
                    nd += 1
                    if nd == 6:
                        if ur_c < pol.x1_thr:
                            book(w, float(c), i, "X1")
                            x1_fired = True
                            w = 0
                            break
            else:
                if close_4h[i]:
                    n4 += 1
                    if n4 == int(pol.x1_n):
                        if ur_c < pol.x1_thr:
                            book(w, float(c), i, "X1")
                            x1_fired = True
                            w = 0
                            break

        # V7 retrace: 20% run then 15% drop from best close — exit next open
        if sp["v7"] and w > 0:
            run_ = side * (best_c / entry - 1.0)
            if run_ >= 0.20 and abs(best_c - c) / best_c >= 0.15 and side * (c - best_c) < 0:
                pend_exit = True
                pend_why = "trail"
                continue

        # K8 direction flip — exit next open
        if sp["kind"] == "k8" and w > 0 and i < N:
            d = k8dir[i]
            if (side > 0 and d < 0) or (side < 0 and d > 0):
                pend_exit = True
                pend_why = "flip"
                continue

        if i == end and w > 0:
            book(w, float(c), i, "time")
            w = 0
            break

    if w > 1e-15:
        book(w, float(C[min(end, N - 1)]), min(end, N - 1), "eod")
    net_R = (realized - cost) / risk if risk > 0 else np.nan
    return dict(tid=sp["tid"], src=src, side=side, t_in=sp["t_in"], t_out=int(T[xo]),
                entry=entry, exit=xp, stop=sp["stop0"], risk=risk, net_R=float(net_R),
                why=why, weight=1.0, ei=ei, xi=int(xo), x1=bool(x1_fired),
                gap=bool(exit_gap),
                gross_R=float(realized / risk) if risk > 0 else np.nan,
                q1=bool(q1_on), z2=bool(z2_part), t1=bool(t1_on), be=bool(be_rule_on),
                a2=sp.get("a2", "NORMAL"))


class SanityError(AssertionError):
    pass


_ALIGN_NOTED = set()


def check_alignment(specs, F, label=""):
    """Every spec's entry time must be the bar at its index in F's own price series, and the entry
    price must sit inside (or within 1% of) that bar. Catches BTC/ETH mix-ups and index/unit slips."""
    Tf = F["px"]["T"]; Of = F["px"]["O"]; Hf = F["px"]["Hh"]; Lf = F["px"]["L"]; Nf = F["px"]["N"]
    bad_t = [sp["tid"] for sp in specs if not (0 <= sp["ei"] < Nf) or int(Tf[sp["ei"]]) != int(sp["t_in"])]
    if bad_t:
        raise SanityError(f"[{label}] {len(bad_t)}/{len(specs)} specs do not line up with this asset's bars "
                          f"(e.g. {bad_t[:3]}) — wrong price series or index")
    out = [sp["tid"] for sp in specs
           if not (Lf[sp["ei"]] * 0.99 <= sp["entry"] <= Hf[sp["ei"]] * 1.01)]
    key = (id(specs), len(specs), len(out))
    if out and key not in _ALIGN_NOTED:
        _ALIGN_NOTED.add(key)
        print(f"  note [{label}]: {len(out)}/{len(specs)} entries sit >1% outside their entry bar", flush=True)
    if len(out) > max(2, 0.25 * len(specs)):
        raise SanityError(f"[{label}] {len(out)}/{len(specs)} entries lie outside their entry bar's range "
                          f"(e.g. {out[:3]}) — wrong price series")
    return len(out)


def r_sanity(rows, label=""):
    """No trade may lose more than 1.5R unless its exit bar gapped through the stop.
    Fees alone can push net R below -1.5 on a very tight stop, so a trade whose price-only R is
    >= -1.0 (it left at/inside its stop) is not a violation."""
    bad = [r for r in rows if _fin(r.get("net_R")) and r["net_R"] < -1.5 and not r.get("gap")
           and not (_fin(r.get("gross_R")) and r["gross_R"] >= -1.0 - 1e-9)]
    if bad:
        ex = "; ".join(f"{r['tid']} R={r['net_R']:.2f} why={r['why']}" for r in bad[:5])
        raise SanityError(f"[{label}] {len(bad)} trades below -1.5R without a gap through the stop: {ex}")
    return True


def walk_all(specs, pol, F, label=None):
    use_frame(F)
    check_alignment(specs, F, label or getattr(pol, "name", ""))
    rows = [walk_spec(sp, pol, F) for sp in specs]
    r_sanity(rows, f"{label or ''} {getattr(pol, 'name', '')}".strip())
    return rows


def identity_check(label, specs, F, base_rows):
    """A no-op exit policy, run through the same variant path as every card, must reproduce the
    baseline per-trade R exactly. Run AFTER both assets are collected (the v1 bug only shows then)."""
    ident = BASE_POL.copy(name="identity")
    var = run_variant(specs, F, ident)
    b, v, ids = pair_maps(base_rows, var)
    if len(ids) != len(base_rows) or len(var) != len(base_rows):
        raise SanityError(f"IDENTITY FAILED on {label}: trade sets differ ({len(base_rows)} vs {len(var)})")
    d = np.array([v[t]["net_R"] - b[t]["net_R"] for t in ids], float)
    d = np.where(np.isfinite(d), d, np.inf)
    mx = float(np.max(np.abs(d))) if len(d) else 0.0
    print(f"  identity {label}: n={len(ids)}  max|dR|={mx:.2e}  {'OK' if mx < 1e-9 else 'FAIL'}", flush=True)
    if not mx < 1e-9:
        raise SanityError(f"IDENTITY FAILED on {label}: max|dR|={mx} — variant path does not reproduce baseline")
    return mx


def pair_maps(base_rows, var_rows):
    b = {r["tid"]: r for r in base_rows}
    v = {r["tid"]: r for r in var_rows}
    ids = [r["tid"] for r in base_rows if r["tid"] in v]
    return b, v, ids



def live_w(src, risk):
    lr = LIVE_RISK.get(src, RISK)
    return min(lr, risk) if np.isfinite(risk) and risk > 0 else lr


def _fin(x):
    try:
        return x is not None and np.isfinite(x)
    except TypeError:
        return False


def trade_pnl(row):
    """Account-fraction pnl at live risk (notional cap 1x)."""
    nr = row.get("net_R", np.nan)
    if not _fin(nr):
        return 0.0
    return live_w(row["src"], row["risk"]) * nr


def filter_rows(rows, start=HEADLINE_START, end=None, src=None, half=None):
    s = pd.Timestamp(start, tz="UTC")
    e = pd.Timestamp(end, tz="UTC") if end else pd.Timestamp("2100-01-01", tz="UTC")
    if half == "A":
        s, e = pd.Timestamp(HALF_A[1], tz="UTC"), pd.Timestamp(HALF_A[2], tz="UTC")
    elif half == "B":
        s, e = pd.Timestamp(HALF_B[1], tz="UTC"), pd.Timestamp(HALF_B[2], tz="UTC")
    out = []
    for r in rows:
        ts = pd.Timestamp(int(r["t_in"]), unit="ms", tz="UTC")
        if ts < s or ts >= e:
            continue
        if src is not None and r["src"] != src:
            continue
        out.append(r)
    return out


def engine_stats(rows, start=HEADLINE_START, end=None, half=None, src=None):
    rr = filter_rows(rows, start, end, src=src, half=half)
    if not rr:
        return dict(tr=0, win=np.nan, pf=np.nan, ret=np.nan, dd=np.nan, avgR=np.nan,
                    exp=np.nan, mar=np.nan, netR=np.nan)
    wR = np.array([r["net_R"] for r in rr], dtype=float)
    wR = wR[np.isfinite(wR)]
    if len(wR) == 0:
        return dict(tr=len(rr), win=np.nan, pf=np.nan, ret=np.nan, dd=np.nan, avgR=np.nan,
                    exp=np.nan, mar=np.nan, netR=np.nan)
    g = wR[wR > 0].sum(); ls = -wR[wR < 0].sum()
    pf = (g / ls) if ls > 0 else (np.inf if g > 0 else np.nan)
    eq = np.cumprod(1.0 + RISK * wR)
    eq = np.r_[1.0, eq]
    peak = np.maximum.accumulate(eq)
    dd = 100 * ((eq / peak) - 1).min()
    ret = 100 * float(eq[-1] - 1)
    avg = float(np.mean(wR))
    mar = ret / abs(dd) if np.isfinite(dd) and dd < 0 else (np.inf if ret > 0 else np.nan)
    return dict(tr=int(len(wR)), win=100 * float((wR > 0).mean()), pf=float(pf) if np.isfinite(pf) else pf,
                ret=ret, dd=float(dd), avgR=avg, exp=avg, mar=float(mar) if np.isfinite(mar) else mar,
                netR=float(np.sum(wR)))


def basket_stats(rows, start=HEADLINE_START, end=None, half=None):
    rr = filter_rows(rows, start, end, half=half)
    if not rr:
        return dict(tr=0, win=np.nan, pf=np.nan, ret=np.nan, dd=np.nan, avgR=np.nan,
                    exp=np.nan, mar=np.nan, netR=np.nan)
    rr = sorted(rr, key=lambda r: (int(r["t_out"]), r["tid"]))
    pnl = np.array([trade_pnl(r) for r in rr], dtype=float)
    wR = np.array([r["net_R"] for r in rr], dtype=float)
    ok = np.isfinite(pnl) & np.isfinite(wR)
    pnl, wR = pnl[ok], wR[ok]
    if len(pnl) == 0:
        return dict(tr=0, win=np.nan, pf=np.nan, ret=np.nan, dd=np.nan, avgR=np.nan,
                    exp=np.nan, mar=np.nan, netR=np.nan)
    # PF / win / avgR on live-weighted R (pnl / live_w would be net_R); use net_R for avgR
    # and account-fraction pnl for the equity curve.
    g = pnl[pnl > 0].sum(); ls = -pnl[pnl < 0].sum()
    pf = (g / ls) if ls > 0 else (np.inf if g > 0 else np.nan)
    eq = np.cumprod(1.0 + pnl)
    eq = np.r_[1.0, eq]
    peak = np.maximum.accumulate(eq)
    dd = 100 * ((eq / peak) - 1).min()
    ret = 100 * float(eq[-1] - 1)
    mar = ret / abs(dd) if np.isfinite(dd) and dd < 0 else (np.inf if ret > 0 else np.nan)
    return dict(tr=int(len(pnl)), win=100 * float((wR > 0).mean()), pf=float(pf) if np.isfinite(pf) else pf,
                ret=ret, dd=float(dd), avgR=float(np.mean(wR)), exp=float(np.mean(wR)),
                mar=float(mar) if np.isfinite(mar) else mar, netR=float(np.sum(wR)))


def paired_bootstrap(delta, n=N_BOOT, seed=1):
    """One-sided bootstrap p-value that mean(delta) > 0: share of resampled means <= 0."""
    d = np.asarray(delta, dtype=float)
    d = d[np.isfinite(d)]
    if len(d) == 0:
        return np.nan, np.nan
    mean = float(np.mean(d))
    rng = np.random.default_rng(int(seed) & 0x7FFFFFFF)
    # vectorised where it fits; chunk if huge
    m = len(d)
    idx = rng.integers(0, m, size=(n, m))
    means = d[idx].mean(axis=1)
    p = float((means <= 0.0).mean())
    return mean, p


def pair_deltas(base_rows, var_rows, src=None, start=HEADLINE_START, end=None, half=None, weighted=False):
    b, v, ids = pair_maps(filter_rows(base_rows, start, end, src=src, half=half),
                          filter_rows(var_rows, start, end, src=src, half=half))
    dR, dP = [], []
    for tid in ids:
        br, vr = b[tid], v[tid]
        if _fin(br.get("net_R")) and _fin(vr.get("net_R")):
            dR.append(vr["net_R"] - br["net_R"])
            dP.append(trade_pnl(vr) - trade_pnl(br))
    return np.array(dR, float), np.array(dP, float), ids


def seed_of(*a):
    s = "|".join(map(str, a)).encode()
    return int(hashlib.md5(s).hexdigest()[:8], 16)


def fmt_row(st, prefix=""):
    mar = st.get("mar", np.nan)
    return (f"{prefix}n={st['tr']}  win={fmt(st['win'],1)}%  avgR={fmt(st['avgR'],3)}  "
            f"exp={fmt(st['exp'],3)}  PF={fmt(st['pf'],2)}  ret={fmt(st['ret'],1)}%  "
            f"DD={fmt(st['dd'],1)}%  MAR={fmt(mar,2)}")


def evaluate(base_rows, var_rows, seed_key="x", start=HEADLINE_START):
    """Basket + per-engine + halves + bootstrap for one variant vs baseline (same asset)."""
    bsk_b = basket_stats(base_rows, start)
    bsk_v = basket_stats(var_rows, start)
    dR, dP, ids = pair_deltas(base_rows, var_rows, start=start, weighted=True)
    mean_r, p_r = paired_bootstrap(dR, seed=seed_of(seed_key, "r"))
    mean_p, p_p = paired_bootstrap(dP, seed=seed_of(seed_key, "p"))
    dmar = (bsk_v["mar"] - bsk_b["mar"]) if (_fin(bsk_v["mar"]) and _fin(bsk_b["mar"])) else np.nan
    halves = {}
    for tag in ("A", "B"):
        hb = basket_stats(base_rows, half=tag)
        hv = basket_stats(var_rows, half=tag)
        hdR, _, _ = pair_deltas(base_rows, var_rows, half=tag)
        hm, hp = paired_bootstrap(hdR, seed=seed_of(seed_key, tag))
        dhm = (hv["mar"] - hb["mar"]) if (_fin(hv["mar"]) and _fin(hb["mar"])) else np.nan
        halves[tag] = dict(base=hb, var=hv, dMAR=dhm, dR=hm, p=hp, n=len(hdR))
    per = {}
    for src in LIVE_ENGINES:
        sb = engine_stats(base_rows, start, src=src)
        sv = engine_stats(var_rows, start, src=src)
        edR, _, _ = pair_deltas(base_rows, var_rows, src=src, start=start)
        em, ep = paired_bootstrap(edR, seed=seed_of(seed_key, src))
        per[src] = dict(base=sb, var=sv, dR=em, p=ep, n=len(edR),
                        dMAR=(sv["mar"] - sb["mar"]) if (_fin(sv["mar"]) and _fin(sb["mar"])) else np.nan)
    return dict(base=bsk_b, var=bsk_v, dMAR=dmar, dR=mean_r, p=p_p, p_r=p_r, mean_pnl=mean_p,
                halves=halves, per=per, n=len(dR))


def eth_contradicts(eth_ev):
    """ETH contradicts if mean trade deltaR is significantly negative (p(mean>0) > 0.9)."""
    if eth_ev is None:
        return False
    dR = eth_ev.get("dR", np.nan)
    p = eth_ev.get("p_r", eth_ev.get("p", np.nan))
    return _fin(dR) and dR < 0 and _fin(p) and p > 0.9


def half_holds(ev):
    """Holds in both halves: BTC basket MAR improves (or dR > 0 if MAR is undefined) in A and B."""
    ok = True
    for tag in ("A", "B"):
        h = ev["halves"][tag]
        if h["n"] < 1:
            return False
        if _fin(h["dMAR"]):
            if h["dMAR"] <= 0:
                ok = False
        elif _fin(h["dR"]):
            if h["dR"] <= 0:
                ok = False
        else:
            ok = False
    return ok


def keep_card(btc_ev, eth_ev):
    reasons = []
    mar_up = _fin(btc_ev["dMAR"]) and btc_ev["dMAR"] > 0
    if not mar_up:
        reasons.append("basket MAR did not improve")
    p_ok = _fin(btc_ev["p"]) and btc_ev["p"] < P_KEEP
    if not p_ok:
        reasons.append(f"bootstrap p={fmt(btc_ev['p'],3)} not < {P_KEEP}")
    h_ok = half_holds(btc_ev)
    if not h_ok:
        reasons.append("did not hold in both halves")
    e_ok = not eth_contradicts(eth_ev)
    if not e_ok:
        reasons.append("ETH contradicts (significant negative deltaR)")
    keep = bool(mar_up and p_ok and h_ok and e_ok)
    return keep, reasons


def print_eval(title, ev, eth_ev=None, per_engine=True):
    print(f"  BTC  {fmt_row(ev['var'])}  dMAR={fmt(ev['dMAR'],3)}  dR={fmt(ev['dR'],3)}  p={fmt(ev['p'],3)}")
    print(f"       baseline {fmt_row(ev['base'])}")
    for tag, lab in (("A", "2017-20"), ("B", "2021-26")):
        h = ev["halves"][tag]
        print(f"       {lab}  n={h['n']}  dMAR={fmt(h['dMAR'],3)}  dR={fmt(h['dR'],3)}  p={fmt(h['p'],3)}  "
              f"var MAR={fmt(h['var']['mar'],2)}")
    if eth_ev is not None:
        print(f"  ETH  {fmt_row(eth_ev['var'])}  dMAR={fmt(eth_ev['dMAR'],3)}  dR={fmt(eth_ev['dR'],3)}  p={fmt(eth_ev['p'],3)}")
        print(f"       baseline {fmt_row(eth_ev['base'])}")
        contra = "YES — veto" if eth_contradicts(eth_ev) else "no"
        print(f"       ETH contradict? {contra}")
    if per_engine:
        print("       BTC per engine:")
        for src in LIVE_ENGINES:
            pe = ev["per"][src]
            if pe["base"]["tr"] == 0 and pe["var"]["tr"] == 0:
                continue
            print(f"         {src:6s}  {fmt_row(pe['var'])}  dR={fmt(pe['dR'],3)}  p={fmt(pe['p'],3)}  "
                  f"base avgR={fmt(pe['base']['avgR'],3)}  n={pe['n']}")


# ---------------------------------------------------------------------------
# BE1: +1R tag-entry diagnostic (not a variant; uses the 1h path + original targets)
# ---------------------------------------------------------------------------
def tag_entry_report(specs, F):
    """Of trades that reach +1R, what fraction tag entry before the far target, by A2 state."""
    keys = ("C1", "C2", "MOM30")
    buckets = {k: {s: [0, 0] for s in list(A2_STATES) + ["ALL"]} for k in keys}  # [reach1, tag]
    reach_then_tgt = {k: {s: [0, 0] for s in list(A2_STATES) + ["ALL"]} for k in keys}
    use_frame(F)
    check_alignment(specs, F, "tag-entry")
    for sp in specs:
        src = sp["src"]
        if src not in keys:
            continue
        side, entry, ei, risk = sp["side"], sp["entry"], sp["ei"], sp["risk"]
        rpx = risk * entry
        lvl1 = entry + side * rpx
        far = sp["tp2"] if np.isfinite(sp["tp2"]) else (entry + side * 3.0 * rpx)
        end = min(N - 1, ei + int(sp["max_hold"]))
        reached = False
        tagged = False
        hit_tgt = False
        for i in range(ei, end + 1):
            h, l = Hh[i], L[i]
            if not reached:
                if (h >= lvl1) if side > 0 else (l <= lvl1):
                    reached = True
            if reached and not hit_tgt:
                if (l <= entry) if side > 0 else (h >= entry):
                    tagged = True
                if np.isfinite(far) and ((h >= far) if side > 0 else (l <= far)):
                    hit_tgt = True
                    break
        if not reached:
            continue
        st = sp.get("a2") or "NORMAL"
        if st not in A2_STATES:
            st = "NORMAL"
        for bucket in (st, "ALL"):
            buckets[src][bucket][0] += 1
            if tagged:
                buckets[src][bucket][1] += 1
            reach_then_tgt[src][bucket][0] += 1
            if tagged and hit_tgt:
                reach_then_tgt[src][bucket][1] += 1
    print("\n  +1R tag-entry diagnostic (share of +1R trades that tag entry before the far target):")
    print(f"  {'eng':6s}  {'state':10s}  n+1R  tag%  tag-then-target%")
    for src in keys:
        for st in list(A2_STATES) + ["ALL"]:
            n, tg = buckets[src][st]
            if n == 0:
                continue
            n2, tt = reach_then_tgt[src][st]
            print(f"  {src:6s}  {st:10s}  {n:4d}  {100.0*tg/n:5.1f}%  {100.0*tt/max(n,1):5.1f}%")
    # headline tax note
    n, tg = buckets["C1"]["ALL"][0] + buckets["C2"]["ALL"][0] + buckets["MOM30"]["ALL"][0], \
            buckets["C1"]["ALL"][1] + buckets["C2"]["ALL"][1] + buckets["MOM30"]["ALL"][1]
    share = 100.0 * tg / n if n else np.nan
    print(f"  combined C1/C2/MOM30: {fmt(share,1)}% of +1R trades tag entry first  (n={n}). "
          f"{'BE is expensive (prior: >60%).' if _fin(share) and share > 60 else 'Below the 60% “expensive BE” flag.'}")
    return share


# ---------------------------------------------------------------------------
# X1 after-exit: what the trade would have made under the current exit
# ---------------------------------------------------------------------------
def x1_after_report(base_rows, var_rows, specs):
    b, v, ids = pair_maps(base_rows, var_rows)
    n_x1 = 0
    would = []
    later_win = 0
    var_r = []
    for tid in ids:
        vr, br = v[tid], b[tid]
        if vr.get("why") != "X1" and not vr.get("x1"):
            continue
        n_x1 += 1
        would.append(br["net_R"])
        var_r.append(vr["net_R"])
        if _fin(br["net_R"]) and br["net_R"] > 0:
            later_win += 1
    if n_x1 == 0:
        print("  X1 after-exit: no early exits in this variant.")
        return
    would = np.array(would, float); var_r = np.array(var_r, float)
    print(f"  X1 after-exit: {n_x1} early exits.  mean R taken={fmt(np.nanmean(var_r),3)}  "
          f"mean R the trade would have made (current exit)={fmt(np.nanmean(would),3)}  "
          f"frac that would have finished as winners={fmt(100.0*later_win/n_x1,1)}%  "
          f"mean leftover (would − taken)={fmt(np.nanmean(would-var_r),3)}")


# ---------------------------------------------------------------------------
# Card runners
# ---------------------------------------------------------------------------
def run_variant(specs, F, pol):
    return walk_all(specs, pol, F)


def pick_best(rows_by_key, base_rows):
    """rows_by_key: {key: var_rows}. Return key with highest BTC-headline basket MAR."""
    best = None
    best_mar = -np.inf
    for k, rows in rows_by_key.items():
        st = basket_stats(rows)
        mar = st["mar"]
        if _fin(mar) and mar > best_mar:
            best_mar, best = mar, k
        elif best is None:
            best = k
            if _fin(mar):
                best_mar = mar
    return best



def test_card(name, grid, middle, make_pol, specs_btc, F_btc, specs_eth, F_eth,
              base_btc, base_eth, extra_cb=None):
    """Sweep grid (list of param keys), print basket lines, evaluate best + middle, return verdict."""
    print(f"\n===== {name} =====")
    packed = {}
    evs = {}
    for key in grid:
        pol = make_pol(key)
        var = run_variant(specs_btc, F_btc, pol)
        packed[key] = var
        st = basket_stats(var)
        bst = basket_stats(base_btc)
        dmar = (st["mar"] - bst["mar"]) if (_fin(st["mar"]) and _fin(bst["mar"])) else np.nan
        print(f"  sweep {key!s:24s}  {fmt_row(st)}  dMAR={fmt(dmar,3)}")
    chosen = pick_best(packed, base_btc)
    print(f"  chosen (best full-sample BTC basket MAR): {chosen}")
    print(f"  middle / round default: {middle}")

    def ev_of(key):
        if key not in evs:
            var_b = packed[key] if key in packed else run_variant(specs_btc, F_btc, make_pol(key))
            var_e = run_variant(specs_eth, F_eth, make_pol(key)) if specs_eth is not None else None
            evb = evaluate(base_btc, var_b, seed_key=f"{name}|{key}|btc")
            eve = evaluate(base_eth, var_e, seed_key=f"{name}|{key}|eth") if var_e is not None else None
            evs[key] = (evb, eve, var_b, var_e)
        return evs[key]

    results = {}
    for label, key in (("CHOSEN", chosen), ("MIDDLE", middle)):
        evb, eve, var_b, var_e = ev_of(key)
        print(f"\n  -- {label} {name} {key} --")
        print_eval(f"{name} {key}", evb, eve, per_engine=True)
        if extra_cb is not None:
            extra_cb(key, var_b, var_e, evb, eve)
        keep, reasons = keep_card(evb, eve)
        tag = "KEEP" if keep else "DROP"
        why = "all four gates passed" if keep else "; ".join(reasons)
        print(f"  verdict {label}: {tag}  ({why})")
        results[label] = dict(key=key, keep=keep, reasons=reasons, ev_btc=evb, ev_eth=eve,
                              var_btc=var_b, var_eth=var_e, pol=make_pol(key))
    return results


def card_x1(specs_btc, F_btc, specs_eth, F_eth, base_btc, base_eth, base_pol=None):
    base_pol = base_pol or BASE_POL
    grid = [(thr, n) for thr in (0.25, 0.50, 0.75) for n in (8, 12, 16)]
    middle = (0.50, 12)

    def make(key, name=None):
        thr, n = key
        return base_pol.copy(name=name or f"X1@{thr}/{n}", x1_thr=float(thr), x1_n=int(n))

    def extra(key, var_b, var_e, evb, eve):
        print("  BTC after-exit:")
        x1_after_report(base_btc, var_b, specs_btc)
        if var_e is not None:
            print("  ETH after-exit:")
            x1_after_report(base_eth, var_e, specs_eth)

    return test_card("X1 dead-trade time stop", grid, middle, make,
                     specs_btc, F_btc, specs_eth, F_eth, base_btc, base_eth, extra)


def card_be1(specs_btc, F_btc, specs_eth, F_eth, base_btc, base_eth, base_pol=None):
    base_pol = base_pol or BASE_POL
    # one dimension at a time: trigger @ buffer=0.1, then buffer @ trigger=1.5
    grid = []
    for trig in (1.0, 1.5, 2.0, None):
        grid.append(("trig", trig, 0.1))
    for buf in (0.0, 0.1, 0.2):
        key = ("buf", 1.5, buf)
        if key not in grid:
            grid.append(key)
    middle = ("trig", 1.5, 0.1)

    def make(key, name=None):
        dim, trig, buf = key
        if trig is None:
            return base_pol.copy(name=name or "BE1@never", be_mode="off")
        return base_pol.copy(name=name or f"BE1@{trig}/{buf}", be_mode="rule",
                             be_trig=float(trig), be_buf=float(buf))

    print("\n===== BE1 tag-entry diagnostic (path feature, independent of the sweep) =====")
    tag_entry_report(specs_btc, F_btc)
    if specs_eth:
        print("  ETH:")
        tag_entry_report(specs_eth, F_eth)

    return test_card("BE1 breakeven overhaul", grid, middle, make,
                     specs_btc, F_btc, specs_eth, F_eth, base_btc, base_eth)


def card_q1(specs_btc, F_btc, specs_eth, F_eth, base_btc, base_eth, base_pol=None):
    base_pol = base_pol or BASE_POL
    grid = [(spl, ch, trig) for spl in (0.30, 0.40, 0.50)
            for ch in (2.5, 3.0, 3.5) for trig in (1.5, 2.0)]
    middle = (0.40, 3.0, 2.0)

    def make(key, name=None):
        spl, ch, trig = key
        return base_pol.copy(name=name or f"Q1@{spl}/{ch}/{trig}",
                             q1=dict(split=float(spl), chand=float(ch), trig=float(trig)))

    return test_card("Q1 runner for D34 and COCO", grid, middle, make,
                     specs_btc, F_btc, specs_eth, F_eth, base_btc, base_eth)


def card_z2(specs_btc, F_btc, specs_eth, F_eth, base_btc, base_eth, base_pol=None):
    base_pol = base_pol or BASE_POL
    grid = [((lo, hi), t) for (lo, hi) in ((-2, 1), (-2, 0)) for t in (0.7, 0.8, 0.9)]
    middle = ((-2, 1), 0.8)

    def make(key, name=None):
        (lo, hi), t = key
        return base_pol.copy(name=name or f"Z2@{lo}..{hi}/{t}",
                             z2=dict(lo=int(lo), hi=int(hi), tighten=float(t)))

    def extra(key, var_b, var_e, evb, eve):
        # monthly vs quarterly split on C1/C2 at this key (BTC)
        (lo, hi), t = key
        print("  expiry-type split (C1+C2, BTC) — in-window trades only:")
        for label, want_q in (("monthly", False), ("quarterly", True)):
            b_rows, v_rows = [], []
            for sp, br, vr in _zip_in_window(specs_btc, F_btc, base_btc, var_b, lo, hi, want_q):
                b_rows.append(br); v_rows.append(vr)
            if not b_rows:
                print(f"    {label}: n=0")
                continue
            sb, sv = engine_stats(b_rows), engine_stats(v_rows)
            dR, _, _ = pair_deltas(b_rows, v_rows)
            m, p = paired_bootstrap(dR, seed=seed_of("Z2", label, key))
            print(f"    {label}: base {fmt_row(sb)}  var {fmt_row(sv)}  dR={fmt(m,3)}  p={fmt(p,3)}")

    return test_card("Z2 expiry-week protocol", grid, middle, make,
                     specs_btc, F_btc, specs_eth, F_eth, base_btc, base_eth, extra)


def _zip_in_window(specs, F, base_rows, var_rows, lo, hi, want_q):
    b, v, _ = pair_maps(base_rows, var_rows)
    smap = {sp["tid"]: sp for sp in specs}
    out = []
    for tid, br in b.items():
        if tid not in v:
            continue
        sp = smap.get(tid)
        if sp is None or sp["src"] not in Z2_ENG:
            continue
        off = F["exp_off"][sp["ei"]]
        q = bool(F["exp_q"][sp["ei"]])
        if not np.isfinite(off) or not (lo <= off <= hi):
            continue
        if q != want_q:
            continue
        out.append((sp, br, v[tid]))
    return out


def card_t1(specs_btc, F_btc, specs_eth, F_eth, base_btc, base_eth, base_pol=None):
    base_pol = base_pol or BASE_POL
    grid = [2.5, 3.0, 3.5, 4.0]
    middle = 3.0

    def make(key, name=None):
        return base_pol.copy(name=name or f"T1@k={key}", t1k=float(key))

    results = test_card("T1 chandelier runner", grid, middle, make,
                        specs_btc, F_btc, specs_eth, F_eth, base_btc, base_eth)
    # chosen k must work in both halves — already in keep_card via half_holds.
    # If chosen fails halves, say so explicitly (the T1-specific gate).
    ch = results["CHOSEN"]
    if not half_holds(ch["ev_btc"]):
        print("  T1 note: the chosen k did NOT work in both halves — T1 is dropped even if other gates look fine.")
        ch["keep"] = False
        if "did not hold in both halves" not in ch["reasons"]:
            ch["reasons"].append("chosen k did not work in both halves")
        print("  verdict CHOSEN: DROP  (chosen k must work in both halves)")
    return results


def greedy_stack(passed, specs_btc, F_btc, specs_eth, F_eth, base_btc, base_eth):
    """Rank by solo BTC dMAR, add in that order if the card still passes on the new baseline."""
    print("\n===== STACK =====")
    if not passed:
        print("  No card passed the keep gates solo. Stack is empty — current exits stay as they are.")
        return [], BASE_POL, base_btc, base_eth
    ranked = sorted(passed, key=lambda r: (-(r["ev_btc"]["dMAR"] if _fin(r["ev_btc"]["dMAR"]) else -1e9),
                                           r["name"]))
    print("  solo rank (by BTC basket dMAR):")
    for i, r in enumerate(ranked, 1):
        print(f"    {i}. {r['name']} {r['key']!s}  dMAR={fmt(r['ev_btc']['dMAR'],3)}  p={fmt(r['ev_btc']['p'],3)}")
    adopted = []
    cur = BASE_POL
    cur_b, cur_e = base_btc, base_eth
    for r in ranked:
        trial = r["make"](r["key"], name="+".join([a["name"] for a in adopted] + [r["name"]]))
        # make() already copies from the card's base_pol which may be BASE_POL (solo). Rebuild from cur.
        trial = _overlay(cur, r)
        print(f"\n  re-test {r['name']} {r['key']!s} on baseline={' + '.join(a['name'] for a in adopted) or 'current exits'}")
        var_b = run_variant(specs_btc, F_btc, trial)
        var_e = run_variant(specs_eth, F_eth, trial)
        evb = evaluate(cur_b, var_b, seed_key=f"stack|{r['name']}|btc")
        eve = evaluate(cur_e, var_e, seed_key=f"stack|{r['name']}|eth")
        print_eval(f"stack {r['name']}", evb, eve, per_engine=True)
        keep, reasons = keep_card(evb, eve)
        if r["name"] == "T1" and not half_holds(evb):
            keep = False
            if "did not hold in both halves" not in reasons:
                reasons.append("chosen k did not work in both halves")
        if keep:
            print(f"  ADD {r['name']} {r['key']!s}")
            adopted.append(dict(name=r["name"], key=r["key"], ev_btc=evb, ev_eth=eve, pol=trial))
            cur, cur_b, cur_e = trial, var_b, var_e
        else:
            print(f"  SKIP {r['name']} {r['key']!s} on the new baseline  ({'; '.join(reasons)})")
    print("\n  adopted stack:", " + ".join(a["name"] + " " + str(a["key"]) for a in adopted) or "(none)")
    if adopted:
        print("  stacked vs original current-exit baseline:")
        evb = evaluate(base_btc, cur_b, seed_key="stack|final|btc")
        eve = evaluate(base_eth, cur_e, seed_key="stack|final|eth")
        print_eval("STACK", evb, eve, per_engine=True)
    return adopted, cur, cur_b, cur_e


def _overlay(cur, card):
    """Apply one card's chosen params on top of an already-stacked policy."""
    p = cur.copy(name=(cur.name + "+" + card["name"]) if cur.name != "baseline" else card["name"])
    n = card["name"]
    key = card["key"]
    if n == "X1":
        p.x1_thr, p.x1_n = float(key[0]), int(key[1])
    elif n == "BE1":
        dim, trig, buf = key
        if trig is None:
            p.be_mode = "off"
        else:
            p.be_mode, p.be_trig, p.be_buf = "rule", float(trig), float(buf)
    elif n == "Q1":
        spl, ch, trig = key
        p.q1 = dict(split=float(spl), chand=float(ch), trig=float(trig))
    elif n == "Z2":
        (lo, hi), t = key
        p.z2 = dict(lo=int(lo), hi=int(hi), tighten=float(t))
    elif n == "T1":
        p.t1k = float(key)
    return p


def plain_words(solo, adopted):
    print("\n===== PLAIN WORDS =====")
    lines = []
    if not solo:
        lines.append("None of the five exit cards cleared the keep gates on their own "
                     "(basket MAR up, bootstrap p < 0.1, both halves, ETH not contradicting). "
                     "Leave the current exits alone until a later batch revisits the ones that were close.")
    else:
        kept = [s for s in solo if s["keep"]]
        dropped = [s for s in solo if not s["keep"]]
        if kept:
            bits = []
            for s in kept:
                ev = s["ev_btc"]
                bits.append(f"{s['name']} {s['key']} (BTC dMAR {fmt(ev['dMAR'],2)}, p={fmt(ev['p'],3)}, "
                            f"dR={fmt(ev['dR'],3)})")
            lines.append("Solo keep: " + "; ".join(bits) + ".")
        if dropped:
            lines.append("Solo drop: " + "; ".join(
                f"{s['name']} {s['key']} ({'; '.join(s['reasons']) or 'gates failed'})" for s in dropped) + ".")
        if adopted:
            names = " + ".join(a["name"] + " " + str(a["key"]) for a in adopted)
            last = adopted[-1]
            ev = last["ev_btc"]
            lines.append(f"The greedy stack kept {names}. Against today's exits the stacked book prints "
                         f"MAR {fmt(ev['var']['mar'],2)} vs {fmt(ev['base']['mar'],2)} "
                         f"(dMAR {fmt(ev['dMAR'],2)}), basket dR {fmt(ev['dR'],3)}, p={fmt(ev['p'],3)}.")
            # if something was skipped on re-test
            skipped = [s["name"] for s in kept if s["name"] not in {a["name"] for a in adopted}]
            if skipped:
                lines.append("Dropped on the re-test (exits interact — BE, trails and the dead-trade clock "
                             "all write the same stop field): " + ", ".join(skipped) + ".")
        else:
            lines.append("Nothing survived the greedy re-test on a moving baseline, so do not change live exits.")
    lines.append("Read expectancy and basket maxDD together: win rate and avg R usually move in opposite "
                 "directions on these cards, so win rate alone will lie. X1's edge, when it has one, is "
                 "freed capacity and a shorter left tail, not a higher per-trade R — look at the after-exit "
                 "table to see how many 'dead' trades would have become winners. BE1 is expensive if more "
                 "than about 60% of +1R trades tag entry before the far target; that tax is why the trigger "
                 "and buffer are swept one dimension at a time and why C1's BE-at-TP1 is the thing being "
                 "moved, not blindly added. Q1 is a small-n call on D34 — believe the bootstrap, not the "
                 "point estimate. Z2 should be applied only where the monthly/quarterly split agrees; "
                 "T1's k has to work in both 2017-20 and 2021-26 or it is just a 2020-21 trend souvenir.")
    for ln in lines:
        print("  " + ln)
    return lines


# ---------------------------------------------------------------------------
# Smoke (synthetic only) and main
# ---------------------------------------------------------------------------
def synthetic_1h(n=20000, seed=7, start="2020-01-01"):
    """Regime-rich synthetic 1h series spanning both 2017-20 and 2021-26 halves when asked."""
    rng = np.random.default_rng(seed)
    t0 = ms(start)
    t = t0 + np.arange(n, dtype="int64") * H1
    day = np.arange(n) // 24
    regime = (day // 40) % 5
    drift = np.where(regime == 0, 0.00028, np.where(regime == 2, -0.00028, 0.00004))
    vol = np.where(regime == 3, 0.012, np.where(regime == 4, 0.0028, np.where(regime == 1, 0.005, 0.0065)))
    # scheduled squeeze-then-break bursts so C1/C2/COCO/D34-like paths exist
    burst = np.zeros(n)
    for b0 in range(200, n - 200, 500):
        burst[b0:b0 + 24] = 0.0
        vol[b0:b0 + 24] = 0.002
        burst[b0 + 24:b0 + 80] = 0.0012 * (1 if (b0 // 500) % 2 == 0 else -1)
    shock = rng.random(n) < 0.002
    vol = vol + shock * 0.02
    r = drift + burst + vol * rng.normal(size=n)
    close = 10000.0 * np.exp(np.cumsum(r))
    open_ = np.r_[close[0], close[:-1]]
    wh = np.abs(rng.normal(0, 1, n)) * vol * close
    high = np.maximum(open_, close) + wh
    low = np.minimum(open_, close) - wh
    low = np.maximum(low, 1e-6)
    volm = rng.lognormal(8, 0.4, n)
    return pd.DataFrame({"time": t, "open": open_, "high": high, "low": low, "close": close,
                         "volume": volm, "source": "synth"})


def synthetic_funding(d, seed=3):
    rng = np.random.default_rng(seed)
    t0, t1 = int(d["time"].iloc[0]), int(d["time"].iloc[-1])
    ts = np.arange(t0, t1 + 1, 8 * H1, dtype="int64")
    x = 0.0001 * rng.normal(size=len(ts))
    return pd.DataFrame({"time": ts, "funding": x})


def _align4(i):
    while i < N and int(T[i]) % H4 != 0:
        i += 1
    return i


def _paint(i0, i1, entry, path):
    """Overwrite OHLC on [i0, i1] so the close follows `path` (multipliers of entry)."""
    for k, i in enumerate(range(i0, min(i1, N))):
        px = float(entry * path[min(k, len(path) - 1)])
        prev = O[i] if k == 0 else C[i - 1]
        O[i] = prev
        C[i] = px
        Hh[i] = max(prev, px) * 1.0004
        L[i] = min(prev, px) * 0.9996


def inject_lab_specs(F, start_half_b=None):
    """Hand-built TradeSpecs that force every walker branch. Mutates OHLC in place."""
    specs = []
    def add(**kw):
        sp = make_spec(**kw)
        if sp:
            sp["a2"] = a2_at(F, sp["ei"]) if F is not None else "NORMAL"
            specs.append(sp)
        return sp

    # ---- X1: dead for 12 4H bars, then a 2R winner (after-exit positive) ----
    i = _align4(80)
    if i + 120 < N:
        e = float(O[i]); risk = 0.03; stop = e * (1 - risk)
        # stay at +0.15R for 12 4h (=48h), then trend to +2R
        path = [1.0 + 0.15 * risk] * 48 + list(np.linspace(1.0 + 0.15 * risk, 1.0 + 2.0 * risk, 40))
        _paint(i, i + len(path), e, path)
        add(src="C1", side=1, ei=i, entry=e, stop0=stop, risk=risk, kind="c1",
            atr_entry=risk * e / 1.5, tp1=e + 2.0 * (risk * e / 1.5), tp2=e + 3.5 * (risk * e / 1.5),
            tp1_frac=0.3, be_at_tp1=True)
        add(src="C2", side=1, ei=i, entry=e, stop0=stop, risk=risk, kind="c2",
            atr_entry=risk * e / 1.5, tp2=e + 3.0 * (risk * e / 1.5))
        add(src="MOM30", side=1, ei=i, entry=e, stop0=e - 1.8 * (risk * e / 1.5), risk=abs(1.8 * (risk / 1.5)),
            kind="mom30", atr_entry=risk * e / 1.5,
            tp1=e + 2.0 * (risk * e / 1.5), tp2=e + 3.0 * (risk * e / 1.5), tp1_frac=0.5, be_at_tp1=True)
        add(src="V7", side=1, ei=i, entry=e, stop0=e * 0.90, risk=0.10, kind="v7", v7=True, atr_entry=0.10 * e)
        add(src="R0", side=1, ei=i, entry=e, stop0=e * 0.90, risk=0.10, kind="r0", max_hold=10 * 24, atr_entry=0.10 * e)
        add(src="S5", side=1, ei=i, entry=e, stop0=stop, risk=risk, kind="s5", max_hold=15 * 24, chand_k=3.0,
            atr_entry=risk * e)
        add(src="B1G", side=1, ei=i, entry=e, stop0=stop, risk=risk, kind="b1g", max_hold=30 * 24, chand_k=3.0,
            atr_entry=risk * e)
        add(src="K8", side=1, ei=i, entry=e, stop0=stop, risk=risk, kind="k8", atr_entry=risk * e)

    # ---- BE1 / tag-entry: +1.2R, retrace through entry, then +3R ----
    j = _align4(400)
    if j + 80 < N:
        e = float(O[j]); risk = 0.02; stop = e * (1 - risk); M = risk * e / 1.5
        path = list(np.linspace(1.0, 1.0 + 1.2 * risk, 12)) + \
               list(np.linspace(1.0 + 1.2 * risk, 0.999, 10)) + \
               list(np.linspace(0.999, 1.0 + 3.5 * risk, 30))
        _paint(j, j + len(path), e, path)
        add(src="C1", side=1, ei=j, entry=e, stop0=stop, risk=risk, kind="c1", atr_entry=M,
            tp1=e + 2.0 * M, tp2=e + 3.5 * M, tp1_frac=0.3, be_at_tp1=True)
        add(src="C2", side=1, ei=j, entry=e, stop0=stop, risk=risk, kind="c2", atr_entry=M, tp2=e + 3.0 * M)
        add(src="MOM30", side=1, ei=j, entry=e, stop0=e - 1.8 * M, risk=1.8 * M / e, kind="mom30",
            atr_entry=M, tp1=e + 2.0 * M, tp2=e + 3.0 * M, tp1_frac=0.5, be_at_tp1=True)

    # ---- Q1: D34/COCO run through +2R and keep going (3R cap would amputate) ----
    k = _align4(700)
    if k + 200 < N:
        e = float(O[k]); risk = 0.04; stop = e * (1 - risk)
        path = list(np.linspace(1.0, 1.0 + 5.0 * risk, 120))
        _paint(k, k + len(path), e, path)
        add(src="D34", side=1, ei=k, entry=e, stop0=stop, risk=risk, kind="d34", atr_entry=risk * e,
            cap_r=3.0, time_stop=7 * 24, tp2=e + 3.0 * risk * e, max_hold=7 * 24)
        add(src="COCO", side=1, ei=k, entry=e, stop0=stop, risk=risk, kind="coco", atr_entry=risk * e,
            max_hold=MAX_HOLD, chand_k=3.0, fill_bar_stopentry=True)

    # ---- Z2: a C1/C2 trade inside the last-Friday window that reaches +1R ----
    # find a 1h bar whose exp_off is in [-2, 1]
    z = None
    for i in range(0, N - 80, 4):
        off = F["exp_off"][i] if F is not None else np.nan
        if np.isfinite(off) and -2 <= off <= 1 and int(T[i]) % H4 == 0:
            z = i
            break
    if z is None:
        z = _align4(24 * 22)  # fallback: ~day 22
    if z + 40 < N:
        e = float(O[z]); risk = 0.02; stop = e * (1 - risk); M = risk * e / 1.5
        path = list(np.linspace(1.0, 1.0 + 1.2 * risk, 8)) + list(np.linspace(1.0 + 1.2 * risk, 1.0 + 2.5 * risk, 20))
        _paint(z, z + len(path), e, path)
        add(src="C1", side=1, ei=z, entry=e, stop0=stop, risk=risk, kind="c1", atr_entry=M,
            tp1=e + 2.0 * M, tp2=e + 3.5 * M, tp1_frac=0.3, be_at_tp1=True)
        add(src="C2", side=1, ei=z, entry=e, stop0=stop, risk=risk, kind="c2", atr_entry=M, tp2=e + 3.0 * M)

    # ---- T1: after TP1 / +1.5R, extend then pull back by ~3 ATR ----
    u = _align4(1100)
    if u + 80 < N:
        e = float(O[u]); risk = 0.02; stop = e * (1 - risk); M = risk * e / 1.5
        path = list(np.linspace(1.0, 1.0 + 2.2 * (2.0 * M) / e, 16)) + \
               list(np.linspace(1.0 + 2.2 * (2.0 * M) / e, 1.0 + 0.4 * risk, 24))
        _paint(u, u + len(path), e, path)
        add(src="C1", side=1, ei=u, entry=e, stop0=stop, risk=risk, kind="c1", atr_entry=M,
            tp1=e + 2.0 * M, tp2=e + 3.5 * M, tp1_frac=0.3, be_at_tp1=True)
        add(src="C2", side=1, ei=u, entry=e, stop0=stop, risk=risk, kind="c2", atr_entry=M, tp2=e + 3.0 * M)

    # ---- stop-first: same bar tags stop and target ----
    v = _align4(1400)
    if v + 8 < N:
        e = float(O[v]); risk = 0.02; stop = e * (1 - risk); M = risk * e / 1.5
        # wide bar: low below stop, high above tp
        O[v] = e
        C[v] = e
        L[v] = stop * 0.999
        Hh[v] = e + 4 * M
        add(src="C1", side=1, ei=v, entry=e, stop0=stop, risk=risk, kind="c1", atr_entry=M,
            tp1=e + 2.0 * M, tp2=e + 3.5 * M, tp1_frac=0.3, be_at_tp1=True)

    # ---- a short, and a 2021-half copy so both halves have trades ----
    # 2021-01-01 is 366 days from 2020-01-01 (leap year) = 8784 hours
    w = _align4(24 * 400)  # ~day 400 of 2020-01-01 series → mid-Feb 2021
    if w + 60 < N:
        e = float(O[w]); risk = 0.025; stop = e * (1 + risk); M = risk * e / 1.5
        path = list(np.linspace(1.0, 1.0 - 0.2 * risk, 48)) + list(np.linspace(1.0 - 0.2 * risk, 1.0 - 2.0 * risk, 20))
        _paint(w, w + len(path), e, path)
        add(src="C1", side=-1, ei=w, entry=e, stop0=stop, risk=risk, kind="c1", atr_entry=M,
            tp1=e - 2.0 * M, tp2=e - 3.5 * M, tp1_frac=0.3, be_at_tp1=True)
        add(src="D34", side=-1, ei=w, entry=e, stop0=stop, risk=risk, kind="d34", atr_entry=risk * e,
            cap_r=3.0, time_stop=7 * 24, tp2=e - 3.0 * risk * e, max_hold=7 * 24)
        add(src="K8", side=-1, ei=w, entry=e, stop0=stop, risk=risk, kind="k8", atr_entry=risk * e)
        add(src="COCO", side=-1, ei=w, entry=e, stop0=stop, risk=risk, kind="coco", atr_entry=risk * e,
            max_hold=MAX_HOLD, chand_k=3.0, fill_bar_stopentry=True)
        add(src="V7", side=-1, ei=w, entry=e, stop0=e * 1.10, risk=0.10, kind="v7", v7=True, atr_entry=0.10 * e)
        add(src="R0", side=-1, ei=w, entry=e, stop0=e * 1.10, risk=0.10, kind="r0", max_hold=10 * 24, atr_entry=0.10 * e)
        add(src="S5", side=-1, ei=w, entry=e, stop0=stop, risk=risk, kind="s5", max_hold=15 * 24, chand_k=3.0)
        add(src="B1G", side=-1, ei=w, entry=e, stop0=stop, risk=risk, kind="b1g", max_hold=30 * 24, chand_k=3.0)
        add(src="MOM30", side=-1, ei=w, entry=e, stop0=e + 1.8 * M, risk=1.8 * M / e, kind="mom30",
            atr_entry=M, tp1=e - 2.0 * M, tp2=e - 3.0 * M, tp1_frac=0.5, be_at_tp1=True)
        add(src="C2", side=-1, ei=w, entry=e, stop0=stop, risk=risk, kind="c2", atr_entry=M, tp2=e - 3.0 * M)

    return specs


def run_smoke():
    print("=== batch11 smoke (synthetic only) ===", flush=True)
    assert callable(fmt), "fmt is missing — this is the bug that crashed batch9 in Colab"
    assert callable(tstats) and callable(last_friday_expiries) and callable(label_A2)
    # long synth covering both halves (2020-01-01 + 20000h ≈ mid-Apr 2022)
    d = synthetic_1h(n=20000, seed=11, start="2020-01-01")
    fund = synthetic_funding(d)
    set_asset(d)
    D = build_day(fund); D = market_states(D)
    a2, _ = label_A2(D)
    assert set(np.unique(a2)).issubset(set(A2_STATES) | set(["NORMAL"])), set(np.unique(a2))
    # engine collection (may be sparse on synth — lab specs cover the walker)
    specs_e, F, D = collect_specs(d, fund)
    n_eng = {s: 0 for s in LIVE_ENGINES}
    for sp in specs_e:
        n_eng[sp["src"]] = n_eng.get(sp["src"], 0) + 1
    print("  engine-collected trades:", n_eng)
    # inject path-coverage specs (mutates OHLC; frame atr arrays stay as-is, which is fine for smoke)
    lab = inject_lab_specs(F)
    # drop duplicate tids (lab wins)
    seen = {sp["tid"] for sp in lab}
    specs = lab + [s for s in specs_e if s["tid"] not in seen]
    srcs = {s["src"] for s in specs}
    missing = [s for s in LIVE_ENGINES if s not in srcs]
    print(f"  lab+engine srcs={sorted(srcs)}  missing={missing}")
    assert not missing, f"smoke must cover every engine, missing {missing}"
    # every card path + bootstrap + stack machinery
    base = walk_all(specs, BASE_POL, F)
    assert all(_fin(r["net_R"]) for r in base), "baseline walker produced non-finite R"
    # stop-first: the wide-bar C1 at the stop/target collision must exit SL, not TP
    sf = [r for r in base if r["why"] == "SL" and r["src"] == "C1"]
    assert len(sf) >= 1, "stop-first path was not exercised"
    # X1
    pol_x1 = Pol(name="X1", x1_thr=0.5, x1_n=12)
    var_x1 = walk_all(specs, pol_x1, F)
    assert any(r.get("x1") or r["why"] == "X1" for r in var_x1), "X1 did not fire on the dead-trade path"
    assert any(r["src"] == "K8" and (r.get("x1") or r["why"] == "X1") for r in var_x1), "K8 daily X1 path was not exercised"
    x1_after_report(base, var_x1, specs)
    ev = evaluate(base, var_x1, seed_key="smoke-x1")
    assert ev["n"] >= 1 and _fin(ev["p"])
    # halves both have trades
    assert ev["halves"]["A"]["n"] >= 1 and ev["halves"]["B"]["n"] >= 1, "both halves must have paired trades"
    # BE1 + tag-entry
    tag_entry_report(specs, F)
    pol_be = Pol(name="BE1", be_mode="rule", be_trig=1.5, be_buf=0.1)
    var_be = walk_all(specs, pol_be, F)
    ev_be = evaluate(base, var_be, seed_key="smoke-be1")
    assert ev_be["n"] >= 1
    assert any(r.get("be") for r in var_be), "BE1 did not move a stop to entry+buffer"
    # Q1 (final why may be SL/trail after the runner; the q1 flag is the path check)
    pol_q1 = Pol(name="Q1", q1=dict(split=0.40, chand=3.0, trig=2.0))
    var_q1 = walk_all(specs, pol_q1, F)
    assert any(r.get("q1") and r["src"] == "D34" for r in var_q1), "Q1 did not partial D34"
    assert any(r.get("q1") and r["src"] == "COCO" for r in var_q1), "Q1 did not partial COCO"
    ev_q1 = evaluate(base, var_q1, seed_key="smoke-q1")
    # D34 bootstrap path exists (small n is the point)
    dR, _, ids = pair_deltas(base, var_q1, src="D34")
    assert len(dR) >= 1
    paired_bootstrap(dR, seed=1)
    # Z2
    pol_z2 = Pol(name="Z2", z2=dict(lo=-2, hi=1, tighten=0.8))
    var_z2 = walk_all(specs, pol_z2, F)
    ev_z2 = evaluate(base, var_z2, seed_key="smoke-z2")
    assert any(r.get("z2") for r in var_z2), "Z2 accelerated partial was not exercised"
    # T1
    pol_t1 = Pol(name="T1", t1k=3.0)
    var_t1 = walk_all(specs, pol_t1, F)
    ev_t1 = evaluate(base, var_t1, seed_key="smoke-t1")
    assert any(r.get("t1") and r["src"] == "C1" for r in var_t1), "T1 did not arm on C1 after TP1"
    assert any(r.get("t1") and r["src"] == "C2" for r in var_t1), "T1 did not arm on C2 after +1.5R"
    # stacked policy walks
    stacked = Pol(name="stack", x1_thr=0.5, x1_n=12, be_mode="rule", be_trig=1.5, be_buf=0.1,
                  q1=dict(split=0.40, chand=3.0, trig=2.0), z2=dict(lo=-2, hi=1, tighten=0.8), t1k=3.0)
    var_st = walk_all(specs, stacked, F)
    ev_st = evaluate(base, var_st, seed_key="smoke-stack")
    assert ev_st["n"] == ev["n"]
    # keep_card / half_holds / eth_contradicts are callable and don't crash
    keep_card(ev, ev)
    half_holds(ev)
    eth_contradicts(ev)
    # never / off BE and a couple of other sweep corners
    walk_all(specs, Pol(name="BE1off", be_mode="off"), F)
    walk_all(specs, Pol(name="X1c", x1_thr=0.25, x1_n=8), F)
    walk_all(specs, Pol(name="X1k", x1_thr=0.75, x1_n=16), F)
    walk_all(specs, Pol(name="Q1c", q1=dict(split=0.30, chand=2.5, trig=1.5)), F)
    walk_all(specs, Pol(name="Z2c", z2=dict(lo=-2, hi=0, tighten=0.7)), F)
    walk_all(specs, Pol(name="T1c", t1k=2.5), F)
    walk_all(specs, Pol(name="T1d", t1k=4.0), F)
    # basket live-risk weights
    assert live_w("K8", 0.05) == 0.02 and live_w("COCO", 0.01) == 0.01 and live_w("C1", 0.02) == 0.01
    print(f"  baseline basket {fmt_row(basket_stats(base))}")
    print(f"  X1 p={fmt(ev['p'],3)}  BE1 p={fmt(ev_be['p'],3)}  Q1 p={fmt(ev_q1['p'],3)}  "
          f"Z2 p={fmt(ev_z2['p'],3)}  T1 p={fmt(ev_t1['p'],3)}  STACK p={fmt(ev_st['p'],3)}")
    # ---- v2: two-asset identity + R sanity (the v1 BTC/ETH global-array bug) ----
    print("  two-asset identity test ...", flush=True)
    dA = synthetic_1h(n=20000, seed=11, start="2020-01-01")
    dB = synthetic_1h(n=17000, seed=29, start="2020-03-01")
    for k in ("open", "high", "low", "close"):
        dB[k] = dB[k] * 0.07          # different price scale, like ETH vs BTC
    fA, fB = synthetic_funding(dA), synthetic_funding(dB)
    specsA, FA, _ = collect_specs(dA, fA)
    specsA = inject_lab_specs(FA) + specsA
    seenA = set(); specsA = [sp for sp in specsA if not (sp["tid"] in seenA or seenA.add(sp["tid"]))]
    baseA = walk_all(specsA, BASE_POL, FA, "A")
    specsB, FB, _ = collect_specs(dB, fB)          # globals now point at asset B (as ETH did in v1)
    baseB = walk_all(specsB, BASE_POL, FB, "B") if specsB else []
    identity_check("A (after B collected)", specsA, FA, baseA)
    if specsB:
        identity_check("B", specsB, FB, baseB)
    # reproduce the v1 bug on purpose: walk A's specs over B's arrays -> must be caught
    use_frame(FB)
    caught = False
    try:
        check_alignment(specsA, FB, "v1-bug-repro")
    except SanityError as e:
        caught = True
        print(f"  v1 bug repro caught by alignment check: {str(e)[:90]}...")
    assert caught, "alignment check failed to catch the BTC/ETH array mix-up"
    bug_rows = [walk_spec(sp, BASE_POL, FA) for sp in specsA if sp["ei"] < N]
    bmap = {r["tid"]: r for r in baseA}
    mx = max(abs(r["net_R"] - bmap[r["tid"]]["net_R"]) for r in bug_rows if r["tid"] in bmap)
    print(f"  v1-style walk (wrong arrays) max|dR| vs baseline = {mx:.2f}  (identity would FAIL, as it should)")
    assert mx > 1e-6
    # R sanity must flag a fake -3R non-gap loss and accept a gapped one
    fake = dict(baseA[0]); fake.update(net_R=-3.0, gross_R=-2.9, gap=False)
    try:
        r_sanity([fake], "fake"); raise AssertionError("r_sanity missed a -3R non-gap loss")
    except SanityError:
        pass
    fake["gap"] = True
    assert r_sanity([fake], "fake-gap")
    worst = min(r["net_R"] for r in baseA)
    print(f"  worst baseline R on A = {worst:.3f}; gapped exits = {sum(r['gap'] for r in baseA)}")
    print("=== smoke ok ===")


def _in_colab():
    return Path("/content").exists()


def run_asset(label, d, fund):
    print(f"\n########## {label}  1h n={len(d):,}  "
          f"{pd.to_datetime(int(d['time'].iloc[0]), unit='ms', utc=True)} → "
          f"{pd.to_datetime(int(d['time'].iloc[-1]), unit='ms', utc=True)}  ##########", flush=True)
    specs, F, D = collect_specs(d, fund)
    cnt = {s: 0 for s in LIVE_ENGINES}
    for sp in specs:
        cnt[sp["src"]] = cnt.get(sp["src"], 0) + 1
    print("  collected entries:", "  ".join(f"{k}={cnt[k]}" for k in LIVE_ENGINES))
    base = walk_all(specs, BASE_POL, F, label)
    print("  current-exit basket:", fmt_row(basket_stats(base)))
    return specs, F, base


def run_all(btc, eth, fund):
    print("Collecting fixed entries (current engines) ...", flush=True)
    specs_b, F_b, base_b = run_asset("BTC", btc, fund)
    specs_e, F_e, base_e = run_asset("ETH", eth, fund)

    print("\n===== IDENTITY CHECK (no-op exit must reproduce baseline R exactly) =====", flush=True)
    try:
        identity_check("BTC", specs_b, F_b, base_b)
        identity_check("ETH", specs_e, F_e, base_e)
    except SanityError as e:
        print("\n" + "!" * 78 + f"\n!!! ABORT: {e}\n" + "!" * 78, flush=True)
        raise SystemExit("batch11 aborted: identity check failed — do NOT read any card results")

    try:
        r_x1 = card_x1(specs_b, F_b, specs_e, F_e, base_b, base_e)
        r_be = card_be1(specs_b, F_b, specs_e, F_e, base_b, base_e)
        r_q1 = card_q1(specs_b, F_b, specs_e, F_e, base_b, base_e)
        r_z2 = card_z2(specs_b, F_b, specs_e, F_e, base_b, base_e)
        r_t1 = card_t1(specs_b, F_b, specs_e, F_e, base_b, base_e)
    except SanityError as e:
        print("\n" + "!" * 78 + f"\n!!! ABORT (sanity): {e}\n" + "!" * 78, flush=True)
        raise SystemExit("batch11 aborted: a variant failed the R sanity check — do NOT read card results")

    def pack(name, res, make):
        ch = res["CHOSEN"]
        return dict(name=name, key=ch["key"], keep=ch["keep"], reasons=ch["reasons"],
                    ev_btc=ch["ev_btc"], ev_eth=ch["ev_eth"], make=make)

    solo = [pack("X1", r_x1, lambda key, name=None: Pol(name=name or "X1", x1_thr=float(key[0]), x1_n=int(key[1]))),
            pack("BE1", r_be, None),
            pack("Q1", r_q1, None),
            pack("Z2", r_z2, None),
            pack("T1", r_t1, None)]
    # fill make via _overlay
    for s in solo:
        s["make"] = lambda key, name=None, _s=s: _overlay(BASE_POL, {**_s, "key": key, "name": _s["name"]})

    passed = [s for s in solo if s["keep"]]
    adopted, _, _, _ = greedy_stack(passed, specs_b, F_b, specs_e, F_e, base_b, base_e)
    plain_words(solo, adopted)
    print(f"\nDone in {time.time() - T0:.1f}s")


if __name__ == "__main__" or True:
    # `%run` in Colab sets __name__ to "__main__"; keep a always-on footer like batch 7/8/10,
    # but refuse real-data runs on the box.
    if "--smoke" in sys.argv:
        run_smoke()
        sys.exit(0)
    if not _in_colab():
        raise SystemExit("batch11.py refuses to backtest real data outside Colab. Use: python3 batch11.py --smoke")
    print("Loading BTC/ETH 1h + funding ...", flush=True)
    btc, bsrc = load_asset("btc")
    eth, esrc = load_asset("eth")
    assert btc is not None and len(btc) > 1000, "BTC 1h data missing"
    assert eth is not None and len(eth) > 1000, "ETH 1h data missing"
    eth = fix_eth_bar(eth)
    print(f"BTC DATA: {bsrc} | {len(btc):,} rows")
    print(f"ETH DATA: {esrc} | {len(eth):,} rows")
    fund = load_funding()
    have_fund = fund is not None and len(fund) > 100
    print(f"FUNDING: {'yes, ' + str(len(fund)) + ' rows' if have_fund else 'NO — market-state fz will be empty'}")
    # headline window: BTC/ETH 2017+
    cut = ms(HEADLINE_START)
    if int(btc["time"].iloc[0]) < cut:
        btc = btc[btc["time"] >= cut - 400 * D1].reset_index(drop=True)  # keep warmup days
    run_all(btc, eth, fund if have_fund else None)
