# ===== oslib — shared Colab backtest library for osom-boba =====
# Hosted at https://osom-boba.pages.dev/colab/oslib.py
# In Colab:
#   !wget -q -O oslib.py https://osom-boba.pages.dev/colab/oslib.py
#   from oslib import *
# Real market data is refused outside Colab. Use selftest() on the box.
"""Shared BTC/ETH perp backtest helpers (data, indicators, live engines, simulate, verdicts)."""
from __future__ import annotations
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)

__version__ = "1.0"
SITE = "https://osom-boba.pages.dev/colab/"
UA = "osom-oslib/1.0"
FNG_URL = "https://api.alternative.me/fng/?limit=0&format=json"

H1 = 3_600_000; D1 = 24 * H1; H4 = 4 * H1; H12 = 12 * H1; M15 = 15 * 60 * 1000
TF_MS = {"15m": M15, "1h": H1, "4h": H4, "1d": D1}
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
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"
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"]
LIVE_RISK = {"K8": 0.02, "COCO": 0.03, "B1G": 0.03, "S5": 0.03,
             "C1": 0.01, "C2": 0.01, "V7": 0.01, "R0": 0.01, "MOM30": 0.01, "D34": 0.01}
TRADE_FIELDS = ("entry_time", "exit_time", "side", "entry", "stop", "exit", "R", "why")

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

def _allow_real():
    return in_colab() or os.environ.get("OSLIB_ALLOW_REAL") == "1"

def _require_real(what):
    if not _allow_real():
        raise RuntimeError(
            f"oslib.{what}() refuses real market data outside Colab. "
            "Run in Colab, or use selftest() / synthetic_1h() on the box."
        )

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

def fix_eth_bar(e):
    t0 = ms("2017-08-22 04:00"); k = np.where(e["time"].values == t0)[0]
    if not len(k) or k[0] == 0 or k[0] >= len(e) - 1:
        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:
        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 _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)) if not url.endswith(".json") else b

def _fetch_bytes(url, timeout=120):
    with urlopen(Request(url, headers={"User-Agent": UA}), timeout=timeout) as r:
        return r.read()

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})
    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) > 0 else 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 resample_ohlcv(df, period_ms):
    """Resample an OHLCV frame (time in ms) to a coarser bar size."""
    d = df if isinstance(df, pd.DataFrame) else pd.DataFrame(df)
    t = d["time"].to_numpy(dtype="int64")
    g = t // int(period_ms)
    r = pd.DataFrame({"g": g, "open": d["open"], "high": d["high"], "low": d["low"],
                      "close": d["close"], "volume": d["volume"] if "volume" in d.columns else 0.0})
    a = r.groupby("g").agg(open=("open", "first"), high=("high", "max"), low=("low", "min"),
                           close=("close", "last"), volume=("volume", "sum"))
    a["time"] = a.index.values * int(period_ms)
    return a.reset_index(drop=True)

def _hosted_or_content(name):
    """Load a hosted colab file. Content/ cache first; never reads the box deploy tree."""
    if Path("/content").exists():
        p = Path("/content") / name
        if p.exists() and p.stat().st_size > 100:
            try:
                return pd.read_csv(p), str(p)
            except Exception:
                pass
    url = SITE + name
    print(f"Downloading {url} ...", flush=True)
    return _fetch(url), url

def load(asset, tf="1h"):
    """Load hosted BTC/ETH OHLCV. tf in {'15m','1h','4h','1d'}. Colab only."""
    _require_real("load")
    asset = str(asset).lower().strip()
    if asset not in ("btc", "eth"):
        raise ValueError("load(asset) asset must be 'btc' or 'eth'")
    tf = str(tf).lower().strip()
    if tf not in TF_MS:
        raise ValueError(f"load(..., tf) must be one of {tuple(TF_MS)}")
    if tf == "15m":
        raw, src = _hosted_or_content(f"{asset}_15m_full.csv.gz")
        d = _norm(raw)
    else:
        raw, src = _hosted_or_content(f"{asset}_1h_full.csv.gz")
        d = _norm(raw)
        if d is not None and asset == "eth":
            d = fix_eth_bar(d)
        if d is not None and tf != "1h":
            d = resample_ohlcv(d, TF_MS[tf])
    if d is None or len(d) < 100:
        raise RuntimeError(f"load({asset!r}, {tf!r}) failed from {src}")
    print(f"  {asset} {tf}: {src} | {len(d):,} bars", flush=True)
    return d

def funding(asset="btc", venue="binance"):
    """Funding history. venue 'binance' (8h, years) or 'hl'/'hyperliquid' (hourly from 2023-05). Colab only."""
    _require_real("funding")
    asset = str(asset).lower().strip()
    venue = str(venue).lower().strip()
    if venue in ("hl", "hyperliquid", "hyperliquid"):
        name = f"hl_{asset}_funding.csv.gz"
    elif venue in ("binance", "bn"):
        name = f"bn_{asset}_funding.csv.gz" if asset in ("btc", "eth") else "btc_funding_8h.csv"
        # bn_* is the longer perp series; fall back to btc_funding_8h
    else:
        raise ValueError("funding venue must be 'binance' or 'hl'")
    try:
        raw, src = _hosted_or_content(name)
        d = _norm_venue(raw, name)
    except Exception as e:
        if venue in ("binance", "bn") and asset == "btc":
            raw, src = _hosted_or_content("btc_funding_8h.csv")
            d = _norm_venue(raw, "btc_funding_8h.csv")
        else:
            raise RuntimeError(f"funding({asset!r}, {venue!r}) failed: {e}") from e
    if d is None or not len(d):
        raise RuntimeError(f"funding({asset!r}, {venue!r}) returned no rows")
    print(f"  funding {asset}/{venue}: {src} | {len(d):,} rows", flush=True)
    return d

def hl_candles(asset="btc"):
    """Hyperliquid 1h perp candles (public snapshot cap, ~5000 bars). Colab only."""
    _require_real("hl_candles")
    asset = str(asset).lower().strip()
    name = f"hl_{asset}_1h.csv.gz"
    raw, src = _hosted_or_content(name)
    d = _norm_venue(raw, name)
    if d is None or not len(d):
        raise RuntimeError(f"hl_candles({asset!r}) failed")
    print(f"  hl {asset} 1h: {src} | {len(d):,} bars", flush=True)
    return d

