# ===== BATCH 9 — Z1 funding divergence, Z3 premium dislocation, options-expiry filter on all live engines, RohOnChain session-open — paste this WHOLE cell into ONE Colab cell =====
# (or:  !wget -q -O batch9.py https://osom-boba.pages.dev/colab/batch9.py   then   %run batch9.py)
#
# COMMON: same loaders as batch 8 (BTC/ETH 1h 2013+/2017+, BTC/ETH 15m hosted at osom-boba.pages.dev/colab/).
#   New hosted venue files: hl_*_funding, hl_*_1h, bn_*_funding, bn_*perp_1h (BTC and ETH).
#   Costs 0.12%/side (FEE 0.0007 + SLIP 0.0005), 1% risk per trade standalone (notional <= 1x) unless a
#   variant says otherwise. Market fills at the next bar open of the engine's timeframe. Stop-first when
#   a bar touches stop and target. One position at a time per engine. BTC and ETH where data allows.
# IDEAS: (1) Z1 cross-venue funding divergence — (a) FILTER on live engines (skip longs when D>=95th pct,
#   skip shorts when D<=5th) over the Hyperliquid period; (b) standalone short when D>=95th AND 4H close
#   < EMA20(4H), stop = 20-bar 4H high + 0.3 ATR, target 2R, time stop 24h; long mirrored. Placebo: same
#   EMA rule without the D condition. Year blocks 2023/2024/2025/2026. (2) Z3 premium dislocation —
#   P=(HL-BN)/BN on 1h, 30d z-score; long when z<=-3 then a 1h close back above -1.5; stop = dislocation
#   low - 0.3 ATR; target z=0 or 2R; time stop 24h; short mirrored. Placebo: same z=±1.5 reclaim without
#   the prior |z|>=3 extreme. Also event count and reversion speed. (3) EXP options-expiry week filter
#   (7 days up to last Friday 08:00 UTC, plus that Friday) on all implemented live engines (K8, C1, C2,
#   COCO, B1G, S5, V7, R0, MOM30, D34). IN vs OUT and basket skip-in-expiry vs no filter, BTC and ETH
#   2017+, year blocks. Adopt only if the basket improves on both BTC and ETH and in most year blocks.
#   (4) RS RohOnChain session-open on 15m, targets 1R and 2R, breakeven at 1R. Placebo: same entry
#   without the HTF bias. Hyperliquid 1h candles only go as far as the public candleSnapshot cap
#   (~5000 bars, from 2026-04-28); funding history is complete from HL launch (2023-05-12).
# VERDICT (pre-declared, same as batch 6/7/8): KEEP if (1) headline PF >= 1.3 with >= 30 trades, (2) PF
#   beats its placebo by >= 0.3, (3) both early and late year-blocks that have trades are positive,
#   (4) ETH PF >= 1.1 (if ETH data exists), (5) corr with K8 < 0.3. WATCH if exactly one fails, else
#   DROP. KEEPs get a +-20% parameter robustness check. Ranked table + PLAIN WORDS at the end.
#   EXP is judged by the pre-declared basket rule, not the standalone KEEP tests.
# Smoke on the box only:  python3 batch9.py --smoke
# This script refuses to run a real-data backtest outside Colab (use --smoke).
import os, io, gzip, time, warnings, math, sys, calendar, json
from datetime import date, timedelta, datetime, timezone
from pathlib import Path
from urllib.error import HTTPError, URLError
from urllib.request import urlopen, Request
import numpy as np
import pandas as pd
warnings.filterwarnings("ignore")
pd.set_option("display.width", 230); pd.set_option("display.max_columns", 50); pd.set_option("display.max_rows", 400)

T0 = time.time()
H1 = 3_600_000; D1 = 24 * H1; H4 = 4 * H1; H12 = 12 * H1; M15 = 15 * 60 * 1000
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")]
HL_BUCKETS = [("2023", "2023-01-01", "2024-01-01"), ("2024", "2024-01-01", "2025-01-01"),
              ("2025", "2025-01-01", "2026-01-01"), ("2026", "2026-01-01", "2027-01-01")]
HEADLINE_START = "2017-01-01"
HL_START = "2023-05-12"
UA = "osom-batch9/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
STATES = ["QUAKE", "EXHAUST", "RIDE", "COIL", "CHOP"]
SCODE = {s: i for i, s in enumerate(STATES)}
P0 = dict(N=7, M=10, K=12, x=0.25, k=1.5)
RNG = np.random.default_rng(20261117)
MAX_HOLD = 30 * 24
TCOLS = ["t_in", "t_out", "side", "ret", "kind", "move", "risk"]
LIVE_ENGINES = ["K8", "C1", "C2", "COCO", "B1G", "S5", "V7", "R0", "MOM30", "D34"]

PLACEBO = {
    "Z1": "same 4H close vs EMA20 entry, stop, 2R and 24h time-stop, without the D-percentile condition",
    "Z3": "same z=+/-1.5 stabilization entry, stop, z=0-or-2R and 24h time-stop, without the prior |z|>=3 extreme",
    "RS-1R": "same session-open break/retest/close entry and 1R target, without the HTF bias",
    "RS-2R": "same session-open break/retest/close entry, BE at 1R and 2R target, without the HTF bias",
}

# --- loaders, indicators, engine run(), K8 (from batch8) ---
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)


# --- map daily signals onto 1h ---
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



# --- C1 / C2 (from batch8) ---
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
    tpm, xc = 3.0, 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)
                fills = [(1.0, float(xp), ei)]
                # 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

def shift_trades(trades, lag_ms):
    out = []
    for tr in trades:
        d = dict(tr)
        d["t_in"] = int(tr["t_in"] + lag_ms)
        d["t_out"] = int(tr["t_out"] + lag_ms)
        d["src"] = tr.get("src", "") + "_shift"
        out.append(d)
    return out

def overlap_freq(c1, c2):
    """Overlap frequency and daily-R correlation of the two standalone books."""
    def spans(tr):
        return [(t["t_in"], t["t_out"], t["side"]) for t in tr]
    s1, s2 = spans(c1), spans(c2)
    n1 = len(s1); n2 = len(s2)
    ov1 = ov2 = same = opp = 0
    for a0, a1, sa in s1:
        for b0, b1, sb in s2:
            if a0 < b1 and b0 < a1:
                if sa == sb: same += 1
                else: opp += 1
                if a0 <= b0 < a1: ov2 += 1  # C2 entered while C1 open
                if b0 <= a0 < b1: ov1 += 1
                break
    # unique overlaps counted per C1 trade that intersects any C2, already in ov1 style
    def daily_R(tr):
        if not tr:
            return pd.Series(dtype=float)
        df = pd.DataFrame(tr)
        day = pd.to_datetime(df["t_out"], unit="ms", utc=True).dt.floor("D")
        s = df.assign(day=day).groupby("day")["net_R"].sum()
        return s
    d1, d2 = daily_R(c1), daily_R(c2)
    if len(d1) and len(d2):
        idx = d1.index.union(d2.index)
        a, b = d1.reindex(idx).fillna(0), d2.reindex(idx).fillna(0)
        corr = float(a.corr(b)) if a.std() > 0 and b.std() > 0 else np.nan
    else:
        corr = np.nan
    return dict(n1=n1, n2=n2, c1_in_c2=ov1, c2_in_c1=ov2,
                frac_c1=ov1 / n1 if n1 else np.nan, frac_c2=ov2 / n2 if n2 else np.nan,
                same=same, opp=opp, corr=corr)

def apply_overlap(c1, c2, mode="both"):
    """mode: both | skip | half. Only same-direction later entries are skipped or halved."""
    ev = ([{**t, "src": "C1"} for t in c1] + [{**t, "src": "C2"} for t in c2])
    ev.sort(key=lambda t: (t["t_in"], 0 if t["src"] == "C1" else 1))
    open_c1 = open_c2 = None
    out = []
    for tr in ev:
        # drop stale opens
        if open_c1 is not None and open_c1["t_out"] <= tr["t_in"]:
            open_c1 = None
        if open_c2 is not None and open_c2["t_out"] <= tr["t_in"]:
            open_c2 = None
        other = open_c2 if tr["src"] == "C1" else open_c1
        overlapping = other is not None and other["side"] == tr["side"] and other["t_in"] <= tr["t_in"] < other["t_out"]
        w = 1.0
        if overlapping and mode == "skip":
            continue
        if overlapping and mode == "half":
            w = 0.5
        d = dict(tr); d["weight"] = w
        out.append(d)
        if tr["src"] == "C1": open_c1 = d
        else: open_c2 = d
    return out

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")

# --- options expiry (from batch8) ---
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

def in_options_week(t_ms, expiries, before_days=7, after_hours=24):
    t = pd.Timestamp(int(t_ms), unit="ms", tz="UTC")
    for e in expiries:
        if (t >= e - pd.Timedelta(days=before_days)) and (t < e + pd.Timedelta(hours=after_hours)):
            return True
    return False

def options_mask(trades, expiries):
    return np.array([in_options_week(t["t_in"], expiries) for t in trades], dtype=bool) if trades else np.array([], dtype=bool)

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

def _tframe(trades):
    if not trades:
        return pd.DataFrame(columns=["side", "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))

# --- daily states, V7, S5/B1G, COCO (from specialists_batch6) ---
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

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


def state_arrays(D):
    code = np.array([SCODE.get(s, -1) for s in D["state"].values], dtype=float)
    stb = to_base(D, code, D1); sdb = to_base(D, D["sdir"].values, D1)
    brkb = to_base(D, D["brk3"].values.astype(float), D1) == 1
    return stb, sdb, brkb

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

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

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 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 exit_args(ex, box_h, side, entry, ctx):
    tp = np.nan; trail = None; exh = None
    if ex == "trail3": trail = 3.0
    elif ex in ("tp1", "tp2", "tp3"): tp = entry + side * int(ex[-1]) * box_h
    elif ex == "2box": tp = entry + side * 2 * box_h
    elif ex == "exh": exh = ctx["exhL"] if side > 0 else ctx["exhS"]
    return tp, trail, exh

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 sys_oco(S, stop_v, ex, ctx, P, rearm=False, pred=None, mode=None):
    """batch-3 OCO; pred = list of leans aligned with S. mode 'one' = only the predicted side, no re-arm;
    mode 'tilt' = full bracket, predicted-side trades x1.5 size."""
    tr = []; dbl = 0; n2 = 0
    for si, s in enumerate(S):
        bh, bl, A = s["bh"], s["bl"], s["A"]; H = bh - bl; i = s["i0"]; i1 = s["i1"]
        pv = pred[si] if pred is not None else 0
        if mode == "one" and pv == 0: continue
        side = 0
        while i <= i1:
            if mode == "one":
                side = pv if ((pv > 0 and Hh[i] >= bh) or (pv < 0 and L[i] <= bl)) else 0
            else:
                side = first_touch(i, bh, bl)
            if side: break
            i += 1
        if not side: continue
        res = []; e_prev_px = np.nan
        for attempt in range(2 if (rearm and mode != "one") else 1):
            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)
            if stop_v == "opp": stp = bl if side > 0 else bh
            elif stop_v == "mid": stp = (bh + bl) / 2
            else: stp = e - side * P["k"] * A
            if side * (e - stp) <= 0: stp = e - side * 0.5 * A
            tp, trail, exh = exit_args(ex, H, side, e, ctx)
            r = sim_leg(i, side, e, stp, tp, trail, exh, fill_bar_stopentry=True, chand=ctx["chand"])
            if r is None: break
            j, px, kind, frac, s0 = r
            b = booked(i, j, side, e, px, frac, kind, s0)
            if mode == "tilt" and side == pv: b = (b[0], b[1], b[2], b[3] * 1.5, b[4], b[5], b[6] / 1.5)
            res.append(b)
            if not (rearm and mode != "one" and 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
        if rearm and len(res) == 2:
            n2 += 1; dbl += int(res[0][3] < 0 and res[1][3] < 0)
        tr += res
    return tr, (100 * dbl / n2 if n2 else np.nan)

# --- R0 ---
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

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


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):
    p = {**R0_DEFAULTS, **(p or {})}
    t, o, h, l, c = D["time"], D["open"], D["high"], D["low"], D["close"]
    n = len(c); W, hold = int(p["len"]), int(p["holdDays"] * 24)
    # Ws: failed break of the 600h (25-day) high/low = sweep-and-reclaim reversal, held 10 days
    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(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; long_ev = np.zeros(n, bool); short_ev = np.zeros(n, bool)
    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
                    (long_ev if M > 0 else short_ev)[w] = True
    if y: base.append((y, ei, None, None, "open"))
    # qd: wait up to 12h for a 0.5 x ATR dip from the signal-bar open, then enter; 10% stop; exit with base
    tr = _true_range(h, l, c); atr = _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"] * atr[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
        C = o[wI]; T = C * (1 - S * v); E = -1; A_ = xP; why = why0
        for P in range(wI, yI):
            if (l[P] <= T) if S > 0 else (h[P] >= T):
                E = P; A_ = min(T, o[P]) if S > 0 else max(T, 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=C, exit=A_, stop=T, fills=[(1.0, A_)],
                               ret=(A_ / C - 1) * S - 0.0014, why=why))
        else:
            trades.append(_open_trade(S, wI, C, T, n, c))
    return dict(trades=trades, long_ev=long_ev, short_ev=short_ev)

# --- rolling helpers / BB width (from zai_batch7) ---
def rolling_max(x, n) -> np.ndarray:
    return pd.Series(x).rolling(n, min_periods=n).max().to_numpy()

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

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

# --- MOM30 ---
import math

H = 3_600_000
H4 = 14_400_000
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)