def _parse_etf(frames):
    out = []
    for f in frames:
        cl = {c.lower().strip(): c for c in f.columns}
        dc = next((cl[c] for c in ("date", "day", "time") if c in cl), None)
        if dc is None:
            continue
        d = pd.to_datetime(f[dc], utc=True, errors="coerce")
        if "flow_usd" in cl:
            v = pd.to_numeric(f[cl["flow_usd"]], errors="coerce")
            if np.nanmax(np.abs(v.values)) < 1e6 and "flow_usdm" in cl:
                v = pd.to_numeric(f[cl["flow_usdm"]], errors="coerce") * 1_000_000.0
        elif "flow_usdm" in cl:
            v = pd.to_numeric(f[cl["flow_usdm"]], errors="coerce") * 1_000_000.0
        elif "total" in cl:
            v = pd.to_numeric(f[cl["total"]], errors="coerce") * 1_000_000.0
        else:
            continue
        out.append(pd.DataFrame({"date": d.dt.floor("D"), "flow_usd": v}).dropna())
    if not out:
        return None
    return pd.concat(out).drop_duplicates("date", keep="last").sort_values("date").reset_index(drop=True)

def etf_flows():
    """Daily US spot BTC ETF net flows (USD) from the hosted Farside extract. Colab only."""
    _require_real("etf_flows")
    raw, src = _hosted_or_content("btc_etf_flows.csv.gz")
    e = _parse_etf([raw])
    if e is None or not len(e):
        raise RuntimeError("etf_flows() failed")
    print(f"  etf flows: {src} | {len(e)} days", flush=True)
    return e

def _parse_fng(raw_bytes):
    js = json.loads(raw_bytes.decode() if isinstance(raw_bytes, (bytes, bytearray)) else raw_bytes)
    rows = []
    for x in js.get("data") or []:
        ts = int(x["timestamp"])
        ts_ms = ts * 1000 if ts < 1e11 else ts
        rows.append((ts_ms, float(x["value"])))
    if not rows:
        return None
    df = pd.DataFrame(rows, columns=["time", "fng"]).sort_values("time").drop_duplicates("time")
    df["day"] = pd.to_datetime(df["time"], unit="ms", utc=True).dt.floor("D")
    return df

def fng():
    """CNN Fear & Greed daily index (hosted if present, else api.alternative.me). Colab only."""
    _require_real("fng")
    # Prefer a hosted snapshot if we ever add one; otherwise the public API (via oslib only).
    for name in ("fng.csv.gz", "fng_alternative.json"):
        try:
            raw, src = _hosted_or_content(name)
            if name.endswith(".json"):
                # _fetch on json may have failed; try bytes
                pass
            if isinstance(raw, pd.DataFrame) and "fng" in raw.columns:
                d = raw.copy()
                if "day" not in d.columns and "time" in d.columns:
                    d["day"] = pd.to_datetime(d["time"], unit="ms", utc=True).dt.floor("D")
                print(f"  fng: {src} | {len(d)} days", flush=True)
                return d
        except Exception:
            continue
    print(f"Downloading {FNG_URL} ...", flush=True)
    raw = _fetch_bytes(FNG_URL, timeout=30)
    d = _parse_fng(raw)
    if d is None:
        raise RuntimeError("fng() failed")
    print(f"  fng: alternative.me | {len(d)} days", flush=True)
    return d

def expiry_days(start="2013-01-01", end=None):
    """Last-Friday-of-month BTC options expiries at 08:00 UTC (calendar only; safe on the box)."""
    return last_friday_expiries(start, end)

# ===== extracted internals from batch9 (proven engines, stats, synthetics) =====
# Do not call these from z.ai scripts; use the public API below.
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

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


# ---------------------------------------------------------------------------
# Public indicator wrappers (plus donchian / er / rsi, not named in batch9)
# ---------------------------------------------------------------------------
def _arr(x):
    if isinstance(x, pd.Series):
        return x.to_numpy(dtype=float)
    return np.asarray(x, dtype=float)

def sma(x, n):
    return _sma(_arr(x), int(n))

def ema(x, n):
    return _ema(_arr(x), int(n))

def donchian(h, l=None, n=20):
    """Donchian channel. Returns upper, lower, mid. If l is None, `h` is used as the price."""
    hs, ls = _arr(h), _arr(h if l is None else l)
    up, lo = rolling_max(hs, int(n)), rolling_min(ls, int(n))
    return up, lo, 0.5 * (up + lo)

def er(close, n=10):
    """Kaufman efficiency ratio: |close-close[n]| / sum(|changes|) over n bars."""
    c = _arr(close)
    n = int(n)
    dist = np.abs(c - np.r_[np.full(n, np.nan), c[:-n]])
    chg = np.abs(np.diff(c, prepend=c[0]))
    path = pd.Series(chg).rolling(n, min_periods=n).sum().to_numpy()
    with np.errstate(invalid="ignore", divide="ignore"):
        out = dist / path
    out[path <= 0] = np.nan
    return out

def rsi(close, n=14):
    """Wilder RSI."""
    x = _arr(close)
    d = np.diff(x, prepend=x[0])
    up = wilder(np.maximum(d, 0), int(n))
    dn = wilder(np.maximum(-d, 0), int(n))
    return 100 - 100 / (1 + up / np.maximum(dn, 1e-12))

def chop(h, l, c, n=14):
    return chop_arr_tr(_arr(h), _arr(l), _arr(c), int(n))

def supertrend(h, l, c, n=10, f=3.0):
    """Supertrend direction: +1 up, -1 down (batch9/C1 port)."""
    return supertrend_dir(_arr(h), _arr(l), _arr(c), int(n), float(f))

# ---------------------------------------------------------------------------
# Standard trade records
# ---------------------------------------------------------------------------
def _std_trade(t, src=""):
    if not isinstance(t, dict):
        t = dict(t)
    side = int(t.get("side", 0))
    entry_time = t.get("entry_time", t.get("t_in"))
    exit_time = t.get("exit_time", t.get("t_out"))
    entry = t.get("entry", t.get("entry_px", np.nan))
    stop = t.get("stop", np.nan)
    exit_px = t.get("exit", t.get("exit_px", np.nan))
    R = t.get("R", t.get("net_R", np.nan))
    why = t.get("why", t.get("kind", ""))
    risk = t.get("risk", np.nan)
    ret = t.get("ret", np.nan)
    # Recover prices from risk/move when engines recorded only fractions.
    if (not np.isfinite(entry) or not np.isfinite(stop) or not np.isfinite(exit_px)):
        move = t.get("move", np.nan)
        # cannot recover entry without the bar; leave NaN
        if np.isfinite(entry) and np.isfinite(risk) and risk > 0 and not np.isfinite(stop):
            stop = entry - side * risk * entry
        if np.isfinite(entry) and np.isfinite(move) and not np.isfinite(exit_px):
            exit_px = entry * (1.0 + side * move)
    if np.isfinite(entry) and np.isfinite(stop) and entry and (not np.isfinite(risk) or risk <= 0):
        risk = abs(entry - stop) / entry
    if np.isfinite(entry) and entry and np.isfinite(exit_px) and (not np.isfinite(ret)):
        ret = side * (exit_px / entry - 1.0) - 2 * COST
    if (not np.isfinite(R)) and np.isfinite(ret) and np.isfinite(risk) and risk > 0:
        R = ret / risk
    out = dict(entry_time=int(entry_time) if entry_time is not None and np.isfinite(entry_time) else 0,
               exit_time=int(exit_time) if exit_time is not None and np.isfinite(exit_time) else 0,
               side=side,
               entry=float(entry) if np.isfinite(entry) else np.nan,
               stop=float(stop) if np.isfinite(stop) else np.nan,
               exit=float(exit_px) if np.isfinite(exit_px) else np.nan,
               R=float(R) if np.isfinite(R) else np.nan,
               why=str(why) if why is not None else "",
               src=t.get("src", src) or src,
               weight=float(t.get("weight", 1.0)),
               risk=float(risk) if np.isfinite(risk) else np.nan,
               ret=float(ret) if np.isfinite(ret) else np.nan,
               ei=int(t["ei"]) if t.get("ei") is not None and np.isfinite(t.get("ei", np.nan)) else 0,
               xi=int(t["xi"]) if t.get("xi") is not None and np.isfinite(t.get("xi", np.nan)) else 0)
    # aliases used by idea_row_ex / _tframe
    out["t_in"] = out["entry_time"]
    out["t_out"] = out["exit_time"]
    out["net_R"] = out["R"]
    return out

def standardize(trades, src=""):
    return [_std_trade(t, src=src) for t in (trades or [])]

# ---------------------------------------------------------------------------
# Generic bar-accurate simulator
# ---------------------------------------------------------------------------
def _is_frac_array(x):
    v = np.asarray(x, dtype=float)
    v = v[np.isfinite(v)]
    return len(v) > 0 and np.nanmax(v) < 0.5 and np.nanmin(v) > 0

def _stop_px(stop, entry, side, i):
    if np.isscalar(stop) or (isinstance(stop, (float, int, np.floating, np.integer))):
        fr = float(stop)
        if fr <= 0:
            raise ValueError("stop fraction must be positive")
        return entry - side * fr * entry
    s = np.asarray(stop, dtype=float)
    val = float(s[i]) if i < len(s) else float(s.flat[0])
    if _is_frac_array(s):
        return entry - side * val * entry
    return val

def _target_px(target, entry, side, risk_px, i):
    if target is None:
        return np.nan
    if np.isscalar(target) or isinstance(target, (float, int, np.floating, np.integer)):
        return entry + side * float(target) * risk_px
    t = np.asarray(target, dtype=float)
    if _is_frac_array(t) is False and (np.nanmax(np.abs(t[np.isfinite(t)] - entry)) if np.isfinite(entry) else 1) > entry * 0.2:
        # prices
        return float(t[i]) if i < len(t) else np.nan
    # R-multiples per bar, or a price array close to entry (treat as prices if around entry)
    val = float(t[i]) if i < len(t) else np.nan
    if np.isfinite(val) and 0 < val < 20 and abs(val - entry) / max(entry, 1e-12) > 0.5:
        return entry + side * val * risk_px
    return val