def bucket4h(bars):
    out, cur, k = [], None, -1
    for b in bars:
        g = int(b["time"] // H4)
        if g != k:
            if cur:
                out.append(cur)
            k = g
            cur = dict(time=g * H4, open=float(b["open"]), high=float(b["high"]), low=float(b["low"]), close=float(b["close"]), volume=float(b.get("volume") or 0), n=1)
        else:
            cur["high"] = max(cur["high"], float(b["high"]))
            cur["low"] = min(cur["low"], float(b["low"]))
            cur["close"] = float(b["close"])
            cur["volume"] += float(b.get("volume") or 0)
            cur["n"] += 1
    if cur:
        out.append(cur)
    return [x for x in out if x["n"] == 4]

def mom30_tr_arr(B):
    t = []
    for i, b in enumerate(B):
        if i == 0:
            t.append(b["high"] - b["low"])
        else:
            pc = B[i - 1]["close"]
            t.append(max(b["high"] - b["low"], abs(b["high"] - pc), abs(b["low"] - pc)))
    return t

def wilder_atr(B, n):
    tr = mom30_tr_arr(B)
    o = [float("nan")] * len(B)
    s = c = 0
    v = float("nan")
    for i, x in enumerate(tr):
        if not math.isfinite(x):
            continue
        if math.isnan(v):
            s += x
            c += 1
            if c == n:
                v = s / n
                o[i] = v
        else:
            v = (v * (n - 1) + x) / n
            o[i] = v
    return o, tr

def sma_finite(x, n):
    o = [float("nan")] * len(x)
    for i in range(n - 1, len(x)):
        win = x[i - n + 1 : i + 1]
        if all(math.isfinite(y) for y in win):
            o[i] = sum(win) / n
    return o

def chop_arr(B, tr, n):
    o = [float("nan")] * len(B)
    for i in range(n - 1, len(B)):
        s, hi, lo, ok = 0, -math.inf, math.inf, True
        for j in range(i - n + 1, i + 1):
            if not math.isfinite(tr[j]):
                ok = False
                break
            s += tr[j]
            hi = max(hi, B[j]["high"])
            lo = min(lo, B[j]["low"])
        if ok and hi > lo:
            o[i] = 100 * math.log10(s / (hi - lo)) / math.log10(n)
    return o

def at_time(t1, t):
    lo, hi = 0, len(t1) - 1
    while lo < hi:
        m = (lo + hi + 1) >> 1
        if t1[m] <= t:
            lo = m
        else:
            hi = m - 1
    return lo

def mom30_calc(bars, opt=None):
    opt = opt or {}
    p = {**P, **(opt.get("p") or {})}
    b1 = list(bars)
    nxt = opt.get("next")
    if nxt and b1 and float(nxt["time"]) == b1[-1]["time"] + H and math.isfinite(float(nxt["open"])):
        n = nxt
        def g(k, d):
            v = n.get(k, d)
            return float(v) if v is not None and math.isfinite(float(v)) else float(d)
        b1 = b1 + [dict(time=float(n["time"]), open=float(n["open"]), high=g("high", n["open"]), low=g("low", n["open"]), close=g("close", n["open"]), volume=float(n.get("volume") or 0), partial=True)]
    B = bucket4h(b1)
    if len(B) < 40:
        return dict(error="not enough bars", trades=[], open=None, skipped=[], last=None)
    atr, tr = wilder_atr(B, p["atrLen"])
    satr = sma_finite(atr, p["satrLen"])
    chop = chop_arr(B, tr, p["atrLen"])
    n1 = len(b1)
    t1 = [b["time"] for b in b1]
    trades, skipped, open_ = [], [], None
    i = 0
    while i < len(B):
        a4, sa, ch = atr[i], satr[i], chop[i]
        take = True
        if not (math.isfinite(a4) and math.isfinite(sa) and math.isfinite(ch)) or i < p["mom"]:
            take = False
        s = 0
        if take:
            c, o, c5 = B[i]["close"], B[i]["open"], B[i - p["mom"]]["close"]
            if ch < p["chop"] and a4 > sa:
                if c > c5 and c > o:
                    s = 1
                elif c < c5 and c < o:
                    s = -1
        if not s:
            i += 1
            continue
        ft = B[i]["time"] + H4
        j0 = at_time(t1, ft)
        if t1[j0] != ft:
            i += 1
            continue
        e = b1[j0]["open"]
        if not math.isfinite(e) or e <= 0:
            i += 1
            continue
        raw_dist = p["sl"] * a4
        raw_pct = raw_dist / e
        if raw_pct < p["minStop"]:
            skipped.append(dict(side=s, sigTime=B[i]["time"], entryTime=t1[j0], entry=e, a4=a4, stopPct=raw_pct, why="stop_under_min"))
            i += 1
            continue
        dist = min(raw_dist, p["cap"] * e)
        sl0 = e - s * dist
        tp1 = e + s * p["tp1"] * a4
        tp2 = e + s * p["tp2"] * a4
        sp, w, legs, stage, why, tp1Time, tp1Px = sl0, 1, [], 0, None, None, None
        def fill_stop(px, b):
            return min(px, b["open"]) if s > 0 else max(px, b["open"])
        def fill_tp(px, b):
            return max(px, b["open"]) if s > 0 else min(px, b["open"])
        for j in range(j0, n1):
            b = b1[j]
            hitS = b["low"] <= sp if s > 0 else b["high"] >= sp
            hit1 = stage == 0 and (b["high"] >= tp1 if s > 0 else b["low"] <= tp1)
            hit2 = b["high"] >= tp2 if s > 0 else b["low"] <= tp2
            if hitS:
                legs.append(dict(w=w, px=fill_stop(sp, b), j=j))
                w = 0
                why = "BE" if stage else "SL"
                break
            if stage == 0 and hit1:
                px1 = fill_tp(tp1, b)
                legs.append(dict(w=p["tp1Frac"], px=px1, j=j))
                w = 1 - p["tp1Frac"]
                stage = 1
                sp = e
                tp1Time, tp1Px = t1[j], px1
                if hit2:
                    legs.append(dict(w=w, px=fill_tp(tp2, b), j=j))
                    w = 0
                    why = "TP2"
                    break
                continue
            if stage == 1 and hit2:
                legs.append(dict(w=w, px=fill_tp(tp2, b), j=j))
                w = 0
                why = "TP2"
                break
        if w > 0:
            open_ = dict(side=s, et=t1[j0], entry=e, sl0=sl0, stop=sp, stop0=sl0, tp1=tp1, tp2=tp2, a4=a4, sigTime=B[i]["time"], tp1Hit=stage == 1, tp1Time=tp1Time, tp1Px=tp1Px, left=w)
            break
        jx = legs[-1]["j"]
        trades.append(dict(side=s, et=t1[j0], xt=t1[jx], entry=e, exit=legs[-1]["px"], sl0=sl0, stop0=sl0, stop=sl0, tp1=tp1, tp2=tp2, a4=a4, sigTime=B[i]["time"], why=why, tp1Hit=len(legs) > 1, tp1Time=tp1Time, tp1Px=tp1Px, left=0))
        tEnd = t1[jx] + H
        ii = i + 1
        while ii < len(B) and B[ii]["time"] + H4 < tEnd:
            ii += 1
        i = ii
        continue
    last = None
    if B:
        li = len(B) - 1
        last = dict(time=B[li]["time"], close=B[li]["close"], open=B[li]["open"], atr=atr[li], satr=satr[li], chop=chop[li])
    return dict(trades=trades, open=open_, skipped=skipped, p=p, last=last)

# --- Batch 9 ideas ---
# ---------------------------------------------------------------------------
# Extra loaders (15m + hosted venue files)
# ---------------------------------------------------------------------------
def load_venue(name):
    """Load a hosted gz/csv (funding or ohlcv) from /content, deploy/colab, or SITE."""
    cands = []
    for base in (Path("/content"), Path("/workspace/osom10/deploy/colab"), Path("/tmp/batch9/data"), Path(".")):
        if base.exists():
            p = base / name
            if p.exists() and p.stat().st_size > 100:
                cands.append(p)
    for p in cands:
        try:
            d = pd.read_csv(p)
            return _norm_venue(d, name), str(p)
        except Exception:
            pass
    url = SITE + name
    try:
        print(f"Downloading {url} ...")
        d = _fetch(url)
        return _norm_venue(d, name), url
    except Exception as e:
        print(f"  hosted {name} failed: {e}")
        return None, None

def _norm_venue(df, name=""):
    if df is None or not len(df):
        return None
    cl = {c.lower().strip(): c for c in df.columns}
    def pick(*names):
        for n in names:
            if n in cl:
                return cl[n]
        return None
    tc = pick("time", "timestamp_ms", "timestamp", "open_time", "fundingtime", "funding_time")
    if tc is None:
        return None
    t = pd.to_numeric(df[tc], errors="coerce")
    mx = float(np.nanmax(t.values)) if len(t) else 0
    if mx > 1e17:
        tms = (t / 1e6).astype("int64")
    elif mx > 1e14:
        tms = (t / 1e3).astype("int64")
    elif mx > 1e11:
        tms = t.astype("int64")
    else:
        tms = (t * 1000).astype("int64")
    fc = pick("funding", "funding_rate", "last_funding_rate", "fundingrate")
    if fc is not None and pick("open") is None:
        out = pd.DataFrame({"time": tms, "funding": pd.to_numeric(df[fc], errors="coerce")}).dropna()
        return out.sort_values("time").drop_duplicates("time").reset_index(drop=True)
    o, h, l, c = pick("open"), pick("high"), pick("low"), pick("close", "adj close", "price")
    v = pick("volume", "vol")
    if None in (o, h, l, c):
        return None
    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})
    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) else None