def simulate(df, signals, stop, target=None, time_stop=None, be_at=None, partial=None, trail=None,
             entry="next_open", check=True):
    """Bar-accurate single-position simulator.

    signals : array of -1/0/+1 aligned to df (signal on bar i).
    stop    : stop *price* array aligned to df, or a positive fraction of entry (e.g. 0.02).
    target  : target *price* array, an R-multiple (e.g. 2.0), or None.
    time_stop : bars from the fill bar, or None.
    be_at   : move stop to entry after this many R (e.g. 1.0), or None.
    partial : (r_level, fraction) take `fraction` off at r_level R, remainder continues.
    trail   : (start_R, giveback_R) chandelier in R once start_R is seen, or
              dict(atr=array, mult=3.0) ATR trail from the excursion extreme.
    entry   : 'next_open' (fill at next bar open) or 'stop_order' (fill when price
              trades through the signal-bar high/low).
    check   : assert a non-gap stop exit is never worse than about -1R minus costs.

    Intrabar conservatism: stop is checked before target on the same bar.
    Costs: 0.12%/side (FEE+SLIP), charged on entry and on each exit notional.
    """
    d = df if isinstance(df, pd.DataFrame) else pd.DataFrame(df)
    t = d["time"].to_numpy(dtype="int64")
    o = d["open"].to_numpy(dtype=float)
    h = d["high"].to_numpy(dtype=float)
    l = d["low"].to_numpy(dtype=float)
    c = d["close"].to_numpy(dtype=float)
    n = len(t)
    if entry not in ("next_open", "stop_order"):
        raise ValueError("entry must be 'next_open' or 'stop_order'")
    sig = np.asarray(signals)
    if isinstance(signals, pd.Series):
        sig = signals.to_numpy()
    if len(sig) != n:
        raise ValueError(f"signals length {len(sig)} != df length {n}")
    sig = np.sign(pd.to_numeric(sig, errors="coerce")).fillna(0).astype(int) if False else np.sign(sig.astype(float)).astype(int)
    sig = np.where(np.isfinite(sig), sig, 0).astype(int)
    part = None
    if partial is not None:
        part = (float(partial[0]), float(partial[1]))
        if not (0 < part[1] < 1):
            raise ValueError("partial fraction must be in (0, 1)")
    trades = []
    i = 0
    while i < n - 1:
        s = int(sig[i])
        if s == 0:
            i += 1
            continue
        if entry == "next_open":
            ei = i + 1
            if ei >= n:
                break
            fill = float(o[ei])
        else:
            trig = float(h[i]) if s > 0 else float(l[i])
            ei = None
            fill = None
            for k in range(i + 1, n):
                hit = (h[k] >= trig) if s > 0 else (l[k] <= trig)
                if hit:
                    fill = max(float(o[k]), trig) if s > 0 else min(float(o[k]), trig)
                    ei = k
                    break
            if ei is None:
                i += 1
                continue
        stp0 = _stop_px(stop, fill, s, i)
        if not np.isfinite(stp0) or s * (fill - stp0) <= 0:
            i = ei + 1 if entry == "next_open" else i + 1
            continue
        risk_px = abs(fill - stp0)
        risk = risk_px / fill if fill else np.nan
        if not (np.isfinite(risk) and risk > 0):
            i = ei + 1
            continue
        tgt0 = _target_px(target, fill, s, risk_px, i)
        # Walk
        stp = float(stp0)
        be_hit = False
        rem = 1.0
        legs = []  # (weight, px)
        why_last = "OPEN"
        exit_px = float(c[-1])
        xi = n - 1
        part_done = False
        peak_px = fill
        atr_tr = None
        atr_mult = None
        if isinstance(trail, dict):
            atr_tr = np.asarray(trail.get("atr"), dtype=float)
            atr_mult = float(trail.get("mult", 3.0))
        for j in range(ei, n):
            hh, ll, oo, cc = h[j], l[j], o[j], c[j]
            if s > 0:
                peak_px = max(peak_px, hh)
            else:
                peak_px = min(peak_px, ll)
            mfe_R = s * (peak_px - fill) / risk_px if risk_px else 0.0
            if be_at is not None and not be_hit and mfe_R >= float(be_at):
                be_hit = True
                stp = fill
            if trail is not None:
                if atr_tr is not None and j < len(atr_tr) and np.isfinite(atr_tr[j]):
                    cand = peak_px - s * atr_mult * atr_tr[j]
                    stp = max(stp, cand) if s > 0 else min(stp, cand)
                elif isinstance(trail, (tuple, list)) and mfe_R >= float(trail[0]):
                    give = float(trail[1]) * risk_px
                    cand = peak_px - s * give
                    stp = max(stp, cand) if s > 0 else min(stp, cand)
            hit_stop = (ll <= stp) if s > 0 else (hh >= stp)
            hit_tgt = np.isfinite(tgt0) and ((hh >= tgt0) if s > 0 else (ll <= tgt0))
            hit_part = (part is not None and not part_done and
                        ((hh >= fill + s * part[0] * risk_px) if s > 0 else (ll <= fill + s * part[0] * risk_px)))
            if hit_stop:
                px = min(stp, oo) if s > 0 else max(stp, oo)
                legs.append((rem, float(px)))
                why_last = "BE" if be_hit and abs(px - fill) / fill < 1e-9 else "SL"
                exit_px, xi = float(px), j
                rem = 0.0
                break
            if hit_part:
                pxi = fill + s * part[0] * risk_px
                px = max(pxi, oo) if s > 0 else min(pxi, oo)
                w = part[1] * rem
                legs.append((w, float(px)))
                rem -= w
                part_done = True
            if hit_tgt:
                px = max(tgt0, oo) if s > 0 else min(tgt0, oo)
                legs.append((rem, float(px)))
                why_last = "TP1+TP" if part_done else "TP"
                exit_px, xi = float(px), j
                rem = 0.0
                break
            if time_stop is not None and (j - ei) >= int(time_stop):
                legs.append((rem, float(cc)))
                why_last = "TIME"
                exit_px, xi = float(cc), j
                rem = 0.0
                break
        else:
            legs.append((rem, float(c[-1])))
            why_last = "OPEN"
            exit_px, xi = float(c[-1]), n - 1
            rem = 0.0
        # House cost: 2*COST on a single full exit (matches walk_1h / _mk_trade).
        # Partials use the C1 convention: entry COST + COST * px/entry on each exit leg.
        if len(legs) == 1:
            ret = s * (legs[0][1] / fill - 1.0) - 2 * COST
        else:
            ret = -COST
            for w, px in legs:
                ret += w * (s * (px / fill - 1.0) - COST * px / fill)
        R = ret / risk if risk > 0 else np.nan
        # Gap check only for a full remaining stop exit (no partial leftover confusion)
        if check and why_last == "SL" and np.isfinite(R) and risk > 0:
            # Non-gap: exit bar open did not skip through the live stop (stp may be BE).
            # Conservative original-stop comparison: if open didn't skip original stop, R >= -1 - costs.
            gap = (o[xi] < stp0) if s > 0 else (o[xi] > stp0)
            if not gap:
                floor = -1.0 - (2 * COST) / risk - 1e-9
                if R < floor - 1e-6:
                    raise AssertionError(
                        f"simulate: non-gap stop exit R={R:.6f} is worse than -1R minus costs ({floor:.6f})"
                    )
        trades.append(_std_trade(dict(src="SIM", side=s, t_in=int(t[ei]), t_out=int(t[xi]),
                                      entry=fill, stop=float(stp0), exit=exit_px, net_R=R, ret=ret,
                                      why=why_last, risk=risk, weight=1.0, ei=ei, xi=xi)))
        i = xi + 1
    return trades

# ---------------------------------------------------------------------------
# Engines, evaluate, verdict, robustness, overlay, paired test, report
# ---------------------------------------------------------------------------
_K8_CACHE = {}

def _k8_for(df):
    key = (id(df), len(df), int(df["time"].iloc[0]), int(df["time"].iloc[-1]))
    if key not in _K8_CACHE:
        _K8_CACHE[key] = k8_daily(df)
    return _K8_CACHE[key]

def engines(asset, fund=None):
    """All 10 live engines (K8, V7, B1G, S5, COCO, C1, C2, R0, MOM30, D34) as standard trade lists.
    `asset` is 'btc'/'eth' (Colab, loads 1h) or a 1h OHLCV DataFrame (synthetic-safe)."""
    if isinstance(asset, str):
        df = load(asset, "1h")
    else:
        df = asset if isinstance(asset, pd.DataFrame) else pd.DataFrame(asset)
    raw = live_engines(df, fund=fund)
    out = {}
    t = df["time"].to_numpy(dtype="int64")
    o = df["open"].to_numpy(dtype=float)
    # Enrich run()-style trades that stored only t_in / risk / move.
    idx = {int(tt): k for k, tt in enumerate(t)}
    for nm, trs in raw.items():
        std = []
        for tr in trs:
            d = dict(tr)
            if (not np.isfinite(d.get("entry", np.nan))) and d.get("t_in") in idx:
                j = idx[int(d["t_in"])]
                d["entry"] = float(o[j])
                if np.isfinite(d.get("risk", np.nan)) and d["risk"] > 0:
                    d["stop"] = d["entry"] - int(d["side"]) * float(d["risk"]) * d["entry"]
                move = d.get("move", np.nan)
                if np.isfinite(move):
                    d["exit"] = d["entry"] * (1.0 + int(d["side"]) * float(move))
            std.append(_std_trade(d, src=nm))
        out[nm] = std
    return out

def evaluate(name, trades, placebo_trades, asset, headline=HEADLINE_START, buckets=None):
    """Standard idea row: PF, ret%, DD, MAR, year blocks, corrK8, placebo. Headline 2017+."""
    buckets = buckets or BUCKETS
    tr = standardize(trades, src=name)
    ptr = standardize(placebo_trades or [], src=name)
    k8d = None
    if isinstance(asset, str) and _allow_real():
        k8d = _k8_for(load(asset, "1h"))
    elif isinstance(asset, pd.Series):
        k8d = asset
    elif isinstance(asset, pd.DataFrame):
        k8d = _k8_for(asset)
    row = idea_row_ex(name, tr, ptr, k8d, buckets=buckets, headline=headline)
    row["asset"] = asset if isinstance(asset, str) else getattr(asset, "name", "df")
    return row

def verdict(rows, eth_rows=None, early_keys=None, late_keys=None):
    """Pre-declared KEEP / WATCH / DROP table. `rows` are evaluate() rows for BTC (or a combined list)."""
    early_keys = early_keys or ["2017-20"]
    late_keys = late_keys or ["2021-23", "2024+", "2026"]
    BR, ER = rows, (eth_rows or [])
    if eth_rows is None and rows and any(str(r.get("asset", "")).lower() == "eth" for r in rows):
        BR = [r for r in rows if str(r.get("asset", "")).lower() != "eth"]
        ER = [r for r in rows if str(r.get("asset", "")).lower() == "eth"]
    return verdicts_of(BR, ER, early_keys, late_keys)

def robustness(fn, params, scales=(0.8, 1.2), keys=None, headline=HEADLINE_START):
    """Vary each numeric param in `params` by +/-20% (or `scales`). `fn(**params)` -> trade list."""
    params = dict(params)
    keys = list(keys) if keys is not None else [k for k, v in params.items()
                                               if isinstance(v, (int, float, np.integer, np.floating))
                                               and not isinstance(v, bool)]
    base = standardize(fn(**params))
    bh = tstats(_window(_tframe(base), headline))
    rows = [{"tag": "base", "param": "-", "scale": 1.0,
             "PF": fmt(bh["pf"], 2), "ret%": fmt(bh["ret"]), "n": bh["tr"],
             "_pf": bh["pf"], "_ret": bh["ret"], "_n": bh["tr"]}]
    for k in keys:
        for sc in scales:
            p = dict(params)
            raw = params[k]
            p[k] = type(raw)(raw * sc) if not isinstance(raw, float) else float(raw) * sc
            if isinstance(raw, int) or isinstance(raw, np.integer):
                p[k] = max(1, int(round(raw * sc)))
            try:
                tr = standardize(fn(**p))
            except Exception as e:
                rows.append({"tag": f"{k} x{sc}", "param": k, "scale": sc, "PF": "err", "ret%": str(e)[:40],
                             "n": 0, "_pf": np.nan, "_ret": np.nan, "_n": 0})
                continue
            st = tstats(_window(_tframe(tr), headline))
            rows.append({"tag": f"{k} x{sc}", "param": k, "scale": sc,
                         "PF": fmt(st["pf"], 2), "ret%": fmt(st["ret"]), "n": st["tr"],
                         "_pf": st["pf"], "_ret": st["ret"], "_n": st["tr"]})
    return pd.DataFrame(rows)