def load_15m(kind):
    full_name = f"{kind}_15m_full.csv.gz"
    for base in (Path("/content"), Path("/workspace/osom10/deploy/colab"), Path(".")):
        p = base / full_name
        if p.exists() and p.stat().st_size > 1000:
            try:
                d = _norm(pd.read_csv(p))
            except Exception:
                d = None
            if d is not None and len(d) > 1000:
                print(f"  {kind} 15m local {p}: {len(d):,} bars")
                return d, str(p)
    url = SITE + full_name
    try:
        print(f"Downloading {url} ...")
        d = _norm(_fetch(url))
        if d is not None and len(d) > 1000:
            return d, url
    except Exception as e:
        print(f"  hosted {kind} 15m failed: {e}")
    return None, None

def range_of(df):
    if df is None or not len(df):
        return "-"
    t0 = pd.to_datetime(int(df["time"].iloc[0]), unit="ms", utc=True)
    t1 = pd.to_datetime(int(df["time"].iloc[-1]), unit="ms", utc=True)
    return f"{t0:%Y-%m-%d %H:%M} UTC -> {t1:%Y-%m-%d %H:%M} UTC ({len(df):,} rows)"

def _mk_trade(src, side, t_in, t_out, entry, exit_px, stop, why, ei=0, xi=0, weight=1.0, extra=None):
    risk = abs(entry - stop) / entry if entry and np.isfinite(entry) and np.isfinite(stop) else np.nan
    ret = side * (exit_px / entry - 1.0) - 2 * COST if entry else np.nan
    net_R = ret / risk if (np.isfinite(risk) and risk > 0) else np.nan
    d = dict(src=src, side=int(side), t_in=int(t_in), t_out=int(t_out), entry=float(entry),
             exit=float(exit_px), 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) if np.isfinite(ret) else np.nan,
             why=why, weight=float(weight), ei=int(ei), xi=int(xi))
    if extra:
        d.update(extra)
    return d

def from_run(res, src):
    t = res.get("trades")
    if t is None or not len(t):
        return []
    out = []
    for row in t.itertuples(index=False):
        t_in, t_out, side, ret, i_in, move, risk = row
        net_R = ret / RISK if RISK else np.nan
        out.append(dict(src=src, side=int(side), t_in=int(t_in), t_out=int(t_out),
                        entry=np.nan, exit=np.nan, stop=np.nan,
                        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="", weight=1.0, ei=int(i_in) if np.isfinite(i_in) else 0, xi=0))
    return out

def from_tuples(tr, src):
    out = []
    for rec in tr:
        t_in, t_out, side, ret, tag, move, risk = rec[:7]
        net_R = ret / RISK if RISK else np.nan
        out.append(dict(src=src, side=int(side), t_in=int(t_in), t_out=int(t_out),
                        entry=np.nan, exit=np.nan, stop=np.nan,
                        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=str(tag), weight=1.0, ei=0, xi=0))
    return out

def walk_1h(t, o, h, l, c, ei, side, entry, stop, target=None, time_stop_bars=24, be_at_R=None,
            z=None, z_flip=0.0, src="", why_open="open"):
    """Intrabar: stop first, then target, then z-target, then time stop, then last close. BE at 1R optional."""
    n = len(t)
    stp = float(stop)
    tgt = float(target) if target is not None and np.isfinite(target) else np.nan
    risk_px = abs(entry - stop)
    be_lvl = entry if (be_at_R is not None) else None
    be_hit = False
    for i in range(ei, n):
        hh, ll, oo, cc = h[i], l[i], o[i], c[i]
        if be_lvl is not None and not be_hit and np.isfinite(risk_px) and risk_px > 0:
            be_px = entry + side * be_at_R * risk_px
            if (hh >= be_px) if side > 0 else (ll <= be_px):
                be_hit = True
                stp = entry
        hit_stop = (ll <= stp) if side > 0 else (hh >= stp)
        hit_tgt = np.isfinite(tgt) and ((hh >= tgt) if side > 0 else (ll <= tgt))
        if hit_stop:
            px = min(stp, oo) if side > 0 else max(stp, oo)
            return _mk_trade(src, side, t[ei], t[i], entry, px, stop, "BE" if be_hit and abs(px - entry) / entry < 1e-9 else "SL", ei, i)
        if hit_tgt:
            px = max(tgt, oo) if side > 0 else min(tgt, oo)
            return _mk_trade(src, side, t[ei], t[i], entry, px, stop, "TP", ei, i)
        if z is not None and i < len(z) and np.isfinite(z[i]):
            if (side > 0 and z[i] >= z_flip) or (side < 0 and z[i] <= z_flip):
                return _mk_trade(src, side, t[ei], t[i], entry, cc, stop, "Z0", ei, i)
        if time_stop_bars is not None and (i - ei) >= time_stop_bars:
            return _mk_trade(src, side, t[ei], t[i], entry, cc, stop, "TIME", ei, i)
    return _mk_trade(src, side, t[ei], t[n - 1], entry, c[n - 1], stop, "OPEN", ei, n - 1)