def overlay(engines_map, mask_or_multiplier, start=HEADLINE_START):
    """Apply a mask or size multiplier to the live-risk basket (K8 2%; COCO/B1G/S5 3%; others 1%).

    mask_or_multiplier:
      - callable(engine_name, trade) -> bool or float (0 = skip)
      - dict engine_name -> float
      - pandas Series indexed by entry_time (ms) with multipliers (reindexed to each trade)
    Returns dict with baseline vs overlay basket stats and the filtered trade map.
    """
    def _mult(nm, t):
        if callable(mask_or_multiplier):
            v = mask_or_multiplier(nm, t)
        elif isinstance(mask_or_multiplier, dict) and not isinstance(mask_or_multiplier, pd.Series):
            v = mask_or_multiplier.get(nm, 1.0)
        elif isinstance(mask_or_multiplier, pd.Series):
            try:
                v = mask_or_multiplier.reindex([t["entry_time"]], method="ffill").iloc[0]
            except Exception:
                v = np.nan
        else:
            v = mask_or_multiplier
        if isinstance(v, (bool, np.bool_)):
            return 1.0 if v else 0.0
        return float(v) if np.isfinite(v) else 0.0

    def _pnl(t, risk_pct):
        r, nr = t.get("risk", np.nan), t.get("R", t.get("net_R", np.nan))
        if not (np.isfinite(r) and r > 0 and np.isfinite(nr)):
            return 0.0
        return float(nr * min(float(risk_pct), r))

    def _basket(use_overlay):
        ev = []
        kept = {nm: [] for nm in engines_map}
        t0 = ms(start)
        for nm, trs in engines_map.items():
            base = LIVE_RISK.get(nm, RISK)
            for t in trs:
                tt = _std_trade(t, src=nm)
                if tt["exit_time"] < t0:
                    continue
                m = _mult(nm, tt) if use_overlay else 1.0
                if m <= 0:
                    continue
                ev.append((tt["exit_time"], _pnl(tt, base * m)))
                kept[nm].append(tt)
        ev.sort(key=lambda x: x[0])
        eq = 1.0; peak = 1.0; mdd = 0.0
        by = {}
        for ts, pnl in ev:
            by[ts] = by.get(ts, 0.0) + pnl
        for ts in sorted(by):
            eq *= (1.0 + by[ts])
            peak = max(peak, eq)
            mdd = min(mdd, eq / peak - 1.0)
        ret = 100 * (eq - 1.0)
        dd = 100 * mdd
        return dict(ret=ret, maxDD=dd, MAR=(ret / abs(dd) if dd < 0 else np.nan),
                    end=10_000 * eq, n=len(ev), eq=eq), kept

    base_s, _ = _basket(False)
    ov_s, kept = _basket(True)
    return dict(baseline=base_s, overlay=ov_s, trades=kept,
                better=ov_s["ret"] > base_s["ret"])

def paired_exit_test(trades_a, trades_b, n_boot=2000, seed=0, label_a="A", label_b="B"):
    """Pair trades by (entry_time, side), compare mean R. Bootstrap CI on mean(R_a - R_b)."""
    def _k(t):
        tt = _std_trade(t)
        return (int(tt["entry_time"]), int(tt["side"]))

    A = {_k(t): _std_trade(t) for t in trades_a}
    B = {_k(t): _std_trade(t) for t in trades_b}
    keys = sorted(set(A) & set(B))
    if not keys:
        return dict(n=0, mean_diff=np.nan, ci_lo=np.nan, ci_hi=np.nan, p_boot=np.nan,
                    mean_a=np.nan, mean_b=np.nan, label_a=label_a, label_b=label_b)
    da = np.array([A[k]["R"] for k in keys], dtype=float)
    db = np.array([B[k]["R"] for k in keys], dtype=float)
    ok = np.isfinite(da) & np.isfinite(db)
    da, db = da[ok], db[ok]
    diff = da - db
    n = len(diff)
    mean = float(diff.mean()) if n else np.nan
    rng = np.random.default_rng(seed)
    if n:
        boots = np.empty(int(n_boot))
        for i in range(int(n_boot)):
            boots[i] = diff[rng.integers(0, n, n)].mean()
        ci_lo, ci_hi = np.quantile(boots, [0.025, 0.975])
        # two-sided: share of bootstrap means on the other side of 0
        p = 2 * min((boots >= 0).mean(), (boots <= 0).mean())
        p = float(min(1.0, p))
    else:
        ci_lo = ci_hi = p = np.nan
    return dict(n=n, mean_diff=mean, ci_lo=float(ci_lo), ci_hi=float(ci_hi), p_boot=p,
                mean_a=float(da.mean()) if n else np.nan, mean_b=float(db.mean()) if n else np.nan,
                label_a=label_a, label_b=label_b)

def report(rows, eth_rows=None, title="RESULTS", out_dir=None, notes=None, write_csv=True):
    """Compact tables, pre-declared verdict, PLAIN WORDS, optional CSVs."""
    out_dir = Path(out_dir) if out_dir is not None else OUT_DIR
    BR = list(rows or [])
    ER = list(eth_rows or [])
    def _show(rs, ttl):
        print(f"\n=== {ttl} | blocks = ret%/PF/trades ===")
        if not rs:
            print("(no rows)"); return
        t = pd.DataFrame(rs)
        cols = [k for k in t.columns if not k.startswith("_") and k != "asset"]
        print(t[cols].to_string(index=False))
    _show(BR, f"{title} — BTC 2017+" if ER or any(str(r.get("asset","")).lower()=="btc" for r in BR) else f"{title} — 2017+")
    if ER:
        _show(ER, f"{title} — ETH 2017+")
    VT = verdict(BR, ER)
    print("\n=== RANKED (pre-declared verdict) ===")
    if VT is not None and len(VT):
        print(VT[[k for k in VT.columns if not k.startswith("_")]].to_string(index=False))
    else:
        print("(no rows to rank)")
    print("\n=== PLAIN WORDS ===")
    if VT is not None and len(VT):
        for _, r in VT.iterrows():
            if r.verdict == "KEEP":
                print(f"  KEEP  {r.idea}: passes every test (BTC PF {r['BTC PF']}, ETH PF {r['ETH PF']}, placebo {r['placebo PF']}).")
            elif r.verdict == "WATCH":
                print(f"  WATCH {r.idea}: one miss -> {r.fails}.")
        nd = int((VT.verdict == "DROP").sum())
        if nd:
            print(f"  DROP  {nd} ideas failed two or more tests: " + ", ".join(VT[VT.verdict == "DROP"].idea.astype(str)))
    if notes:
        for line in (notes if isinstance(notes, (list, tuple)) else [notes]):
            print(f"  {line}")
    print("  Paper-trade any KEEP before it gets money; these are standalone 1%-risk backtests, not live-bot size mixes.")
    written = []
    if write_csv:
        out_dir.mkdir(parents=True, exist_ok=True)
        if BR:
            pd.DataFrame(BR).to_csv(out_dir / "oslib_btc.csv", index=False); written.append("oslib_btc.csv")
        if ER:
            pd.DataFrame(ER).to_csv(out_dir / "oslib_eth.csv", index=False); written.append("oslib_eth.csv")
        if VT is not None and len(VT):
            VT.to_csv(out_dir / "oslib_verdicts.csv", index=False); written.append("oslib_verdicts.csv")
        if written:
            print(f"\nWrote {', '.join(written)} to {out_dir}")
    return VT


# ---------------------------------------------------------------------------
# Synthetic self-test (no real market data)
# ---------------------------------------------------------------------------
def _handmade_ohlcv():
    """A short deterministic series: trend, a clean stop, a gapped stop, a target."""
    # 20 bars starting 2017-06-01 00:00 UTC, 1h, price around 1000
    t0 = ms("2017-06-01")
    rows = []
    px = 1000.0
    # 0-4: flat
    for i in range(5):
        rows.append((t0 + i * H1, px, px + 1, px - 1, px, 10))
    # 5: long signal bar (close up), 6: fill at 1000, 7: stop at 990 (no gap)
    # We'll drive signals separately; just make prices:
    # bar 6 open 1000 high 1005 low 989 close 995  -> hits stop 990
    # Then a new long: bar 8 signal, 9 fill 1000, 10 gaps open 980 through stop 990
    # Then a new long: bar 12 signal, 13 fill 1000, 14 hits target 1020
    def bar(i, o, h, l, c):
        return (t0 + i * H1, o, h, l, c, 10)
    # rebuild cleanly
    rec = []
    for i in range(20):
        rec.append(bar(i, 1000, 1001, 999, 1000))
    # bar 6: stop hit for a long filled at open 1000, stop 990
    rec[6] = bar(6, 1000, 1005, 989, 995)
    # bar 9 fill, bar 10 gap down
    rec[9] = bar(9, 1000, 1002, 998, 1000)
    rec[10] = bar(10, 980, 985, 975, 982)
    # bar 13 fill, bar 14 target
    rec[13] = bar(13, 1000, 1025, 999, 1022)
    rec[14] = bar(14, 1022, 1026, 1018, 1020)
    return pd.DataFrame(rec, columns=["time", "open", "high", "low", "close", "volume"])