def _r0_wrap(D):
    raw = osom_r0(D)["trades"]
    t = D["time"]
    out = []
    for tr in raw:
        if tr.get("exit") is None or tr.get("entry") is None:
            continue
        ei, xi = int(tr["ei"]), int(tr["xi"])
        if xi is None or not np.isfinite(tr["exit"]):
            continue
        risk = abs(tr["entry"] - tr["stop"]) / tr["entry"] if tr["entry"] else np.nan
        ret = tr["side"] * (tr["exit"] / tr["entry"] - 1.0) - 2 * COST
        net_R = ret / risk if (np.isfinite(risk) and risk > 0) else np.nan
        out.append(dict(src="R0", side=int(tr["side"]), t_in=int(t[ei]), t_out=int(t[xi]),
                        entry=float(tr["entry"]), exit=float(tr["exit"]), stop=float(tr["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=tr.get("why", ""), weight=1.0, ei=ei, xi=xi))
    return out

def _mom30_wrap(D):
    bars = [dict(time=int(t), open=float(o), high=float(h), low=float(l), close=float(c), volume=float(v))
            for t, o, h, l, c, v in zip(D["time"], D["open"], D["high"], D["low"], D["close"], D["volume"])]
    raw = mom30_calc(bars)
    out = []
    for tr in raw.get("trades") or []:
        side, entry, sl0 = tr["side"], tr["entry"], tr["sl0"]
        risk = abs(entry - sl0) / entry if entry else np.nan
        ret = -COST
        if tr.get("tp1Hit") and tr.get("tp1Px"):
            p1, p2 = float(tr["tp1Px"]), float(tr["exit"])
            ret += 0.5 * (side * (p1 / entry - 1.0) - COST * p1 / entry)
            ret += 0.5 * (side * (p2 / entry - 1.0) - COST * p2 / entry)
        else:
            px = float(tr["exit"])
            ret += 1.0 * (side * (px / entry - 1.0) - COST * px / entry)
        net_R = ret / risk if (np.isfinite(risk) and risk > 0) else np.nan
        out.append(dict(src="MOM30", side=int(side), t_in=int(tr["et"]), t_out=int(tr["xt"]),
                        entry=float(entry), exit=float(tr["exit"]), stop=float(sl0),
                        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=tr.get("why", ""), weight=1.0, ei=0, xi=0))
    return out

def d34_trades(df_1h, placebo=False):
    """Weekly squeeze (or non-squeeze placebo): stop-order break of 10-day high/low, 3R, 7-day time stop."""
    d = df_1h if isinstance(df_1h, pd.DataFrame) else pd.DataFrame(df_1h)
    t = np.asarray(d["time"], dtype="int64")
    day = pd.DataFrame({
        "g": t // D1, "open": np.asarray(d["open"], float), "high": np.asarray(d["high"], float),
        "low": np.asarray(d["low"], float), "close": np.asarray(d["close"], float),
        "last_i": np.arange(len(t)),
    }).groupby("g").agg(open=("open", "first"), high=("high", "max"), low=("low", "min"),
                        close=("close", "last"), last_i=("last_i", "max")).reset_index()
    day["ts"] = pd.to_datetime(day["g"] * D1, unit="ms", utc=True)
    h, l, c = day.high.to_numpy(), day.low.to_numpy(), day.close.to_numpy()
    weekly = day.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"]
    flag = weekly["squeeze"].fillna(False)
    squeeze_state = np.zeros(len(day), dtype=bool)
    for tw, val in flag.items():
        use = (not val) if placebo else val
        if not use:
            continue
        close_t = pd.Timestamp(tw)
        if close_t.tzinfo is None:
            close_t = close_t.tz_localize("UTC")
        else:
            close_t = close_t.tz_convert("UTC")
        trade_from = close_t + pd.Timedelta(days=7)
        trade_to = trade_from + pd.Timedelta(days=7)
        m = (day["ts"] >= trade_from) & (day["ts"] < trade_to)
        squeeze_state[m.to_numpy()] = True
    d10h = rolling_max(h, 10)
    d10l = rolling_min(l, 10)
    ent_h = np.r_[np.nan, d10h[:-1]]
    ent_l = np.r_[np.nan, d10l[:-1]]
    trades = []; i = 1
    o_d = day.open.to_numpy()
    li = day.last_i.to_numpy()
    gt = day.g.to_numpy()
    n = len(day)
    t1 = t
    o1 = np.asarray(d["open"], float); h1 = np.asarray(d["high"], float)
    l1 = np.asarray(d["low"], float); c1 = np.asarray(d["close"], float)
    while i < n - 1:
        if not squeeze_state[i] or not np.isfinite(ent_h[i]) or not np.isfinite(ent_l[i]):
            i += 1
            continue
        up = h[i] >= ent_h[i]
        dn = l[i] <= ent_l[i]
        side = 0
        if up and dn:
            side = 1 if (ent_h[i] - o_d[i]) <= (o_d[i] - ent_l[i]) else -1
        elif up:
            side = 1
        elif dn:
            side = -1
        if not side:
            i += 1
            continue
        entry_lvl = ent_h[i] if side > 0 else ent_l[i]
        stop_lvl = ent_l[i] if side > 0 else ent_h[i]
        i0 = int(day.last_i.iloc[i - 1]) + 1 if i > 0 else 0
        i1 = int(li[i])
        ei = None
        entry = None
        for k in range(i0, i1 + 1):
            if (h1[k] >= entry_lvl) if side > 0 else (l1[k] <= entry_lvl):
                entry = max(o1[k], entry_lvl) if side > 0 else min(o1[k], entry_lvl)
                ei = k
                break
        if ei is None:
            i += 1
            continue
        risk_px = abs(entry - stop_lvl)
        if entry <= 0 or risk_px / entry < 1e-6:
            i += 1
            continue
        target = entry + side * 3 * risk_px
        tr = walk_1h(t1, o1, h1, l1, c1, ei, side, entry, stop_lvl, target=target,
                     time_stop_bars=7 * 24, src="D34")
        trades.append(tr)
        xi = tr["xi"]
        exit_g = t1[xi] // D1
        nxt = int(np.searchsorted(gt, exit_g, side="right"))
        i = max(i + 1, nxt)
    return trades

def live_engines(df_1h, fund=None):
    """All implemented live engines on a 1h OHLCV DataFrame. Returns dict name -> trades."""
    global STOP_RULE
    set_asset(df_1h)
    Dday = market_states(build_day(fund))
    out = {}
    prev = STOP_RULE
    STOP_RULE = ("cap", 0.10)
    k8 = k8_system(Dday)
    out["K8"] = from_run(run("K8", k8["sig"], k8["stop"], exitL=k8["dir"] < 0, exitS=k8["dir"] > 0,
                             allow=k8_allow(k8, k8["sig"])), "K8")
    out["V7"] = from_run(run("V7", v7_system(Dday), 0.10 * C, trail_start=0.20, trail_drop=0.15), "V7")
    S5P, B1P = s5_b1(Dday)
    stb, sdb, _ = state_arrays(Dday)
    gate = (stb == SCODE["COIL"]) | (stb == SCODE["QUAKE"]) | (stb == SCODE["RIDE"])
    out["B1G"] = from_run(run("B1G", B1P["sig"], B1P["stop_dist"], chand_atr=B1P["chand_atr"],
                              chand_mult=3.0, max_hold=B1P["max_hold"], allow=gate), "B1G")
    out["S5"] = from_run(run("S5", S5P["sig"], S5P["stop_dist"], chand_atr=S5P["chand_atr"],
                             chand_mult=3.0, max_hold=S5P["max_hold"]), "S5")
    ctx = dict(chand=to_base(Dday, Dday["atr"].values, D1),
               exhL=(stb == SCODE["EXHAUST"]) & (sdb > 0), exhS=(stb == SCODE["EXHAUST"]) & (sdb < 0))
    S = coil_setups(Dday, P0)
    out["COCO"] = from_tuples(sys_oco(S, "opp", "trail3", ctx, P0, rearm=True)[0], "COCO")
    STOP_RULE = prev
    Dn = _norm_d(df_1h)
    out["C1"] = _c1_trades(Dn)
    out["C2"] = c2_trades(Dn)
    out["R0"] = _r0_wrap(Dn)
    out["MOM30"] = _mom30_wrap(Dn)
    out["D34"] = d34_trades(df_1h, placebo=False)
    return out

z1_HOURS = None

def funding_divergence(hl, bn, hourly_t):
    """F=24h sum of funding paid per venue, D=F_HL-F_BN, rolling 90d percentile (no lookahead)."""
    def paid(fd):
        s = pd.Series(fd["funding"].to_numpy(), index=(fd["time"].to_numpy().astype("int64") // H1 * H1))
        s = s.groupby(level=0).sum()
        return s.reindex(hourly_t).fillna(0.0)
    hl_h = paid(hl)
    bn_h = paid(bn)
    F_hl = hl_h.rolling(24, min_periods=1).sum()
    F_bn = bn_h.rolling(24, min_periods=1).sum()
    D = (F_hl - F_bn).to_numpy(dtype=float)
    look = 90 * 24
    pct = np.full(len(D), np.nan)
    if len(D) > look:
        w = np.lib.stride_tricks.sliding_window_view(D, look)
        past = w[:-1]
        cur = D[look:]
        pct[look:] = (past <= cur[:, None]).mean(axis=1)
    return F_hl.to_numpy(), F_bn.to_numpy(), D, pct

def _lookup_hour(t_ms, hours, *arrs):
    if hours is None or not len(hours):
        return (np.nan,) * len(arrs)
    j = int(np.searchsorted(hours, t_ms // H1 * H1, side="right")) - 1
    if j < 0:
        return (np.nan,) * len(arrs)
    return tuple(a[j] if j < len(a) else np.nan for a in arrs)

def z1_standalone(price_1h, D, pct, p_hi=0.95, p_lo=0.05, ema_n=20, atr_n=14, placebo=False):
    """Signal on 4H close. Enter next 1h open (start of next 4H)."""
    df = price_1h if isinstance(price_1h, pd.DataFrame) else pd.DataFrame(price_1h)
    t = np.asarray(df["time"], dtype="int64")
    o = np.asarray(df["open"], float); h = np.asarray(df["high"], float)
    l = np.asarray(df["low"], float); c = np.asarray(df["close"], float)
    H4b = pd.DataFrame({"g": t // H4, "open": o, "high": h, "low": l, "close": c, "i": np.arange(len(t))})
    a = H4b.groupby("g").agg(open=("open", "first"), high=("high", "max"), low=("low", "min"),
                             close=("close", "last"), last_i=("i", "max")).reset_index()
    hc, hh, hl_, ho = a.close.to_numpy(), a.high.to_numpy(), a.low.to_numpy(), a.open.to_numpy()
    ema = _ema(hc, ema_n)
    a4 = atr(hh, hl_, hc, atr_n)
    hi20 = rolling_max(hh, 20)
    lo20 = rolling_min(hl_, 20)
    close_t = (a["g"].to_numpy() + 1) * H4 - H1
    trades = []
    last_exit_i = -1
    for k in range(1, len(a) - 1):
        if not np.isfinite(ema[k]) or not np.isfinite(a4[k]) or not np.isfinite(hi20[k]) or not np.isfinite(lo20[k]):
            continue
        ct = int(close_t[k])
        _di, p = _lookup_hour(ct, z1_HOURS, D, pct)
        if not placebo:
            if not np.isfinite(p):
                continue
            short_ok = p >= p_hi
            long_ok = p <= p_lo
        else:
            short_ok = True
            long_ok = True
        side = 0
        if short_ok and hc[k] < ema[k]:
            side = -1
        elif long_ok and hc[k] > ema[k]:
            side = 1
        if not side:
            continue
        ei = int(a.last_i.iloc[k]) + 1
        if ei >= len(t) or ei <= last_exit_i:
            continue
        entry = float(o[ei])
        stop = float(hi20[k] + 0.3 * a4[k]) if side < 0 else float(lo20[k] - 0.3 * a4[k])
        if side * (entry - stop) <= 0:
            continue
        target = entry + side * 2 * abs(entry - stop)
        tr = walk_1h(t, o, h, l, c, ei, side, entry, stop, target=target, time_stop_bars=24, src="Z1")
        trades.append(tr)
        last_exit_i = tr["xi"]
    return trades

def filter_trades_z1(trades, hours, D, pct, p_hi=0.95, p_lo=0.05):
    kept = []; skipped = 0
    for tr in trades:
        _di, p = _lookup_hour(tr["t_in"], hours, D, pct)
        if not np.isfinite(p):
            kept.append(tr); continue
        if tr["side"] > 0 and p >= p_hi:
            skipped += 1; continue
        if tr["side"] < 0 and p <= p_lo:
            skipped += 1; continue
        kept.append(tr)
    return kept, skipped

def premium_z(hl_1h, bn_1h, zwin=30 * 24):
    h = hl_1h.set_index(hl_1h["time"].to_numpy() // H1 * H1)["close"]
    b = bn_1h.set_index(bn_1h["time"].to_numpy() // H1 * H1)["close"]
    h = h[~h.index.duplicated(keep="last")]
    b = b[~b.index.duplicated(keep="last")]
    idx = h.index.intersection(b.index)
    hl = h.reindex(idx).astype(float)
    bn = b.reindex(idx).astype(float)
    P = (hl - bn) / bn
    mu = P.rolling(zwin, min_periods=zwin // 2).mean().shift(1)
    sd = P.rolling(zwin, min_periods=zwin // 2).std(ddof=0).shift(1)
    z = (P - mu) / sd.replace(0, np.nan)
    return pd.DataFrame({"time": idx.to_numpy(dtype="int64"), "P": P.to_numpy(), "z": z.to_numpy(),
                         "hl": hl.to_numpy(), "bn": bn.to_numpy()})

def z3_trades(hl_1h, bn_1h, z=None, z_ext=3.0, z_stab=1.5, placebo=False):
    """Trade on Binance perp 1h after HL-vs-BN dislocation stabilizes."""
    zdf = premium_z(hl_1h, bn_1h) if z is None else z
    bn = bn_1h.set_index(bn_1h["time"].to_numpy() // H1 * H1)
    bn = bn[~bn.index.duplicated(keep="last")]
    zdf = zdf[zdf["time"].isin(bn.index)].copy()
    if not len(zdf):
        return [], {}
    t = zdf["time"].to_numpy(dtype="int64")
    o = bn.loc[t, "open"].to_numpy(dtype=float)
    h = bn.loc[t, "high"].to_numpy(dtype=float)
    l = bn.loc[t, "low"].to_numpy(dtype=float)
    c = bn.loc[t, "close"].to_numpy(dtype=float)
    zv = zdf["z"].to_numpy(dtype=float)
    a1 = atr(h, l, c, 14)
    trades = []; events = []
    n = len(t); i = 1
    while i < n - 2:
        zi = zv[i]
        if not np.isfinite(zi):
            i += 1; continue
        if placebo:
            side = 0
            if zv[i - 1] < -z_stab and zi >= -z_stab:
                side = 1
            elif zv[i - 1] > z_stab and zi <= z_stab:
                side = -1
            if not side:
                i += 1; continue
            ei = i + 1
            if ei >= n:
                break
            entry = float(o[ei])
            lo = l[max(0, i - 6):i + 1].min(); hi = h[max(0, i - 6):i + 1].max()
            stop = (lo - 0.3 * a1[i]) if side > 0 else (hi + 0.3 * a1[i])
            if not np.isfinite(stop) or side * (entry - stop) <= 0:
                i += 1; continue
            target = entry + side * 2 * abs(entry - stop)
            tr = walk_1h(t, o, h, l, c, ei, side, entry, stop, target=target,
                         time_stop_bars=24, z=zv, z_flip=0.0, src="Z3")
            trades.append(tr)
            i = tr["xi"] + 1
            continue
        if zi <= -z_ext or zi >= z_ext:
            side_ext = 1 if zi <= -z_ext else -1
            ext_i = i
            j = i + 1
            found = None
            lo = l[i]; hi = h[i]
            while j < n and (j - i) <= 5 * 24:
                lo = min(lo, l[j]); hi = max(hi, h[j])
                zj = zv[j]
                if not np.isfinite(zj):
                    j += 1; continue
                if side_ext > 0 and zj >= -z_stab:
                    found = j; break
                if side_ext < 0 and zj <= z_stab:
                    found = j; break
                if side_ext > 0 and zj <= -z_ext:
                    ext_i = j
                if side_ext < 0 and zj >= z_ext:
                    ext_i = j
                j += 1
            if found is None:
                i = j; continue
            i_stab = found
            ev_hours = (t[found] - t[ext_i]) / H1
            ei = i_stab + 1
            if ei >= n:
                break
            entry = float(o[ei])
            stop = (lo - 0.3 * a1[i_stab]) if side_ext > 0 else (hi + 0.3 * a1[i_stab])
            if not np.isfinite(stop) or side_ext * (entry - stop) <= 0:
                i = ei; continue
            target = entry + side_ext * 2 * abs(entry - stop)
            tr = walk_1h(t, o, h, l, c, ei, side_ext, entry, stop, target=target,
                         time_stop_bars=24, z=zv, z_flip=0.0, src="Z3")
            z0_h = np.nan
            for k in range(ext_i, tr["xi"] + 1):
                if np.isfinite(zv[k]) and ((side_ext > 0 and zv[k] >= 0) or (side_ext < 0 and zv[k] <= 0)):
                    z0_h = (t[k] - t[ext_i]) / H1
                    break
            tr["rev_hours"] = float(z0_h) if np.isfinite(z0_h) else float((t[tr["xi"]] - t[ext_i]) / H1)
            tr["stab_hours"] = float(ev_hours)
            trades.append(tr)
            events.append(dict(side=side_ext, t_ext=int(t[ext_i]), t_stab=int(t[i_stab]), z_ext=float(zv[ext_i]),
                               stab_h=float(ev_hours), rev_h=tr["rev_hours"], why=tr["why"], net_R=tr["net_R"]))
            i = tr["xi"] + 1
            continue
        i += 1
    info = {}
    if events:
        revs = [e["rev_h"] for e in events if np.isfinite(e["rev_h"])]
        stabs = [e["stab_h"] for e in events if np.isfinite(e["stab_h"])]
        info = dict(events=len(events), med_rev_h=float(np.median(revs)) if revs else np.nan,
                    mean_rev_h=float(np.mean(revs)) if revs else np.nan,
                    med_stab_h=float(np.median(stabs)) if stabs else np.nan)
    return trades, info

def expiry_windows(expiries, before_days=7, after_hours=24):
    starts = np.array([int((e - pd.Timedelta(days=before_days)).value // 1_000_000) for e in expiries], dtype="int64")
    ends = np.array([int((e + pd.Timedelta(hours=after_hours)).value // 1_000_000) for e in expiries], dtype="int64")
    return starts, ends

def in_expiry_arr(t_ms, starts, ends):
    t = np.asarray(t_ms, dtype="int64")
    j = np.searchsorted(starts, t, side="right") - 1
    ok = (j >= 0) & (t < ends[np.clip(j, 0, len(ends) - 1)]) & (t >= starts[np.clip(j, 0, len(starts) - 1)])
    return ok & (j >= 0)

def split_expiry(trades, starts, ends):
    if not trades:
        return [], []
    t = np.array([tr["t_in"] for tr in trades], dtype="int64")
    m = in_expiry_arr(t, starts, ends)
    return [tr for tr, k in zip(trades, m) if k], [tr for tr, k in zip(trades, m) if not k]

def basket_equity(engine_trades, start_px=10000.0, start="2017-01-01", end=None):
    ev = []
    for nm, tr in engine_trades.items():
        for t in tr:
            if t["t_out"] < ms(start):
                continue
            if end and t["t_out"] >= ms(end):
                continue
            if not np.isfinite(t.get("net_R", np.nan)):
                continue
            ev.append((int(t["t_out"]), float(t["weight"]) * float(t["net_R"])))
    ev.sort()
    if not ev:
        return dict(end=start_px, ret=0.0, dd=0.0, n=0, netR=0.0, pf=np.nan)
    r = np.array([x[1] for x in ev], float)
    eq = start_px * np.cumprod(1.0 + RISK * r)
    eq = np.r_[start_px, eq]
    peak = np.maximum.accumulate(eq)
    dd = 100 * ((eq / peak) - 1).min()
    g = r[r > 0].sum(); ls = -r[r < 0].sum()
    pf = (g / ls) if ls > 0 else (np.inf if g > 0 else np.nan)
    return dict(end=float(eq[-1]), ret=100 * (eq[-1] / start_px - 1), dd=float(dd), n=int(len(r)),
                netR=float(r.sum()), pf=float(pf) if np.isfinite(pf) else pf)

SESSIONS = (("Asia", 0, 0), ("London", 7, 0), ("NY", 13, 30))

def _colour(o, c):
    return np.where(c > o, 1, np.where(c < o, -1, 0)).astype("int8")

def rs_trades(df15, df1h, target_R=2.0, placebo=False, skip_atr=0.5):
    d15 = df15 if isinstance(df15, pd.DataFrame) else pd.DataFrame(df15)
    t = np.asarray(d15["time"], dtype="int64")
    o = np.asarray(d15["open"], float); h = np.asarray(d15["high"], float)
    l = np.asarray(d15["low"], float); c = np.asarray(d15["close"], float)
    n = len(t)
    src = df1h if df1h is not None and len(df1h) else d15
    ts = np.asarray(src["time"], dtype="int64")
    so = np.asarray(src["open"], float); sh = np.asarray(src["high"], float)
    sl = np.asarray(src["low"], float); sc = np.asarray(src["close"], float)
    dg = ts // D1
    day = pd.DataFrame({"g": dg, "open": so, "high": sh, "low": sl, "close": sc}).groupby("g").agg(
        open=("open", "first"), high=("high", "max"), low=("low", "min"), close=("close", "last"))
    d_o, d_h, d_l, d_c = day.open.to_numpy(), day.high.to_numpy(), day.low.to_numpy(), day.close.to_numpy()
    d_g = day.index.to_numpy()
    d_col = _colour(d_o, d_c)
    d_atr = atr(d_h, d_l, d_c, 14)
    hi20 = rolling_max(d_h, 20); lo20 = rolling_min(d_l, 20)
    g4 = ts // H4
    h4 = pd.DataFrame({"g": g4, "open": so, "close": sc}).groupby("g").agg(open=("open", "first"), close=("close", "last"))
    h4_g = h4.index.to_numpy(); h4_col = _colour(h4.open.to_numpy(), h4.close.to_numpy())
    week_ms = 7 * D1
    mon = ((ts + 3 * D1) // week_ms) * week_ms - 3 * D1
    wk = pd.DataFrame({"g": mon, "open": so, "close": sc}).groupby("g").agg(open=("open", "first"), close=("close", "last"))
    w_g = wk.index.to_numpy(); w_col = _colour(wk.open.to_numpy(), wk.close.to_numpy())

    def daily_ctx(t_ms):
        day_id = t_ms // D1 - 1
        j = int(np.searchsorted(d_g, day_id, side="left"))
        if j < len(d_g) and d_g[j] == day_id:
            return d_col[j], d_atr[j], hi20[j], lo20[j]
        j = int(np.searchsorted(d_g, day_id, side="right")) - 1
        if j >= 0:
            return d_col[j], d_atr[j], hi20[j], lo20[j]
        return 0, np.nan, np.nan, np.nan

    def closed_val(groups, vals, key):
        j = int(np.searchsorted(groups, key, side="left"))
        if j < len(groups) and groups[j] == key:
            return int(vals[j])
        j = int(np.searchsorted(groups, key, side="right")) - 1
        return int(vals[j]) if j >= 0 else 0

    minute = ((t // 60000) % 1440).astype("int32")
    trades = []; last_exit = -1
    for sname, shour, smin in SESSIONS:
        start_min = shour * 60 + smin
        first = np.where(minute == start_min)[0]
        for i0 in first:
            if i0 + 4 >= n:
                continue
            okbars = True
            for k in range(1, 4):
                if i0 + k >= n or t[i0 + k] - t[i0 + k - 1] != M15:
                    okbars = False; break
            if not okbars:
                continue
            t0 = int(t[i0])
            dcol, datr, dhi, dlo = daily_ctx(t0)
            c4 = closed_val(h4_g, h4_col, (t0 // H4 - 1) * H4)
            this_mon = ((t0 + 3 * D1) // week_ms) * week_ms - 3 * D1
            cw = closed_val(w_g, w_col, this_mon - week_ms)
            if placebo:
                sides = (1, -1)
            else:
                if dcol != 0 and dcol == c4:
                    bias = dcol
                elif dcol != c4:
                    bias = cw
                else:
                    bias = 0
                if bias == 0:
                    continue
                sides = (bias,)
            px = float(o[i0])
            first_hi, first_lo = float(h[i0]), float(l[i0])
            for side in sides:
                if not np.isfinite(datr) or not np.isfinite(dhi) or not np.isfinite(dlo):
                    continue
                if side > 0 and px >= (dhi - skip_atr * datr):
                    continue
                if side < 0 and px <= (dlo + skip_atr * datr):
                    continue
                lvl = first_hi if side > 0 else first_lo
                broke = False; dip_i = None; conf_i = None
                for k in range(i0 + 1, i0 + 4):
                    if k >= n:
                        break
                    if not broke:
                        if (h[k] > lvl) if side > 0 else (l[k] < lvl):
                            broke = True
                        continue
                    if (l[k] <= lvl) if side > 0 else (h[k] >= lvl):
                        dip_i = k
                    if dip_i is not None and ((c[k] > lvl) if side > 0 else (c[k] < lvl)):
                        conf_i = k
                        break
                if conf_i is None or dip_i is None:
                    continue
                ei = conf_i + 1
                if ei >= n or ei <= last_exit:
                    continue
                entry = float(o[ei])
                stop = float(l[dip_i]) if side > 0 else float(h[dip_i])
                if side * (entry - stop) <= 0:
                    continue
                target = entry + side * target_R * abs(entry - stop)
                tr = walk_1h(t, o, h, l, c, ei, side, entry, stop, target=target,
                             time_stop_bars=96, be_at_R=1.0 if target_R > 1.0 else None,
                             src=f"RS-{int(target_R)}R")
                trades.append(tr)
                last_exit = tr["xi"]
                break
    trades.sort(key=lambda x: x["t_in"])
    cleaned = []; busy = -1
    for tr in trades:
        if tr["ei"] <= busy:
            continue
        cleaned.append(tr)
        busy = tr["xi"]
    return cleaned

def idea_row_ex(name, trades, p_trades, k8d, buckets=None, headline=HEADLINE_START):
    buckets = buckets or BUCKETS
    tdf = _tframe(trades)
    h = tstats(_window(tdf, headline))
    tw = _window(tdf, headline)
    if tw is not None and len(tw):
        years = max(0.25, (tw["exit_ts"].max() - pd.Timestamp(headline, tz="UTC")).days / 365.25)
    else:
        years = max(0.25, (pd.Timestamp("now", tz="UTC") - pd.Timestamp(headline, 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']}"
        row[f"_ret_{b}"] = q["ret"]
        row[f"_n_{b}"] = q["tr"]
    ph = tstats(_window(_tframe(p_trades), headline))
    row["placebo PF/ret"] = f"{fmt(ph['pf'],2)}/{fmt(ph['ret'])} ({ph['tr']})"
    d = daily_from_trades(trades, headline)
    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["_h"] = h; row["_headline"] = headline
    return row

def verdicts_of(BR, ER, early_keys, late_keys):
    eth_pf = {r["idea"]: r.get("_pf", np.nan) for r in ER}
    VR = []
    for r in BR:
        nm = r["idea"]; fails = []
        if r.get("_n", 0) == 0:
            VR.append({"idea": nm, "verdict": "DROP", "fails": "no trades", "BTC n": 0,
                       "BTC PF": "-", "BTC ret%": "-", "BTC DD%": "-", "ETH PF": fmt(eth_pf.get(nm, np.nan), 2),
                       "placebo PF": "-", "corrK8": "-", "_pf": 0}); continue
        pf, n, ppf, ck = r["_pf"], r["_n"], r["_ppf"], r["_ck"]
        if not (np.isfinite(pf) and pf >= 1.3 and n >= 30):
            fails.append(f"PF {fmt(pf,2)} / n {n}")
        if not (np.isfinite(ppf) and np.isfinite(pf) and pf - ppf >= 0.3):
            fails.append(f"placebo {fmt(ppf,2)}")
        early = [r.get(f"_ret_{k}") for k in early_keys if r.get(f"_n_{k}", 0)]
        late = [r.get(f"_ret_{k}") for k in late_keys if r.get(f"_n_{k}", 0)]
        if early and late:
            if not (all(np.isfinite(x) and x > 0 for x in early) and all(np.isfinite(x) and x > 0 for x in late)):
                fails.append(f"blocks {fmt(early[0] if early else np.nan)}/{fmt(late[0] if late else np.nan)}")
        elif early or late:
            block = early or late
            if not all(np.isfinite(x) and x > 0 for x in block):
                fails.append("available year blocks not all positive")
        e = eth_pf.get(nm, np.nan)
        if ER:
            if not (np.isfinite(e) and e >= 1.1):
                fails.append(f"ETH PF {fmt(e,2)}")
        if not (np.isfinite(ck) and ck < 0.3):
            fails.append(f"corrK8 {fmt(ck,2)}")
        v = "KEEP" if not fails else ("WATCH" if len(fails) == 1 else "DROP")
        VR.append({"idea": nm, "verdict": v, "fails": "; ".join(fails) or "-", "BTC n": n, "BTC PF": fmt(pf, 2),
                   "BTC ret%": r["ret%"], "BTC DD%": r["maxDD%"], "ETH PF": fmt(e, 2), "placebo PF": fmt(ppf, 2),
                   "corrK8": r["corrK8"], "_pf": pf if np.isfinite(pf) else 0})
    VT = pd.DataFrame(VR)
    if len(VT):
        VT["_o"] = VT.verdict.map({"KEEP": 0, "WATCH": 1, "DROP": 2}); VT["_pf"] = VT["_pf"].fillna(0)
        VT = VT.sort_values(["_o", "_pf"], ascending=[True, False])
    return VT

def synthetic_1h(n=14000, seed=9, start="2017-01-02", px0=10000.0):
    rng = np.random.default_rng(seed)
    t0 = int(pd.Timestamp(start, tz="UTC").value // 1_000_000)
    t = t0 + np.arange(n) * H1
    ret = rng.normal(0.00015, 0.004, n)
    close = px0 * np.exp(np.cumsum(ret))
    open_ = np.r_[close[0], close[:-1]]
    high = np.maximum(open_, close) * (1 + np.abs(rng.normal(0, 0.0015, n)))
    low = np.minimum(open_, close) * (1 - np.abs(rng.normal(0, 0.0015, n)))
    vol = rng.uniform(100, 1000, n)
    i0 = 24 * 40
    if n > i0 + 200:
        px = float(close[i0 - 1])
        for k in range(200):
            i = i0 + k
            step = 0.003 + 0.00004 * k
            open_[i] = px; close[i] = px * (1 + step)
            high[i] = close[i] * 1.002; low[i] = open_[i] * 0.998
            vol[i] = 2000 + 80 * k; px = float(close[i])
    # After 210 days (rank lookbacks are live): a tight 12-day box and a wide breakout day for B1G/COCO.
    k0 = 24 * 210
    if n > k0 + 24 * 20:
        px = float(close[k0 - 1])
        for k in range(24 * 12):
            i = k0 + k
            open_[i] = px; close[i] = px * (1 + (0.0003 if k % 2 == 0 else -0.0003))
            high[i] = max(open_[i], close[i]) * 1.0003
            low[i] = min(open_[i], close[i]) * 0.9997
            vol[i] = 50
            px = float(close[i])
        # big breakout day
        for k in range(24 * 12, 24 * 14):
            i = k0 + k
            open_[i] = px; close[i] = px * 1.012
            high[i] = close[i] * 1.004; low[i] = open_[i] * 0.999
            vol[i] = 4000
            px = float(close[i])
    # Tight weekly closes for ~40 weeks (BB width collapses to a 26-week low), then a 10-day breakout for D34.
    j0 = 24 * 250
    n_tight = 24 * 7 * 40
    if n > j0 + n_tight + 24 * 14:
        px = float(close[j0 - 1])
        for k in range(n_tight):
            i = j0 + k
            step = 0.00005 * (1 if (k // 24) % 2 == 0 else -1)
            open_[i] = px; close[i] = px * (1 + step)
            high[i] = max(open_[i], close[i]) * 1.0002
            low[i] = min(open_[i], close[i]) * 0.9998
            vol[i] = 80
            px = float(close[i])
        for k in range(n_tight, n_tight + 24 * 12):
            i = j0 + k
            open_[i] = px; close[i] = px * 1.006
            high[i] = close[i] * 1.002; low[i] = open_[i] * 0.999
            vol[i] = 3000
            px = float(close[i])
    return pd.DataFrame({"time": t.astype("int64"), "open": open_.astype(float), "high": high.astype(float),
                         "low": low.astype(float), "close": close.astype(float), "volume": vol.astype(float)})

def synthetic_15m_from_1h(h1, seed=11):
    rng = np.random.default_rng(seed)
    rows = []
    for t, o, h, l, c, v in zip(h1.time, h1.open, h1.high, h1.low, h1.close, h1.volume):
        px = float(o); target = float(c)
        for k in range(4):
            tt = int(t) + k * M15
            cl = target if k == 3 else px * (1 + rng.normal(0, 0.0008))
            op = px
            hi = max(op, cl) * (1 + abs(rng.normal(0, 0.0004)))
            lo = min(op, cl) * (1 - abs(rng.normal(0, 0.0004)))
            rows.append((tt, op, max(hi, op, cl), min(lo, op, cl), cl, float(v) / 4))
            px = cl
    return pd.DataFrame(rows, columns=["time", "open", "high", "low", "close", "volume"])

def plant_rs_setup(d15):
    d = d15.copy()
    t = d.time.to_numpy()
    minute = (t // 60000) % 1440
    cands = np.where((minute == 0) & (t >= t[0] + 25 * D1) & (t < t[-1] - D1))[0]
    if not len(cands):
        return d
    i0 = int(cands[len(cands) // 3])
    base = float(d.close.iloc[i0 - 1])
    day0 = (t[i0] // D1 - 1) * D1
    sl = (t >= day0) & (t < t[i0])
    d.loc[sl, "open"] = base * 0.99
    d.loc[sl, "close"] = base * 1.00
    d.loc[sl, "high"] = base * 1.005
    d.loc[sl, "low"] = base * 0.985
    d.iloc[i0, d.columns.get_loc("open")] = base
    d.iloc[i0, d.columns.get_loc("close")] = base * 1.001
    d.iloc[i0, d.columns.get_loc("high")] = base * 1.002
    d.iloc[i0, d.columns.get_loc("low")] = base * 0.999
    lvl = base * 1.002
    d.iloc[i0 + 1, d.columns.get_loc("open")] = base * 1.001
    d.iloc[i0 + 1, d.columns.get_loc("high")] = lvl * 1.003
    d.iloc[i0 + 1, d.columns.get_loc("low")] = base * 1.000
    d.iloc[i0 + 1, d.columns.get_loc("close")] = lvl * 1.002
    d.iloc[i0 + 2, d.columns.get_loc("open")] = lvl * 1.001
    d.iloc[i0 + 2, d.columns.get_loc("low")] = lvl * 0.999
    d.iloc[i0 + 2, d.columns.get_loc("high")] = lvl * 1.004
    d.iloc[i0 + 2, d.columns.get_loc("close")] = lvl * 1.003
    return d

def synthetic_venues(price_1h, seed=13):
    rng = np.random.default_rng(seed)
    t = price_1h["time"].to_numpy(dtype="int64")
    hl_f = rng.normal(0, 5e-6, len(t))
    bn_t = t[::8]
    bn_f = rng.normal(0, 3e-5, len(bn_t))
    i0 = 24 * 100
    hl_f[i0:i0 + 36] = 0.0008
    c = price_1h["close"].to_numpy(dtype=float)
    hl_c = c.copy(); hl_o = price_1h["open"].to_numpy(dtype=float).copy()
    hl_h = price_1h["high"].to_numpy(dtype=float).copy(); hl_l = price_1h["low"].to_numpy(dtype=float).copy()
    j0 = 24 * 130
    # Build a 30d z-score warm-up, then a clear -4-sigma dislocation vs BN
    for k in range(8):
        hl_c[j0 + k] = c[j0 + k] * 0.955
        hl_o[j0 + k] = c[j0 + k] * 0.96
        hl_h[j0 + k] = c[j0 + k] * 0.965
        hl_l[j0 + k] = c[j0 + k] * 0.95
    for k in range(8, 30):
        a = (k - 8) / 22
        hl_c[j0 + k] = c[j0 + k] * (0.955 + 0.045 * a)
        hl_o[j0 + k] = c[j0 + k] * (0.96 + 0.04 * a)
        hl_h[j0 + k] = max(hl_o[j0 + k], hl_c[j0 + k]) * 1.001
        hl_l[j0 + k] = min(hl_o[j0 + k], hl_c[j0 + k]) * 0.999
    hl = pd.DataFrame({"time": t, "open": hl_o, "high": hl_h, "low": hl_l, "close": hl_c,
                       "volume": price_1h["volume"].to_numpy()})
    bn = price_1h.copy()
    hl_fund = pd.DataFrame({"time": t, "funding": hl_f})
    bn_fund = pd.DataFrame({"time": bn_t, "funding": bn_f})
    return hl_fund, bn_fund, hl, bn


def run_z1(label, price, hl_f, bn_f, k8d, engines):
    global z1_HOURS
    if hl_f is None or bn_f is None or price is None:
        print(f"  {label} Z1 skipped (missing venue funding)")
        return None
    t0 = max(int(hl_f.time.iloc[0]), int(bn_f.time.iloc[0]), int(price.time.iloc[0]))
    t1 = min(int(hl_f.time.iloc[-1]), int(bn_f.time.iloc[-1]), int(price.time.iloc[-1]))
    hours = np.arange(t0 // H1 * H1, t1 + H1, H1, dtype="int64")
    z1_HOURS = hours
    Fhl, Fbn, D, pct = funding_divergence(hl_f, bn_f, hours)
    print(f"  {label} Z1 hours {len(hours):,}; finite D-pct {int(np.isfinite(pct).sum()):,}")
    tr = z1_standalone(price, D, pct, placebo=False)
    ptr = z1_standalone(price, D, pct, placebo=True)
    row = idea_row_ex("Z1", tr, ptr, k8d, buckets=HL_BUCKETS, headline=HL_START)
    filt_rows = []
    for nm, trades in engines.items():
        base = [t for t in trades if t["t_in"] >= ms(HL_START)]
        kept, skipped = filter_trades_z1(base, hours, D, pct)
        sb = tstats(_window(_tframe(base), HL_START))
        sk = tstats(_window(_tframe(kept), HL_START))
        filt_rows.append({"engine": nm, "n": sb["tr"], "PF": fmt(sb["pf"], 2), "ret%": fmt(sb["ret"]),
                          "netR": fmt(sb["netR"], 1), "n_filt": sk["tr"], "PF_filt": fmt(sk["pf"], 2),
                          "ret_filt%": fmt(sk["ret"]), "netR_filt": fmt(sk["netR"], 1), "skipped": skipped})
    return dict(row=row, trades=tr, placebo=ptr, filt=filt_rows, hours=hours, D=D, pct=pct)

def run_z3(label, hl_px, bn_px, k8d):
    if hl_px is None or bn_px is None:
        print(f"  {label} Z3 skipped (missing HL or Binance 1h)")
        return None
    tr, info = z3_trades(hl_px, bn_px, placebo=False)
    ptr, _ = z3_trades(hl_px, bn_px, placebo=True)
    print(f"  {label} Z3 trades {len(tr)}; events={info}")
    hl_head = pd.to_datetime(int(hl_px.time.iloc[0]), unit="ms", utc=True).strftime("%Y-%m-%d")
    head = max(HL_START, hl_head)
    row = idea_row_ex("Z3", tr, ptr, k8d, buckets=HL_BUCKETS, headline=head)
    return dict(row=row, trades=tr, placebo=ptr, info=info, headline=head)

def exp_report(label, Eng, starts, ends):
    print(f"\n=== EXPIRY-WEEK FILTER — {label} (2017+) ===")
    rows = []
    for nm, tr in Eng.items():
        inn, out = split_expiry(tr, starts, ends)
        si = tstats(_window(_tframe(inn), HEADLINE_START))
        so = tstats(_window(_tframe(out), HEADLINE_START))
        sa = tstats(_window(_tframe(tr), HEADLINE_START))
        rows.append({"engine": nm,
                     "ALL n/PF/ret/netR": f"{sa['tr']}/{fmt(sa['pf'],2)}/{fmt(sa['ret'])}/{fmt(sa['netR'],1)}",
                     "IN n/PF/ret/netR": f"{si['tr']}/{fmt(si['pf'],2)}/{fmt(si['ret'])}/{fmt(si['netR'],1)}",
                     "OUT n/PF/ret/netR": f"{so['tr']}/{fmt(so['pf'],2)}/{fmt(so['ret'])}/{fmt(so['netR'],1)}"})
    print(pd.DataFrame(rows).to_string(index=False))
    all_b = basket_equity(Eng, start=HEADLINE_START)
    skipped = {nm: split_expiry(tr, starts, ends)[1] for nm, tr in Eng.items()}
    skip_b = basket_equity(skipped, start=HEADLINE_START)
    print(f"  {label} basket $10,000 2017+: no-filter end ${all_b['end']:.0f} ret {fmt(all_b['ret'])}% "
          f"DD {fmt(all_b['dd'])}% n {all_b['n']} PF {fmt(all_b['pf'],2)} netR {fmt(all_b['netR'],1)}")
    print(f"  {label} basket $10,000 2017+: skip-in-expiry end ${skip_b['end']:.0f} ret {fmt(skip_b['ret'])}% "
          f"DD {fmt(skip_b['dd'])}% n {skip_b['n']} PF {fmt(skip_b['pf'],2)} netR {fmt(skip_b['netR'],1)}")
    block_rows = []; improved = 0; considered = 0
    for b, a_, z in BUCKETS:
        if a_ < "2017-01-01":
            continue
        A = basket_equity(Eng, start=a_, end=z)
        S = basket_equity(skipped, start=a_, end=z)
        if A["n"] == 0 and S["n"] == 0:
            continue
        considered += 1
        if S["ret"] > A["ret"]:
            improved += 1
        block_rows.append({"block": b, "all ret%/PF/n": f"{fmt(A['ret'])}/{fmt(A['pf'],2)}/{A['n']}",
                           "skip ret%/PF/n": f"{fmt(S['ret'])}/{fmt(S['pf'],2)}/{S['n']}",
                           "better": "yes" if S["ret"] > A["ret"] else "no"})
    if block_rows:
        print(pd.DataFrame(block_rows).to_string(index=False))
    return dict(all=all_b, skip=skip_b, improved=improved, considered=considered,
                better_overall=(skip_b["ret"] > all_b["ret"]))

def run_rs(label, d15, d1h, k8d):
    if d15 is None:
        print(f"  {label} RS skipped (no 15m)")
        return None
    print(f"  {label} RS session-open on {len(d15):,} 15m bars ...", flush=True)
    tA = time.time()
    r1 = rs_trades(d15, d1h, target_R=1.0, placebo=False)
    r1p = rs_trades(d15, d1h, target_R=1.0, placebo=True)
    r2 = rs_trades(d15, d1h, target_R=2.0, placebo=False)
    r2p = rs_trades(d15, d1h, target_R=2.0, placebo=True)
    print(f"  {label} RS-1R {len(r1)}  RS-2R {len(r2)}  placebos {len(r1p)}/{len(r2p)} in {time.time()-tA:.0f}s")
    return {"RS-1R": (r1, r1p), "RS-2R": (r2, r2p)}

def show_rows(rows, title):
    print(f"\n=== {title} | blocks = ret%/PF/trades ===")
    t = pd.DataFrame(rows)
    if not len(t):
        print("(no rows)"); return
    print(t[[k for k in t.columns if not k.startswith("_")]].to_string(index=False))

def rob_row(nm, pairs, headline):
    row = {"idea": nm}
    ok = True
    for tag, tr in pairs:
        st = tstats(_window(_tframe(tr), headline))
        row[tag] = f"{fmt(st['pf'],2)}/{fmt(st['ret'])}/{st['tr']}"
        if not (np.isfinite(st["pf"]) and st["pf"] >= 1.15 and st["ret"] > 0):
            ok = False
    row["robust"] = "yes" if ok else "NO"
    return row

def exp_adopt(b, e):
    if not b or not e:
        return False, "need both BTC and ETH baskets"
    if not (b["better_overall"] and e["better_overall"]):
        return False, f"basket ret did not improve on both venues (BTC {b['better_overall']}, ETH {e['better_overall']})"
    if b["considered"] and b["improved"] * 2 < b["considered"]:
        return False, f"not most year blocks (BTC {b['improved']}/{b['considered']}, ETH {e['improved']}/{e['considered']})"
    if e["considered"] and e["improved"] * 2 < e["considered"]:
        return False, f"not most year blocks (BTC {b['improved']}/{b['considered']}, ETH {e['improved']}/{e['considered']})"
    return True, f"basket improved BTC and ETH; year blocks BTC {b['improved']}/{b['considered']}, ETH {e['improved']}/{e['considered']}"

def print_plain_words(VT, ROB, adopt, adopt_why):
    print("\n=== PLAIN WORDS ===")
    if len(VT):
        for _, r in VT.iterrows():
            if r.verdict == "KEEP":
                rb = next((x.get("robust", "?") for x in ROB if x.get("idea") == r.idea), "?")
                print(f"  KEEP  {r.idea}: passes every test (BTC PF {r['BTC PF']}, ETH PF {r['ETH PF']}, placebo {r['placebo PF']}); robust to +-20%: {rb}.")
            elif r.verdict == "WATCH":
                print(f"  WATCH {r.idea}: one miss -> {r.fails}.")
        nd = int((VT.verdict == "DROP").sum())
        drop_ids = list(VT[VT.verdict == "DROP"].idea.unique()) if nd else []
        if nd:
            print(f"  DROP  {nd} ideas failed two or more tests: " + ", ".join(drop_ids))
    print(f"  EXP   {'ADOPT' if adopt else 'DO NOT ADOPT'} the expiry-week skip: {adopt_why}.")
    print("  Paper-trade any KEEP before it gets money; these are standalone 1%-risk backtests, not live-bot size mixes.")
    print("  Z1/Z3 use Hyperliquid-era history only. Official HL 1h candles start at the ~5000-bar candleSnapshot cap (2026-04-28); funding is from 2023-05-12.")

def run_reports(btc, eth, btc15, eth15, hl_bf, bn_bf, hl_b1, bn_b1,
                hl_ef, bn_ef, hl_e1, bn_e1, K8D, K8E, BTC_ENG, ETH_ENG,
                starts, ends, write_csv=True, force_robust=False):
    """Z1, Z3, EXP, RS, ranked table and PLAIN WORDS. Shared by Colab and --smoke."""
    global z1_HOURS
    print("Z1 funding divergence ...", flush=True)
    Z1B = run_z1("BTC", bn_b1 if bn_b1 is not None else btc, hl_bf, bn_bf, K8D, BTC_ENG)
    Z1E = run_z1("ETH", bn_e1 if bn_e1 is not None else eth, hl_ef, bn_ef, K8E, ETH_ENG) if eth is not None else None

    print("Z3 premium dislocation ...", flush=True)
    Z3B = run_z3("BTC", hl_b1, bn_b1, K8D)
    Z3E = run_z3("ETH", hl_e1, bn_e1, K8E) if eth is not None else None

    EXP_BTC = exp_report("BTC", BTC_ENG, starts, ends)
    EXP_ETH = exp_report("ETH", ETH_ENG, starts, ends) if ETH_ENG else None

    print("\nRS RohOnChain session-open ...", flush=True)
    RSB = run_rs("BTC", btc15, btc, K8D)
    RSE = run_rs("ETH", eth15, eth, K8E) if eth is not None else None

    BR, ER = [], []
    if Z1B: BR.append(Z1B["row"])
    if Z3B: BR.append(Z3B["row"])
    if RSB:
        for nm, (tr, ptr) in RSB.items():
            BR.append(idea_row_ex(nm, tr, ptr, K8D, buckets=BUCKETS, headline=HEADLINE_START))
    if Z1E: ER.append(Z1E["row"])
    if Z3E: ER.append(Z3E["row"])
    if RSE:
        for nm, (tr, ptr) in RSE.items():
            ER.append(idea_row_ex(nm, tr, ptr, K8E, buckets=BUCKETS, headline=HEADLINE_START))

    show_rows(BR, "BTC — headline (Z1/Z3 from HL-era, RS from 2017+)")
    if ER:
        show_rows(ER, "ETH — headline")

    if Z1B and Z1B["filt"]:
        print("\n=== Z1 FILTER on live engines — BTC, HL period (skip longs D>=95th, shorts D<=5th) ===")
        print(pd.DataFrame(Z1B["filt"]).to_string(index=False))
    if Z1E and Z1E["filt"]:
        print("\n=== Z1 FILTER on live engines — ETH, HL period ===")
        print(pd.DataFrame(Z1E["filt"]).to_string(index=False))

    if Z3B and Z3B["info"]:
        info = Z3B["info"]
        print("\n=== Z3 event stats — BTC ===")
        print(f"  events {info.get('events', 0)}; median hours extreme->z=0 (or exit) {fmt(info.get('med_rev_h'), 1)}; "
              f"mean {fmt(info.get('mean_rev_h'), 1)}; median hours extreme->stabilize {fmt(info.get('med_stab_h'), 1)}")
    if Z3E and Z3E.get("info"):
        info = Z3E["info"]
        print("=== Z3 event stats — ETH ===")
        print(f"  events {info.get('events', 0)}; median rev-h {fmt(info.get('med_rev_h'), 1)}; "
              f"mean {fmt(info.get('mean_rev_h'), 1)}; median stab-h {fmt(info.get('med_stab_h'), 1)}")

    print("\nPlacebos:", "; ".join(f"{k} = {v}" for k, v in PLACEBO.items()))

    Zideas = [r for r in BR if r["idea"] in ("Z1", "Z3")]
    Rideas = [r for r in BR if r["idea"].startswith("RS")]
    Ze = [r for r in ER if r["idea"] in ("Z1", "Z3")]
    Re = [r for r in ER if r["idea"].startswith("RS")]
    frames = []
    if Zideas:
        frames.append(verdicts_of(Zideas, Ze, early_keys=["2023", "2024"], late_keys=["2025", "2026"]))
    if Rideas:
        frames.append(verdicts_of(Rideas, Re, early_keys=["2017-20"], late_keys=["2021-23", "2024+", "2026"]))
    VT = pd.concat(frames, ignore_index=True) if frames else pd.DataFrame()

    ROB = []
    names = list(VT[VT.verdict == "KEEP"].idea) if len(VT) else []
    if force_robust:
        for nm in ("Z1", "Z3", "RS-1R", "RS-2R"):
            if nm not in names:
                names.append(nm)
    for nm in names:
        try:
            if nm == "Z1" and Z1B:
                z1_HOURS, D, pct = Z1B["hours"], Z1B["D"], Z1B["pct"]
                px = bn_b1 if bn_b1 is not None else btc
                pairs = []
                for m, tag in ((0.8, "x0.8 PF/ret/n"), (1.2, "x1.2 PF/ret/n")):
                    hi = 0.90 if m < 1 else 0.96
                    lo = 0.10 if m < 1 else 0.04
                    tr = z1_standalone(px, D, pct, p_hi=hi, p_lo=lo, ema_n=int(round(20 * m)))
                    pairs.append((tag, tr))
                ROB.append(rob_row(nm, pairs, HL_START))
            elif nm == "Z3" and Z3B:
                pairs = []
                for m, tag in ((0.8, "x0.8 PF/ret/n"), (1.2, "x1.2 PF/ret/n")):
                    tr, _ = z3_trades(hl_b1, bn_b1, z_ext=3.0 * m, z_stab=1.5 * m)
                    pairs.append((tag, tr))
                head = Z3B.get("headline", HL_START)
                ROB.append(rob_row(nm, pairs, head))
            elif nm.startswith("RS") and RSB:
                tgt = 1.0 if nm == "RS-1R" else 2.0
                pairs = []
                for m, tag in ((0.8, "x0.8 PF/ret/n"), (1.2, "x1.2 PF/ret/n")):
                    tr = rs_trades(btc15, btc, target_R=tgt, skip_atr=0.5 * m)
                    pairs.append((tag, tr))
                ROB.append(rob_row(nm, pairs, HEADLINE_START))
        except Exception as e:
            ROB.append({"idea": nm, "robust": f"err {e}"})

    print("\n=== RANKED (pre-declared verdict; BTC headline as above) ===")
    if len(VT):
        print(VT[[k for k in VT.columns if not k.startswith("_")]].to_string(index=False))
    else:
        print("(no standalone ideas to rank)")
    if ROB:
        print("\n=== KEEP robustness (+-20% parameters, BTC) ===")
        print(pd.DataFrame(ROB)[[k for k in pd.DataFrame(ROB).columns if not k.startswith("_")]].to_string(index=False))

    adopt, adopt_why = exp_adopt(EXP_BTC, EXP_ETH)
    print_plain_words(VT, ROB, adopt, adopt_why)

    if write_csv:
        pd.DataFrame(BR).to_csv(OUT_DIR / "batch9_btc.csv", index=False)
        if ER:
            pd.DataFrame(ER).to_csv(OUT_DIR / "batch9_eth.csv", index=False)
        if len(VT):
            VT.to_csv(OUT_DIR / "batch9_verdicts.csv", index=False)
        print(f"\nWrote batch9_btc/eth/verdicts.csv to {OUT_DIR} | runtime {time.time()-T0:.0f}s")
    return dict(BR=BR, ER=ER, VT=VT, ROB=ROB, Z1B=Z1B, Z1E=Z1E, Z3B=Z3B, Z3E=Z3E,
                EXP_BTC=EXP_BTC, EXP_ETH=EXP_ETH, RSB=RSB, RSE=RSE, adopt=adopt, adopt_why=adopt_why)

def run_smoke():
    print("SMOKE: synthetic 1h/15m + venue funding/prices (no real market data)")
    raw = synthetic_1h(n=18000, seed=9, start="2023-02-15")
    assert isinstance(raw, pd.DataFrame) and isinstance(raw["time"], pd.Series)
    d15 = plant_rs_setup(synthetic_15m_from_1h(raw))
    hl_f, bn_f, hl_px, bn_px = synthetic_venues(raw)
    Dn = _norm_d(raw)
    c1 = _c1_trades(Dn); c2 = c2_trades(Dn)
    print(f"  C1 {len(c1)}  C2 {len(c2)}")
    assert len(c1) > 0, "C1 produced 0 trades on synthetic data"
    assert len(c2) > 0, "C2 produced 0 trades on synthetic data"
    Eng = live_engines(raw, fund=bn_f)
    for nm in LIVE_ENGINES:
        n = len(Eng.get(nm) or [])
        print(f"  engine {nm}: {n} trades")
        if n == 0 and nm == "D34":
            d34p = d34_trades(raw, placebo=True)
            print(f"    D34 placebo {len(d34p)}")
        assert n > 0, f"{nm} produced 0 trades on synthetic data"
    hours = np.arange(int(raw.time.iloc[0]) // H1 * H1, int(raw.time.iloc[-1]) + H1, H1, dtype="int64")
    global z1_HOURS
    z1_HOURS = hours
    _, _, D, pct = funding_divergence(hl_f, bn_f, hours)
    z1 = z1_standalone(raw, D, pct, placebo=False)
    z1p = z1_standalone(raw, D, pct, placebo=True)
    print(f"  Z1 {len(z1)}  placebo {len(z1p)}  finite pct {np.isfinite(pct).sum()}")
    assert len(z1) > 0, "Z1 produced 0 trades on synthetic data"
    kept, skipped = filter_trades_z1(Eng["C2"], hours, D, pct)
    print(f"  Z1-filter C2 kept {len(kept)} skipped {skipped}")
    z3, info = z3_trades(hl_px, bn_px, placebo=False)
    z3p, _ = z3_trades(hl_px, bn_px, placebo=True)
    print(f"  Z3 {len(z3)}  placebo {len(z3p)}  events {info}")
    assert len(z3) > 0, "Z3 produced 0 trades on synthetic data"
    ex = last_friday_expiries("2017-01-01", "2017-12-31")
    assert len(ex) == 12 and ex[0].dayofweek == 4 and ex[0].hour == 8
    starts, ends = expiry_windows(ex)
    fake = [dict(src="C1", side=1, t_in=int(ex[0].value // 1_000_000 - 2 * D1),
                 t_out=int(ex[0].value // 1_000_000), entry=100, exit=101, stop=99, risk=0.01,
                 net_R=1.0, ret=0.01, why="TP", weight=1.0, ei=0, xi=1)]
    inn, out = split_expiry(fake, starts, ends)
    assert len(inn) == 1 and len(out) == 0
    rs1 = rs_trades(d15, raw, target_R=1.0, placebo=False)
    rs2 = rs_trades(d15, raw, target_R=2.0, placebo=False)
    rsp = rs_trades(d15, raw, target_R=1.0, placebo=True)
    print(f"  RS-1R {len(rs1)}  RS-2R {len(rs2)}  placebo {len(rsp)}")
    assert len(rs1) > 0, "RS-1R produced 0 trades on synthetic data"
    assert len(rs2) > 0, "RS-2R produced 0 trades on synthetic data"
    s = tstats(_tframe(c1 + c2 + z1 + z3 + rs1))
    print(f"  combined tstats n={s['tr']}")
    # Exercise COCO placebo (RNG) and the R0 open-trade helper on this synthetic series.
    heights = np.array([0.01, 0.02, 0.03])
    _ = coil_setups(market_states(build_day(bn_f)), P0, placebo=True, heights=heights)
    _ = _open_trade(1, 0, float(raw.close.iloc[0]), float(raw.close.iloc[0]) * 0.99, len(raw), raw.close.to_numpy())
    print("Computing K8 baseline + ETH synthetic engines for the report path ...", flush=True)
    K8D = k8_daily(raw)
    eth = synthetic_1h(n=18000, seed=17, start="2023-02-15")
    eth15 = plant_rs_setup(synthetic_15m_from_1h(eth, seed=19))
    hl_ef, bn_ef, hl_e1, bn_e1 = synthetic_venues(eth, seed=21)
    ETH_ENG = live_engines(eth, fund=bn_ef)
    for nm in LIVE_ENGINES:
        assert len(ETH_ENG.get(nm) or []) > 0, f"ETH {nm} produced 0 trades on synthetic data"
    K8E = k8_daily(eth)
    expiries = last_friday_expiries("2013-01-01")
    estart, eend = expiry_windows(expiries)
    out = run_reports(raw, eth, d15, eth15, hl_f, bn_f, hl_px, bn_px,
                      hl_ef, bn_ef, hl_e1, bn_e1, K8D, K8E, Eng, ETH_ENG,
                      estart, eend, write_csv=False, force_robust=True)
    assert out["Z1B"] is not None and out["Z1B"]["row"]["idea"] == "Z1"
    assert out["Z3B"] is not None and out["Z3B"]["row"]["idea"] == "Z3"
    assert out["Z1E"] is not None and out["Z3E"] is not None
    assert out["EXP_BTC"] is not None and out["EXP_ETH"] is not None
    assert out["RSB"] is not None and "RS-1R" in out["RSB"] and "RS-2R" in out["RSB"]
    assert out["RSE"] is not None
    assert len(out["BR"]) >= 4 and len(out["ER"]) >= 4
    assert len(out["VT"]) >= 1
    assert any(r["idea"] == "Z1" for r in out["ROB"]) and any(r["idea"] == "Z3" for r in out["ROB"])
    print(f"SMOKE OK: {time.time()-T0:.1f}s")

if "--smoke" in sys.argv or os.environ.get("BATCH9_SMOKE") == "1":
    run_smoke()
    raise SystemExit(0)

if __name__ != "__main__" and not Path("/content").exists():
    # imported for tests; do not run a backtest or refuse
    raise SystemExit(0)

if not Path("/content").exists() and os.environ.get("BATCH9_ALLOW_REAL") != "1":
    raise SystemExit("Batch 9 refuses to run a real-data backtest outside Colab. Use:  python3 batch9.py --smoke")

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

def must_venue(name):
    d, src = load_venue(name)
    if d is None:
        print(f"  WARNING: {name} not available")
        return None, None
    print(f"  {name}: {src} | {range_of(d)}")
    return d, src

hl_bf, _ = must_venue("hl_btc_funding.csv.gz")
bn_bf, _ = must_venue("bn_btc_funding.csv.gz")
hl_b1, _ = must_venue("hl_btc_1h.csv.gz")
bn_b1, _ = must_venue("bn_btcperp_1h.csv.gz")
hl_ef, _ = must_venue("hl_eth_funding.csv.gz")
bn_ef, _ = must_venue("bn_eth_funding.csv.gz")
hl_e1, _ = must_venue("hl_eth_1h.csv.gz")
bn_e1, _ = must_venue("bn_ethperp_1h.csv.gz")

btc15, S15 = load_15m("btc")
if btc15 is not None:
    print(f"BTC 15m: {S15} | {len(btc15):,} rows")
eth, ESRC = load_asset("eth")
if eth is not None:
    eth = fix_eth_bar(eth)
    print(f"ETH DATA: {ESRC} | {len(eth):,} rows")
    print("Computing K8 baseline on ETH 1h ...", flush=True)
    K8E = k8_daily(eth)
else:
    K8E = None
eth15, ES15 = load_15m("eth")
if eth15 is not None:
    print(f"ETH 15m: {ES15} | {len(eth15):,} rows")

expiries = last_friday_expiries("2013-01-01")
print(f"  options expiries: {len(expiries)} last Fridays (08:00 UTC)")
ESTART, EEND = expiry_windows(expiries)

print("Computing live engines on BTC 1h ...", flush=True)
tE = time.time()
BTC_ENG = live_engines(btc, fund=bn_bf if bn_bf is not None else load_funding())
print("  BTC engines:", ", ".join(f"{k} {len(v)}" for k, v in BTC_ENG.items()), f"in {time.time()-tE:.0f}s")
ETH_ENG = {}
if eth is not None:
    print("Computing live engines on ETH 1h ...", flush=True)
    tE = time.time()
    ETH_ENG = live_engines(eth, fund=bn_ef)
    print("  ETH engines:", ", ".join(f"{k} {len(v)}" for k, v in ETH_ENG.items()), f"in {time.time()-tE:.0f}s")


print("Z1 / Z3 / EXP / RS + ranked output ...", flush=True)
run_reports(btc, eth, btc15, eth15, hl_bf, bn_bf, hl_b1, bn_b1,
            hl_ef, bn_ef, hl_e1, bn_e1, K8D, K8E, BTC_ENG, ETH_ENG,
            ESTART, EEND, write_csv=True, force_robust=False)