def selftest():
    """Run every public function on synthetic data. Safe on the box. Returns a short summary dict."""
    print(f"oslib.selftest() v{__version__} — synthetic data only", flush=True)
    # --- indicators ---
    x = np.arange(50, dtype=float)
    s = sma(x, 5)
    assert np.isfinite(s[4]) and abs(s[4] - 2.0) < 1e-9
    e = ema(np.ones(20), 5)
    assert np.isfinite(e[-1]) and abs(e[-1] - 1) < 1e-9
    h = x + 2; l = x; c = x + 1
    a = atr(h, l, c, 5)
    assert np.nanmax(a) > 0
    ad, pdi, mdi = adx(h, l, c, 5)
    assert np.isfinite(ad[-1])
    up, mid, lo, w = bb_width(c, 10, 2)
    assert w.shape == c.shape and np.nanmax(w) >= 0
    du, dl, dm = donchian(h, l, 5)
    assert du[-1] >= dl[-1]
    # straight line => ER ~ 1
    ev = er(x, 10)
    assert ev[-1] > 0.99
    # monotone up => RSI high
    rv = rsi(x, 5)
    assert rv[-1] > 70
    ch = chop(h, l, c, 5)
    assert ch.shape == c.shape
    st = supertrend(h, l, c, 5, 3)
    assert set(np.unique(st)).issubset({-1, 0, 1})
    # --- expiry (calendar only) ---
    ex = expiry_days("2017-01-01", "2017-12-31")
    assert len(ex) == 12 and ex[0].dayofweek == 4 and ex[0].hour == 8
    # --- simulate: stop, gap, target, be, partial, trail, stop_order ---
    d = _handmade_ohlcv()
    n = len(d)
    sig = np.zeros(n, dtype=int)
    sig[5] = 1   # fill bar 6, stop 1% -> 990, bar 6 low 989 hits
    tr = simulate(d, sig, stop=0.01, target=2.0, time_stop=10, entry="next_open", check=True)
    assert len(tr) >= 1 and tr[0]["why"] == "SL"
    # non-gap 1% stop: raw price R = -1, net R = -1 - 2*COST/0.01
    expect = -1.0 - (2 * COST) / 0.01
    assert abs(tr[0]["R"] - expect) < 1e-6, (tr[0]["R"], expect)
    assert tr[0]["side"] == 1 and tr[0]["entry"] == 1000
    # gapped stop (open 980 through 990): worse than -1R minus costs, allowed
    sig2 = np.zeros(n, dtype=int); sig2[8] = 1
    tr2 = simulate(d, sig2, stop=0.01, target=2.0, time_stop=10, entry="next_open", check=True)
    assert len(tr2) >= 1 and tr2[0]["why"] == "SL"
    assert tr2[0]["R"] < expect - 0.05, tr2[0]["R"]
    # target hit
    sig3 = np.zeros(n, dtype=int); sig3[12] = 1
    # 2R of 1% = 20 points -> 1020, bar 14 high 1026
    tr3 = simulate(d, sig3, stop=0.01, target=2.0, time_stop=10, entry="next_open", check=True)
    assert len(tr3) >= 1 and tr3[0]["why"] == "TP"
    assert tr3[0]["R"] > 1.5
    # stop-order: signal bar 5 (high 1001), fill when later bar trades through 1001
    tr4 = simulate(d, sig, stop=0.02, target=2.0, time_stop=15, entry="stop_order", check=True)
    assert isinstance(tr4, list)
    # BE + trail + partial on a longer synthetic walk
    raw = synthetic_1h(n=4000, seed=3, start="2017-03-01")
    sigm = np.where(raw["close"].to_numpy() > ema(raw["close"], 20), 1, -1)
    # zero out warmup
    sigm[:50] = 0
    t_be = simulate(raw, sigm, stop=0.02, target=2.0, time_stop=48, be_at=1.0, entry="next_open", check=True)
    t_pa = simulate(raw, sigm, stop=0.02, target=3.0, time_stop=48, partial=(1.0, 0.5), entry="next_open", check=True)
    t_tr = simulate(raw, sigm, stop=0.02, target=3.0, time_stop=48, trail=(1.0, 0.5), entry="next_open", check=True)
    assert len(t_be) and len(t_pa) and len(t_tr)
    for tr_ in t_be + t_pa + t_tr:
        for k in TRADE_FIELDS:
            assert k in tr_, k
    # --- engines on synthetic 1h (planted structures from batch9) ---
    h1 = synthetic_1h(n=16000, seed=9, start="2017-01-02")
    fund = pd.DataFrame({"time": h1["time"].to_numpy()[::8],
                         "funding": np.random.default_rng(0).normal(0, 1e-5, (len(h1) + 7) // 8)})
    Eng = engines(h1, fund=fund)
    assert set(LIVE_ENGINES) <= set(Eng)
    for nm in LIVE_ENGINES:
        assert len(Eng[nm]) > 0, f"{nm} produced 0 trades on synthetic data"
        t0 = Eng[nm][0]
        for k in TRADE_FIELDS:
            assert k in t0, (nm, k)
    # --- evaluate / verdict / report ---
    # A dummy "idea": take K8 as the idea, shuffled signs as a rough placebo
    k8 = Eng["K8"]
    plc = [dict(t, side=-t["side"], R=-t["R"] if np.isfinite(t["R"]) else t["R"],
                net_R=-(t["R"] if np.isfinite(t["R"]) else t["net_R"])) for t in k8]
    row = evaluate("K8-syn", k8, plc, h1)
    assert row["idea"] == "K8-syn" and "PF" in row and "2017-20" in row and "corrK8" in row
    # a second idea so verdict has something to rank
    row2 = evaluate("V7-syn", Eng["V7"], plc[: max(1, len(Eng["V7"]))], h1)
    import tempfile
    tdir = Path(tempfile.mkdtemp(prefix="oslib-selftest-"))
    VT = report([row, row2], title="SELFTEST", out_dir=tdir, notes="synthetic only", write_csv=True)
    assert (tdir / "oslib_btc.csv").exists()
    assert VT is not None
    # --- robustness ---
    def _fn(sl=0.02, tgt=2.0):
        return simulate(raw, sigm, stop=sl, target=tgt, time_stop=24, entry="next_open", check=True)
    rb = robustness(_fn, dict(sl=0.02, tgt=2.0), scales=(0.8, 1.2))
    assert len(rb) >= 1 and "PF" in rb.columns
    # --- overlay ---
    ov = overlay(Eng, lambda nm, t: 0.5)
    assert "baseline" in ov and "overlay" in ov and ov["overlay"]["n"] >= 1
    ov2 = overlay(Eng, {nm: 1.0 for nm in LIVE_ENGINES})
    assert ov2["baseline"]["n"] == ov2["overlay"]["n"]
    # --- paired exit test ---
    a = simulate(raw, sigm, stop=0.02, target=2.0, time_stop=48, entry="next_open", check=True)
    b = simulate(raw, sigm, stop=0.02, target=3.0, time_stop=48, entry="next_open", check=True)
    pt = paired_exit_test(a, b, n_boot=200, seed=1, label_a="2R", label_b="3R")
    assert pt["n"] >= 1 and np.isfinite(pt["mean_diff"])
    # --- loaders refuse real data on the box ---
    if not _allow_real():
        for fn, args in (
            (lambda: load("btc", "1h"), "load"),
            (lambda: funding("btc", "binance"), "funding"),
            (lambda: hl_candles("btc"), "hl_candles"),
            (lambda: etf_flows(), "etf_flows"),
            (lambda: fng(), "fng"),
            (lambda: engines("btc"), "engines(str)"),
        ):
            try:
                fn()
                raise AssertionError(f"{args} should refuse real data outside Colab")
            except RuntimeError as e:
                assert "refuses" in str(e) or "Colab" in str(e)
    # --- parser fixtures (no network, no real history) ---
    ohlc = pd.DataFrame({"time": [1_483_228_800_000, 1_483_232_400_000],
                         "open": [1, 2], "high": [2, 3], "low": [0.5, 1], "close": [1.5, 2.5], "volume": [3, 4]})
    nn = _norm(ohlc)
    assert nn is not None and len(nn) == 2
    fund_fix = pd.DataFrame({"time": [1_483_228_800_000], "funding": [0.0001]})
    nv = _norm_venue(fund_fix, "x")
    assert nv is not None and "funding" in nv.columns
    etf_fix = _parse_etf([pd.DataFrame({"date": ["2024-01-15"], "flow_usd": [1.5e8]})])
    assert len(etf_fix) == 1 and abs(etf_fix.flow_usd.iloc[0] - 1.5e8) < 1
    fng_fix = _parse_fng(b'{"data":[{"timestamp":"1483228800","value":"40"}]}')
    assert fng_fix is not None and len(fng_fix) == 1
    r4 = resample_ohlcv(h1, H4)
    rd = resample_ohlcv(h1, D1)
    assert len(r4) < len(h1) and len(rd) < len(r4)
    d15 = synthetic_15m_from_1h(h1.iloc[:100])
    assert len(d15) == 400
    print(f"SELFTEST OK  engines={ {nm: len(Eng[nm]) for nm in LIVE_ENGINES} }  paired n={pt['n']}")
    return dict(ok=True, engines={nm: len(Eng[nm]) for nm in LIVE_ENGINES}, verdicts=len(VT), paired=pt)

__all__ = [
    "load", "funding", "hl_candles", "etf_flows", "expiry_days", "fng",
    "atr", "ema", "sma", "adx", "bb_width", "donchian", "chop", "er", "rsi", "supertrend",
    "engines", "simulate", "evaluate", "verdict", "robustness", "overlay",
    "paired_exit_test", "report", "selftest",
    "LIVE_ENGINES", "LIVE_RISK", "COST", "FEE", "SLIP", "RISK", "SITE", "HEADLINE_START", "H1", "D1", "H4", "M15",
    "in_colab", "standardize", "synthetic_1h", "synthetic_15m_from_1h", "resample_ohlcv",
    "__version__",
]

if __name__ == "__main__":
    if "--selftest" in sys.argv or "--smoke" in sys.argv or not in_colab():
        selftest()
        raise SystemExit(0)
    print("oslib: from oslib import *   (real data loaders run only in Colab)")
