
# ==== header.py ====
# ===== BATCH 10 — A1 trend-efficiency, A2 vol-cycle, A3 expiry-window, C1 turn-of-month, C2 ETF-flow tilt — paste this WHOLE cell into ONE Colab cell =====
# (or:  !wget -q -O batch10.py https://osom-boba.pages.dev/colab/batch10.py   then   %run batch10.py)
#
# COMMON: same loaders as batch 8 (BTC 1h 2013+, ETH 1h 2017+, BTC funding 8h 2020+ hosted at
#   osom-boba.pages.dev/colab/). Costs 0.12%/side (FEE 0.0007 + SLIP 0.0005). Engine trades are
#   generated once at 1% risk (notional <= 1x); the basket overlay then resizes them to approximate
#   live risks: K8 2%; COCO, B1G and S5 3%; C1, C2, V7, R0, MOM30, D34 1%. Market fills at the next
#   bar open of the engine's timeframe. Stop-first when a bar touches stop and target. One position
#   at a time per engine. BTC and ETH, 2017+ headline.
# ENGINES (reused, not re-invented): K8 / C1 / C2 from batch8.py (C1/C2 = live-engine ports);
#   V7, S5, B1G and the COCO coil-state filter from specialists_batch6.py; COCO itself is the live
#   OCO + one re-arm 3xATR trail from the x7/test10 port of batch-4 sys_oco; R0 is osom6's 600h
#   sweep-and-reclaim (10% stop, 0.5xATR dip wait; default _ok1 gates are off); MOM30 is the
#   mom30.mjs Python port (partial 50% at 2 ATR, rest 3 ATR); D34 is zai_batch7's weekly BB-squeeze
#   → 10-day stop-order break, 3R, 7-day time stop, filled on 1h.
# TESTS: (A1/A2) label every 1D bar; for each engine, mean next-30-day R per state AND trade R by
#   the state at entry (last completed 1D bar). Placebo = 1000 block-shuffles of state runs
#   (preserves frequencies and run lengths). Keep a mapping only if z >= 2 on the full 2017+ sample
#   AND the sign of (state mean − overall mean) holds in both 2017-20 and 2021-25. Then simulate
#   the pre-declared sizing overlay and a "passed-only" overlay on the 10-engine basket vs the
#   no-overlay baseline (return, maxDD, MAR) on BTC and ETH. A2 also event-studies engine R in the
#   30d after each COIL exit vs date-matched placebo exits. (A3) trade R by day-offset to last
#   Friday-of-month 08:00 UTC, offsets -7..+3, quarterly flagged separately, vs a shuffled-Friday
#   placebo; adopt skip or half-size for C1/C2 (and any other engine with the same drag) in the
#   tightest window that improves the basket on both assets when possible. (C1) long at the 1D
#   close of the last UTC day of each month (skip if the 3-settlement funding filter says skip),
#   exit after 3 daily closes, stop 2 ATR(1D); short only when the closing month returned >= +15%
#   (and funding >= 70th pct if available). Placebo = the same trade shifted +/-7 days. Also test
#   00:00 vs 22:00 UTC entry on 1h bars. Standalone 1% risk, KEEP/WATCH/DROP + corrK8. (C2) F5 =
#   5-day cumulative net US spot BTC ETF flow (Farside, hosted as colab/btc_etf_flows.csv.gz),
#   T+1 lag; long when F5 >= +$1B and close > EMA20(1D), enter next open, hold 10 days, stop 2 ATR;
#   short mirrored. Placebo: flows shuffled inside +/-30d windows; also sweep $0.5B..$2B. 2024+ only.
# VERDICT (pre-declared, same as batch 6/7/8): KEEP if (1) BTC 2017+ PF >= 1.3 with >= 30 trades,
#   (2) PF beats its placebo by >= 0.3, (3) 2017-20 and 2021+ both positive, (4) ETH PF >= 1.1,
#   (5) corr with K8 < 0.3. WATCH if exactly one fails, else DROP. KEEPs get a +-20% parameter
#   robustness check. Ranked table + PLAIN WORDS at the end.
# Smoke on the box only:  python3 batch10.py --smoke
# This script refuses to run a real-data backtest outside Colab (use --smoke).
import os, io, gzip, time, warnings, math, sys, calendar, json
from datetime import date, timedelta, datetime, timezone
from pathlib import Path
from urllib.error import HTTPError, URLError
from urllib.request import urlopen, Request
import numpy as np
import pandas as pd
warnings.filterwarnings("ignore")
pd.set_option("display.width", 230); pd.set_option("display.max_columns", 50); pd.set_option("display.max_rows", 400)

T0 = time.time()
H1 = 3_600_000; D1 = 24 * H1; H4 = 4 * H1; H12 = 12 * H1
FEE, SLIP = 0.0007, 0.0005
COST = FEE + SLIP
RISK = 0.01
MAX_NOTIONAL = 1.0
STOP_MIN, STOP_CAP = 0.015, 0.10
LAG_C2 = 8e-4
SITE = "https://osom-boba.pages.dev/colab/"
OUT_DIR = Path("/content") if Path("/content").exists() else Path(".")
BUCKETS = [("2013-16", "2013-01-01", "2017-01-01"), ("2017-20", "2017-01-01", "2021-01-01"),
           ("2021-23", "2021-01-01", "2024-01-01"), ("2024+", "2024-01-01", "2100-01-01"),
           ("2026", "2026-01-01", "2027-01-01")]
HEADLINE_START = "2017-01-01"
UA = "osom-batch10/1.0"
C1_DEFAULTS = dict(don=20, chop=34, chopLen=14, adx=18, adxLen=14, stLen=10, stF=3,
                   htf=12, atrLen=14, sl=1.5, tp1=2.0, tp2=3.5, tp1Frac=0.3)
STOP_RULE = None
MIN_ON = True
MIN_STOP = 0.015
MAX_HOLD = 30 * 24
N_SHUFF = 1000
LIVE_RISK = {"K8": 0.02, "COCO": 0.03, "B1G": 0.03, "S5": 0.03,
             "C1": 0.01, "C2": 0.01, "V7": 0.01, "R0": 0.01, "MOM30": 0.01, "D34": 0.01}
LIVE_ENGINES = list(LIVE_RISK)
TREND_ENG = {"K8", "MOM30"}
BREAK_ENG = {"C1", "C2", "COCO", "D34"}
A1_STATES = ["TREND", "RANGE", "CHOP", "EXPANSION", "OTHER"]
A2_STATES = ["COIL", "EXPANSION", "NORMAL"]
CHAND = None
FT = FC = None

PLACEBO = {
    "C1-TOM": "same month-turn window, stop and 3-day time exit, shifted +/-7 days",
    "C2-ETF": "same EMA20 + F5-threshold rule after a +/-30d window shuffle of the flow series",
}


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

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

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

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

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

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

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

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

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

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

def atr(h, l, c, n=14) -> np.ndarray:
    return _rma(true_range(h, l, c), n)
def set_asset(d):
    global df, N, O, Hh, L, C, V, T, BAR, BPD
    df = d.reset_index(drop=True); N = len(df); BAR = H1; BPD = 24
    O, Hh, L, C, V = (df[k].values.astype("float64") for k in ("open", "high", "low", "close", "volume"))
    T = df["time"].values.astype("int64")

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

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

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

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

STOP_RULE = None

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

# ==== b8_stats.py ====
def _tframe(trades):
    if not trades:
        return pd.DataFrame(columns=["side", "t_in", "t_out", "net_R", "weight", "src", "why"])
    return pd.DataFrame([{
        "side": t["side"], "t_in": int(t["t_in"]), "t_out": int(t["t_out"]),
        "net_R": float(t["net_R"]) if np.isfinite(t.get("net_R", np.nan)) else np.nan,
        "weight": float(t.get("weight", 1.0)), "src": t.get("src", ""), "why": t.get("why", ""),
        "entry_ts": pd.Timestamp(int(t["t_in"]), unit="ms", tz="UTC"),
        "exit_ts": pd.Timestamp(int(t["t_out"]), unit="ms", tz="UTC"),
    } for t in trades])

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

def tstats(tf):
    if tf is None or len(tf) == 0:
        return dict(tr=0, win=np.nan, pf=np.nan, ret=np.nan, dd=np.nan, avgR=np.nan, netR=np.nan, ddR=np.nan)
    wR = (tf["weight"] * tf["net_R"]).astype(float).to_numpy()
    wR = wR[np.isfinite(wR)]
    if len(wR) == 0:
        return dict(tr=len(tf), win=np.nan, pf=np.nan, ret=np.nan, dd=np.nan, avgR=np.nan, netR=np.nan, ddR=np.nan)
    g = wR[wR > 0].sum(); ls = -wR[wR < 0].sum()
    pf = (g / ls) if ls > 0 else (np.inf if g > 0 else np.nan)
    eq = np.cumprod(1.0 + RISK * wR)
    eq = np.r_[1.0, eq]
    peak = np.maximum.accumulate(eq)
    dd = 100 * ((eq / peak) - 1).min()
    cs = np.cumsum(wR); pk = np.maximum.accumulate(cs)
    ddR = float((cs - pk).min()) if len(cs) else np.nan
    return dict(tr=int(len(tf)), win=100 * float((wR > 0).mean()), pf=float(pf) if np.isfinite(pf) else pf,
                ret=100 * float(eq[-1] - 1), dd=float(dd), avgR=float(np.nanmean(wR)),
                netR=float(np.nansum(wR)), ddR=ddR)

def daily_from_trades(trades, start=HEADLINE_START):
    tf = _window(_tframe(trades), start)
    if tf is None or len(tf) == 0:
        return pd.Series(dtype=float)
    s = tf.assign(R=tf["weight"] * tf["net_R"]).set_index("exit_ts")["R"].groupby(lambda x: pd.Timestamp(x).floor("D")).sum()
    s.index = pd.to_datetime(s.index, utc=True)
    return (RISK * s).rename("ret")

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

def d34_trades():
    """zai_batch7 D34 on the current set_asset 1h frame: weekly BB squeeze → 10-day stop break, 3R, 7d."""
    D = resample(D1)
    ts = pd.to_datetime(D["time"].values, unit="ms", utc=True)
    df = D.copy(); df["ts"] = ts
    h, l, c = df.high.to_numpy(), df.low.to_numpy(), df.close.to_numpy()
    weekly = df.set_index("ts").resample("W-MON", label="left", closed="left").agg(
        open=("open", "first"), high=("high", "max"), low=("low", "min"), close=("close", "last")
    ).dropna()
    _, _, _, wbw = bb_width(weekly["close"].to_numpy(dtype=float), 20, 2)
    weekly = weekly.copy()
    weekly["bbw"] = wbw
    weekly["bbw_low"] = pd.Series(wbw, index=weekly.index).rolling(26, min_periods=26).min()
    weekly["squeeze"] = weekly["bbw"] <= weekly["bbw_low"]
    squeeze_state = pd.Series(False, index=df.index)
    if len(weekly):
        flag = weekly["squeeze"].fillna(False)
        for t, val in flag.items():
            if not val:
                continue
            close_t = pd.Timestamp(t)
            close_t = close_t.tz_localize("UTC") if close_t.tzinfo is None else close_t.tz_convert("UTC")
            trade_from = close_t + pd.Timedelta(days=7)
            trade_to = trade_from + pd.Timedelta(days=7)
            mask = (df["ts"] >= trade_from) & (df["ts"] < trade_to)
            squeeze_state.loc[mask] = True
    sq = squeeze_state.to_numpy()
    d10h, d10l = rolling_max(h, 10), rolling_min(l, 10)
    # map daily signal onto the last 1h bar of each day (batch7 lift_pack)
    last_i = D["last_i"].values.astype(int)
    long = np.zeros(N, bool); short = np.zeros(N, bool)
    ent_l = np.full(N, np.nan); ent_s = np.full(N, np.nan)
    stp_l = np.full(N, np.nan); stp_s = np.full(N, np.nan)
    for di, li in enumerate(last_i):
        if 0 <= li < N and sq[di]:
            long[li] = short[li] = True
            ent_l[li], ent_s[li] = d10h[di], d10l[di]
            stp_l[li], stp_s[li] = d10l[di], d10h[di]
    return _stop_oco_bt(ent_l, ent_s, stp_l, stp_s, long, short, target_R=3, time_bars=7 * 24, src="D34")

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

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

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

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

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

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

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

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

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

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

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

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

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

def run_lengths(states):
    """Return (starts, lengths, values) of contiguous runs."""
    s = np.asarray(states)
    n = len(s)
    if n == 0:
        return np.array([], int), np.array([], int), s
    chg = np.r_[True, s[1:] != s[:-1]]
    starts = np.flatnonzero(chg)
    lengths = np.diff(np.r_[starts, n])
    return starts, lengths, s[starts]

def day_in_state(states):
    starts, lengths, _ = run_lengths(states)
    out = np.zeros(len(states), dtype=int)
    for st, ln in zip(starts, lengths):
        out[st:st + ln] = np.arange(1, ln + 1)
    return out

def block_shuffle(states, rng):
    starts, lengths, vals = run_lengths(states)
    if len(vals) <= 1:
        return np.array(states, copy=True)
    order = rng.permutation(len(vals))
    return np.repeat(vals[order], lengths[order])

def completed_day_idx(t_ms, day_t):
    """Index of the last completed 1D bar at time t_ms (no lookahead)."""
    key = int(t_ms) - 1
    j = int(np.searchsorted(day_t, key, side="right") - 1)
    return j

def attach_state(trades, day_t, states, days_in=None):
    st = np.asarray(states)
    for t in trades:
        j = completed_day_idx(t["t_in"], day_t)
        t["state_i"] = j
        t["state"] = st[j] if 0 <= j < len(st) else "OTHER"
        t["day_in"] = int(days_in[j]) if days_in is not None and 0 <= j < len(days_in) else 0
    return trades

def daily_R_series(trades, day_t, start=HEADLINE_START):
    """R credited on the exit day's completed-bar index."""
    r = np.zeros(len(day_t))
    t0 = ms(start)
    for t in trades:
        if t["t_out"] < t0:
            continue
        j = completed_day_idx(t["t_out"], day_t)
        if 0 <= j < len(r) and np.isfinite(t.get("net_R", np.nan)):
            r[j] += float(t["net_R"]) * float(t.get("weight", 1.0))
    return r

def fwd_sum(x, n=30):
    """fwd[i] = sum(x[i+1:i+1+n]) (next n days, excluding today)."""
    c = np.r_[0.0, np.cumsum(np.asarray(x, dtype=float))]
    out = np.full(len(x), np.nan)
    end = np.arange(len(x)) + n + 1
    ok = end <= len(x)
    out[ok] = c[end[ok]] - c[np.arange(len(x))[ok] + 1]
    return out

def half_mask(day_t, a="2017-01-01", b="2021-01-01", c="2026-01-01"):
    early = (day_t >= ms(a)) & (day_t < ms(b))
    late = (day_t >= ms(b)) & (day_t < ms(c))
    head = (day_t >= ms(HEADLINE_START))
    return head, early, late

def state_means(fwd, states, labels, mask):
    out = {}
    f, s = fwd[mask], np.asarray(states)[mask]
    ok = np.isfinite(f)
    f, s = f[ok], s[ok]
    overall = float(f.mean()) if len(f) else np.nan
    out["__all__"] = dict(mean=overall, n=int(len(f)))
    for lab in labels:
        m = s == lab
        out[lab] = dict(mean=float(f[m].mean()) if m.any() else np.nan, n=int(m.sum()))
    return out

def shuffle_z(fwd, states, labels, mask, n=N_SHUFF, seed=10):
    """z of (state mean - overall) vs block-shuffle null, frequencies preserved."""
    rng = np.random.default_rng(seed)
    base = state_means(fwd, states, labels, mask)
    s0 = np.asarray(states)
    # only shuffle inside the masked region, keep runs of the masked slice
    idx = np.flatnonzero(mask)
    if len(idx) < 50:
        return {lab: dict(**base.get(lab, {}), z=np.nan, null_mean=np.nan, null_sd=np.nan) for lab in labels}, base
    sub = s0[idx]
    null = {lab: np.empty(n) for lab in labels}
    for k in range(n):
        sh = block_shuffle(sub, rng)
        # overall is invariant under shuffle (same fwd, same mask)
        for lab in labels:
            m = sh == lab
            null[lab][k] = float(fwd[idx][m].mean()) if m.any() else np.nan
    out = {}
    overall = base["__all__"]["mean"]
    for lab in labels:
        obs = base[lab]["mean"]
        nv = null[lab]
        nv = nv[np.isfinite(nv)]
        mu, sd = (float(nv.mean()), float(nv.std(ddof=1))) if len(nv) > 5 else (np.nan, np.nan)
        z = (obs - mu) / sd if (np.isfinite(obs) and np.isfinite(sd) and sd > 0) else np.nan
        # also z vs overall: sign of edge
        out[lab] = dict(mean=obs, n=base[lab]["n"], z=z, null_mean=mu, null_sd=sd,
                        vs_all=(obs - overall) if np.isfinite(obs) and np.isfinite(overall) else np.nan)
    return out, base

def mapping_pass(zrow, early_vs, late_vs, zmin=2.0):
    """Pass if |z|>=2 and vs-all sign agrees in both halves (and is not nan)."""
    z = zrow.get("z", np.nan)
    vs = zrow.get("vs_all", np.nan)
    if not (np.isfinite(z) and abs(z) >= zmin and np.isfinite(vs) and vs != 0):
        return False
    if not (np.isfinite(early_vs) and np.isfinite(late_vs)):
        return False
    return (np.sign(vs) == np.sign(early_vs) == np.sign(late_vs)) and (early_vs != 0) and (late_vs != 0)

def a1_mult(engine, state, day_in):
    m = 1.0
    if state == "TREND" and engine in TREND_ENG:
        m = 1.25
    elif state == "CHOP" and engine in BREAK_ENG:
        m = 0.5
    elif state == "RANGE" and engine in TREND_ENG:
        m = 0.75
    elif state == "EXPANSION" and engine in BREAK_ENG and day_in > 3:
        m = 0.5
    return m

def a2_mult(engine, state, day_in):
    m = 1.0
    if state == "COIL" and engine in BREAK_ENG:
        m = 1.5
    elif state == "EXPANSION":
        if 1 <= day_in <= 5:
            if engine in TREND_ENG:
                m = 1.25
            elif engine in BREAK_ENG:
                m = 0.75
        elif day_in >= 6 and engine in BREAK_ENG:
            m = 0.5
    return m

def trade_pnl(t, risk_pct):
    """Account fraction PnL at the given risk (notional capped at 1x)."""
    r, nr = t.get("risk", np.nan), 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_curve(engine_trades, day_t, sizes, start=HEADLINE_START):
    """Compound equity, PnL credited on exit day. sizes[name](trade)->risk fraction."""
    t0 = ms(start)
    ev = []
    for nm, tr in engine_trades.items():
        fn = sizes[nm] if isinstance(sizes, dict) and callable(sizes.get(nm)) else None
        for t in tr:
            if t["t_out"] < t0:
                continue
            rp = fn(t) if fn else (LIVE_RISK.get(nm, RISK) if not callable(sizes) else sizes(nm, t))
            ev.append((int(t["t_out"]), trade_pnl(t, rp)))
    ev.sort(key=lambda x: x[0])
    eq = 1.0; peak = 1.0; mdd = 0.0
    by_day = {}
    for t_out, pnl in ev:
        by_day[t_out] = by_day.get(t_out, 0.0) + pnl
    rec = []
    for t_out in sorted(by_day):
        eq *= (1.0 + by_day[t_out])
        peak = max(peak, eq)
        mdd = min(mdd, eq / peak - 1.0)
        rec.append((t_out, eq))
    ret = 100 * (eq - 1.0)
    dd = 100 * mdd
    mar = (ret / abs(dd)) if dd < 0 else np.nan
    return dict(ret=ret, maxDD=dd, MAR=mar, eq=eq, n=len(ev), curve=rec)

def sizes_baseline(_nm, t):
    return LIVE_RISK.get(_nm, RISK) if False else LIVE_RISK.get(t.get("src", _nm), RISK)

def make_sizes(kind, passed=None, a3=None):
    """kind: 'base' | 'A1' | 'A2' | 'A1pass' | 'A2pass' | 'A3' | 'stack'."""
    passed = passed or {}
    def fn(nm, t):
        base = LIVE_RISK.get(nm, RISK)
        m = 1.0
        st, di = t.get("state", "OTHER"), t.get("day_in", 0)
        if kind in ("A1", "A1pass", "stack"):
            mm = a1_mult(nm, st, di)
            if kind == "A1pass":
                key = (nm, "A1", st)
                if not passed.get(key, False) and not passed.get(("A1", st), False):
                    mm = 1.0
            m *= mm
        if kind in ("A2", "A2pass", "stack"):
            # A2 state lives in t['state'] only when we attached A2; for stack we use t['a2']
            st2, di2 = t.get("a2", t.get("state")), t.get("a2_day_in", t.get("day_in", 0))
            mm = a2_mult(nm, st2, di2)
            if kind == "A2pass":
                key = (nm, "A2", st2)
                if not passed.get(key, False) and not passed.get(("A2", st2), False):
                    mm = 1.0
            m *= mm
        if kind in ("A3", "stack") and a3 is not None:
            m *= a3(nm, t)
        return base * m
    return fn

def eval_protocol(name, states, labels, engine_trades, day_t, seed=11):
    """Per-engine next-30d R and trade-R-at-entry vs block-shuffle placebo."""
    head, early, late = half_mask(day_t)
    rows = []
    passed = {}
    for eng, tr in engine_trades.items():
        dR = daily_R_series(tr, day_t)
        fwd = fwd_sum(dR, 30)
        zfull, _ = shuffle_z(fwd, states, labels, head, seed=seed + abs(hash(eng)) % 1000)
        # half-sample signs (no extra shuffles; just means)
        be = state_means(fwd, states, labels, early)
        bl = state_means(fwd, states, labels, late)
        # trade R by state at entry
        trR = {lab: [] for lab in labels}
        for t in tr:
            if t["t_in"] < ms(HEADLINE_START):
                continue
            lab = t.get("state")
            if lab in trR and np.isfinite(t.get("net_R", np.nan)):
                trR[lab].append(float(t["net_R"]))
        overall = zfull.get("TREND", zfull.get(labels[0], {})).get("mean", np.nan)  # unused
        for lab in labels:
            zrow = zfull[lab]
            evs = (be[lab]["mean"] - be["__all__"]["mean"]) if be[lab]["n"] and be["__all__"]["n"] else np.nan
            lvs = (bl[lab]["mean"] - bl["__all__"]["mean"]) if bl[lab]["n"] and bl["__all__"]["n"] else np.nan
            ok = mapping_pass(zrow, evs, lvs)
            passed[(eng, name, lab)] = ok
            arr = np.array(trR[lab], float) if trR[lab] else np.array([])
            rows.append(dict(
                engine=eng, card=name, state=lab, n_days=zrow["n"],
                fwd30=zrow["mean"], z=zrow["z"], vs_all=zrow["vs_all"],
                early=evs, late=lvs, pass_="yes" if ok else "no",
                tr_n=int(len(arr)), tr_avgR=float(arr.mean()) if len(arr) else np.nan,
            ))
    return rows, passed

def coil_exit_study(states, engine_trades, day_t, n_plac=200, seed=99):
    st = np.asarray(states)
    exits = np.zeros(len(st), bool)
    exits[1:] = (st[1:] != "COIL") & (st[:-1] == "COIL")
    idx = np.flatnonzero(exits)
    head = (day_t >= ms(HEADLINE_START))
    idx = idx[head[idx] & (idx + 30 < len(st))]
    rows = []
    rng = np.random.default_rng(seed)
    cand = np.flatnonzero(head & (np.arange(len(st)) + 30 < len(st)))
    for eng, tr in engine_trades.items():
        dR = daily_R_series(tr, day_t)
        fwd = fwd_sum(dR, 30)
        obs = float(np.nanmean(fwd[idx])) if len(idx) else np.nan
        null = np.empty(n_plac)
        for k in range(n_plac):
            if len(cand) < max(10, len(idx)):
                null[k] = np.nan; continue
            pick = rng.choice(cand, size=len(idx), replace=False)
            null[k] = float(np.nanmean(fwd[pick]))
        nv = null[np.isfinite(null)]
        mu, sd = (float(nv.mean()), float(nv.std(ddof=1))) if len(nv) > 5 else (np.nan, np.nan)
        z = (obs - mu) / sd if (np.isfinite(obs) and np.isfinite(sd) and sd > 0) else np.nan
        rows.append(dict(engine=eng, n_exits=int(len(idx)), fwd30=obs, placebo=mu, z=z))
    return rows, int(len(idx))

# ---------------------------------------------------------------------------
# A3 options-expiry offsets
# ---------------------------------------------------------------------------
def expiry_offset(t_ms, expiries):
    t = pd.Timestamp(int(t_ms), unit="ms", tz="UTC")
    best = None; best_abs = 10**9
    for e in expiries:
        off = (t - e) / pd.Timedelta(days=1)
        # use calendar-day offset rounded to nearest day from 08:00
        od = int(round(off))
        if abs(od) < best_abs or (abs(od) == best_abs and abs(off) < abs((t - expiries[0]).days)):
            best, best_abs = (od, e), abs(od)
    if best is None:
        return None, False
    od, e = best
    q = e.month in (3, 6, 9, 12)
    return od, q

def a3_offset_table(engine_trades, expiries, n_plac=300, seed=17):
    rows = []
    rng = np.random.default_rng(seed)
    # build real-expiry assignment
    def collect(exps):
        buckets = {}
        for eng, tr in engine_trades.items():
            for t in tr:
                if t["t_in"] < ms(HEADLINE_START) or not np.isfinite(t.get("net_R", np.nan)):
                    continue
                od, q = expiry_offset(t["t_in"], exps)
                if od is None or od < -7 or od > 3:
                    key = (eng, "out", False)
                else:
                    key = (eng, od, q)
                buckets.setdefault(key, []).append(float(t["net_R"]))
        return buckets
    real = collect(expiries)
    # placebo: for each month pick a random Friday (not necessarily last)
    def random_fridays():
        out = []
        for e in expiries:
            # all fridays in that month
            y, m = e.year, e.month
            last = calendar.monthrange(y, m)[1]
            fr = [date(y, m, d) for d in range(1, last + 1) if date(y, m, d).weekday() == 4]
            d = fr[rng.integers(0, len(fr))] if fr else e.date()
            out.append(pd.Timestamp(year=d.year, month=d.month, day=d.day, hour=8, tz="UTC"))
        return out
    # pre-aggregate observed means
    keys = set()
    for eng in engine_trades:
        for od in list(range(-7, 4)) + ["out"]:
            for q in (False, True):
                keys.add((eng, od, q))
    null_mean = {k: [] for k in keys}
    for _ in range(n_plac):
        b = collect(random_fridays())
        for k in keys:
            arr = b.get(k)
            if arr:
                null_mean[k].append(float(np.mean(arr)))
    for eng in LIVE_ENGINES:
        for od in list(range(-7, 4)) + ["out"]:
            for q, qlab in ((False, "mth"), (True, "qtr")):
                k = (eng, od, q)
                arr = np.array(real.get(k, []), float)
                nv = np.array(null_mean[k], float)
                obs = float(arr.mean()) if len(arr) else np.nan
                mu, sd = (float(nv.mean()), float(nv.std(ddof=1))) if len(nv) > 5 else (np.nan, np.nan)
                z = (obs - mu) / sd if (np.isfinite(obs) and np.isfinite(sd) and sd > 0) else np.nan
                rows.append(dict(engine=eng, offset=od, cal=qlab, n=int(len(arr)),
                                 avgR=obs, z=z, placebo=mu))
    return rows

def choose_a3_window(rows, engines=("C1", "C2")):
    """Tightest consecutive offset window inside -7..+3 where those engines show z<=-1.5 on monthly (or overall) sample.
    Fallback to the pre-declared -2..+1 if nothing is significant."""
    # combine mth+qtr by pooling isn't stored; use cal=='mth' (more n) and also a combined view: prefer rows with n>=8
    best = None
    for lo in range(-7, 4):
        for hi in range(lo, 4):
            zs = []
            ns = 0
            for eng in engines:
                sub = [r for r in rows if r["engine"] == eng and r["offset"] != "out"
                       and lo <= r["offset"] <= hi and r["cal"] == "mth" and r["n"] >= 5]
                if not sub:
                    continue
                # mean z weighted by n
                z = np.nansum([r["z"] * r["n"] for r in sub]) / max(1, sum(r["n"] for r in sub))
                zs.append(z); ns += sum(r["n"] for r in sub)
            if len(zs) < 1 or ns < 10:
                continue
            mz = float(np.mean(zs))
            # want negative drag, prefer tighter windows when z similar
            score = (-mz, -(hi - lo), ns)
            if mz <= -1.5 and (best is None or score > best[0]):
                best = (score, lo, hi, mz, ns)
    if best is None:
        return -2, 1, "default (no z<=-1.5 window)"
    return best[1], best[2], f"z={best[3]:.2f} n={best[4]}"

def a3_mult_fn(lo, hi, engines, mode="half"):
    fac = 0.0 if mode == "skip" else 0.5
    engs = set(engines)
    def fn(nm, t):
        if nm not in engs:
            return 1.0
        od = t.get("exp_off")
        if od is None or od == "out":
            return 1.0
        if lo <= od <= hi:
            return fac
        return 1.0
    return fn

# ---------------------------------------------------------------------------
# C1 turn-of-month and C2 ETF tilt (standalone)
# ---------------------------------------------------------------------------
def last_days_of_month(day_t):
    dts = pd.to_datetime(day_t, unit="ms", utc=True)
    # last bar whose calendar month differs from the next bar's month
    is_last = np.r_[dts[:-1].month != dts[1:].month, True]
    return is_last

def simulate_tom(d_1h, day, entry_hour=0, fund3=None, use_fund=True, shift_days=0, stop_mult=2.0, hold_days=3):
    """Enter at close of the (shifted) month-end 1h bar at entry_hour UTC; exit after hold_days daily closes; stop stop_mult ATR."""
    set_asset(d_1h)  # 1h globals
    h, l, c, tms = day.high.values, day.low.values, day.close.values, day["time"].values.astype("int64")
    a = atr(h, l, c, 14)
    last = last_days_of_month(tms)
    # month return ending on that last day
    dts = pd.to_datetime(tms, unit="ms", utc=True)
    month_ret = np.full(len(day), np.nan)
    # first close of month vs last close
    first_c = {}
    for i, ts in enumerate(dts):
        key = (ts.year, ts.month)
        if key not in first_c:
            first_c[key] = c[i]
        if last[i] and first_c[key] > 0:
            month_ret[i] = c[i] / first_c[key] - 1.0
    # 1h index by time
    pos = {int(T[i]): i for i in range(N)}
    trades = []
    idxs = np.flatnonzero(last)
    for i0 in idxs:
        j = i0 + int(shift_days)
        if j < 0 or j >= len(day) - 1:
            continue
        # entry timestamp: that day's date + hour
        day0 = pd.Timestamp(int(tms[j]), unit="ms", tz="UTC")
        # daily bar time is 00:00 of that UTC day; close of the day is 00:00 next day, but
        # "close of last day" = last 1h close on that date. For hour H, use that H:00 bar's close.
        et = int(day0.value // 1_000_000) + int(entry_hour) * H1
        # if hour==0 we use the 00:00 bar of that day (open of the UTC day) — also offer the true daily close:
        # interpret 00:00 as the daily close = last 1h bar of that day = 23:00 close, i.e. next day's 00:00 open? 
        # Spec: "test entry at 00:00 vs 22:00 UTC". For 00:00 we enter at the 00:00 1h close of the last day
        # (the 00:00-01:00 bar's close is 01:00, messy). We take the close of the 1h bar that OPENS at hour H.
        if et not in pos:
            # snap to nearest earlier 1h bar
            k = int(np.searchsorted(T, et, side="right") - 1)
            if k < 0: continue
            ei = k
        else:
            ei = pos[et]
        if ei < 0 or ei >= N - 2:
            continue
        entry = float(C[ei])  # close of that 1h bar
        # stop from daily ATR at the last completed day j
        if not np.isfinite(a[j]) or a[j] <= 0 or entry <= 0:
            continue
        # funding filter at entry
        pct = fund_at(fund3, T[ei], "pct") if use_fund else np.nan
        # LONG always (subject to funding skip); SHORT only if month >= +15% and funding >= 70th
        cands = []
        skip_long = use_fund and np.isfinite(pct) and pct >= 0.90
        if not skip_long:
            cands.append(1)
        if np.isfinite(month_ret[j]) and month_ret[j] >= 0.15:
            ok_s = (not use_fund) or (np.isfinite(pct) and pct >= 0.70)
            if ok_s:
                cands.append(-1)
        # exit: after `hold_days` daily closes = daily bar j + hold_days (that bar's last 1h)
        if j + hold_days >= len(day):
            continue
        x_day_t = int(tms[j + hold_days])  # start of exit day
        # exit at that day's close = last 1h bar with time < x_day_t + D1, i.e. time == x_day_t + 23h
        x_close_t = x_day_t + 23 * H1
        xi_time = int(np.searchsorted(T, x_close_t, side="right") - 1)
        if xi_time <= ei:
            continue
        for side in cands:
            stop = entry - side * stop_mult * a[j]
            risk = abs(entry - stop) / entry
            if risk <= 0: continue
            # walk 1h, stop-first, else time exit at xi_time close
            why, xp, xo = "time", float(C[xi_time]), xi_time
            for p in range(ei + 1, xi_time + 1):
                if side > 0 and L[p] <= stop:
                    why, xp, xo = "SL", min(O[p], stop), p; break
                if side < 0 and Hh[p] >= stop:
                    why, xp, xo = "SL", max(O[p], stop), p; break
            tr = _as_trade("C1-TOM", side, T[ei], T[xo], entry, xp, stop, why=why)
            if tr:
                trades.append(tr)
    return trades

def simulate_etf(d_1h, day, flows, thresh=1e9, hold_days=10, stop_mult=2.0, flow_shift=None, min_date="2024-01-11"):
    """T+1 lag: at daily bar i (close of day i) we only know flows through day i-1; enter next 1h/daily open."""
    if flows is None or not len(flows):
        return []
    c = day.close.values; tms = day["time"].values.astype("int64")
    a = atr(day.high.values, day.low.values, c, 14)
    ema20 = pd.Series(c).ewm(span=20, adjust=False, min_periods=20).mean().to_numpy()
    f = flows.copy()
    f["date"] = pd.to_datetime(f["date"], utc=True).dt.floor("D")
    s = f.set_index("date")["flow_usd"].sort_index()
    # align to daily bars; missing days (weekends) = 0
    dts = pd.to_datetime(tms, unit="ms", utc=True).floor("D")
    flow = s.reindex(dts).fillna(0.0).to_numpy()
    if flow_shift is not None:
        flow = flow_shift(flow, dts)
    # F5 = 5-day cumulative (calendar days in the series, including zeros for weekends)
    F5 = pd.Series(flow).rolling(5, min_periods=5).sum().to_numpy()
    pos = {int(T[i]): i for i in range(N)}
    trades = []; in_pos_until = -1
    for i in range(len(day) - 1):
        if tms[i] < ms(min_date):
            continue
        if i <= in_pos_until:
            continue
        # T+1: use F5[i-1] (flows through prior day) with today's close/EMA
        if i < 1 or not np.isfinite(F5[i - 1]) or not np.isfinite(ema20[i]) or not np.isfinite(a[i]):
            continue
        f5 = F5[i - 1]
        side = 0
        if f5 >= thresh and c[i] > ema20[i]:
            side = 1
        elif f5 <= -thresh and c[i] < ema20[i]:
            side = -1
        if not side:
            continue
        # enter next open = first 1h bar of the next daily bar (tms[i+1])
        if i + 1 >= len(day):
            continue
        et = int(tms[i + 1])
        ei = pos.get(et)
        if ei is None:
            ei = int(np.searchsorted(T, et, side="left"))
        if ei >= N - 1:
            continue
        entry = float(O[ei])
        stop = entry - side * stop_mult * a[i]
        risk = abs(entry - stop) / entry
        if entry <= 0 or risk <= 0:
            continue
        # exit after hold_days daily closes from the signal day i → day i+hold_days close
        jx = min(len(day) - 1, i + hold_days)
        x_close_t = int(tms[jx]) + 23 * H1
        xi = int(np.searchsorted(T, x_close_t, side="right") - 1)
        if xi <= ei:
            continue
        why, xp, xo = "time", float(C[xi]), xi
        for p in range(ei, xi + 1):
            if side > 0 and L[p] <= stop:
                why, xp, xo = "SL", min(O[p], stop), p; break
            if side < 0 and Hh[p] >= stop:
                why, xp, xo = "SL", max(O[p], stop), p; break
        tr = _as_trade("C2-ETF", side, T[ei], T[xo], entry, xp, stop, why=why)
        if tr:
            trades.append(tr)
            in_pos_until = jx
    return trades

def window_shuffle_flows(flow, dts, rng, window=30):
    """Shuffle values inside successive `window`-day blocks, with a random block offset."""
    x = np.array(flow, copy=True)
    n = len(x)
    off = int(rng.integers(0, max(1, window)))
    i = off
    # leading stub
    if off > 0:
        sl = x[:off]; rng.shuffle(sl); x[:off] = sl
    while i < n:
        j = min(n, i + window)
        sl = x[i:j]; rng.shuffle(sl); x[i:j] = sl
        i = j
    return x

# ==== tail3.py ====
def _seed(name):
    return 17 + sum(ord(ch) for ch in name) * 13

def sizes_fn(kind, passed=None, a3=None):
    passed = passed or {}
    def fn(nm, t):
        base = LIVE_RISK.get(nm, RISK)
        m = 1.0
        if kind in ("A1", "A1pass", "stack"):
            st, di = t.get("a1", t.get("state")), t.get("a1_day_in", t.get("day_in", 0))
            mm = a1_mult(nm, st, di)
            if kind == "A1pass" and not passed.get((nm, "A1", st), False):
                mm = 1.0
            m *= mm
        if kind in ("A2", "A2pass", "stack"):
            st, di = t.get("a2", t.get("state")), t.get("a2_day_in", t.get("day_in", 0))
            mm = a2_mult(nm, st, di)
            if kind == "A2pass" and not passed.get((nm, "A2", st), False):
                mm = 1.0
            m *= mm
        if kind in ("A3", "stack") and a3 is not None:
            m *= a3(nm, t)
        return base * m
    return fn

def fmt_z(x):
    return "-" if x is None or (isinstance(x, float) and not np.isfinite(x)) else f"{x:.2f}"

def print_proto(rows, title):
    print(f"\n=== {title} ===")
    if not rows:
        print("(none)"); return
    df = pd.DataFrame(rows)
    df["fwd30"] = df["fwd30"].map(lambda x: fmt_z(x))
    df["z"] = df["z"].map(lambda x: fmt_z(x))
    df["vs_all"] = df["vs_all"].map(lambda x: fmt_z(x))
    df["early"] = df["early"].map(lambda x: fmt_z(x))
    df["late"] = df["late"].map(lambda x: fmt_z(x))
    df["tr_avgR"] = df["tr_avgR"].map(lambda x: fmt_z(x))
    cols = ["engine", "state", "n_days", "fwd30", "z", "vs_all", "early", "late", "pass_", "tr_n", "tr_avgR"]
    print(df[cols].to_string(index=False))

def print_basket(rows, title):
    print(f"\n=== {title} ===")
    df = pd.DataFrame(rows)
    for c in ("ret", "maxDD", "MAR"):
        if c in df.columns:
            df[c] = df[c].map(lambda x: fmt(x, 2))
    print(df.to_string(index=False))

def verdict_of(row):
    fails = []
    n, pf, ppf = row.get("_n", 0), row.get("_pf", np.nan), row.get("_ppf", np.nan)
    b1, b2, ck, eth_pf = row.get("_b1", np.nan), row.get("_b2", np.nan), row.get("_ck", np.nan), row.get("_eth_pf", np.nan)
    if not (n >= 30 and np.isfinite(pf) and pf >= 1.3):
        fails.append("PF/n")
    if not (np.isfinite(pf) and np.isfinite(ppf) and pf >= ppf + 0.3):
        fails.append("placebo")
    if not (np.isfinite(b1) and np.isfinite(b2) and b1 > 0 and b2 > 0):
        fails.append("halves")
    if row.get("_eth_missing"):
        fails.append("ETH")
    elif not (np.isfinite(eth_pf) and eth_pf >= 1.1):
        fails.append("ETH")
    if not (np.isfinite(ck) and abs(ck) < 0.3):
        fails.append("corrK8")
    if len(fails) == 0:
        return "KEEP", fails
    if len(fails) == 1:
        return "WATCH", fails
    return "DROP", fails

def tag_asset_trades(tr, a1, a1d, a2, a2d, day_t, expiries):
    attach_state(tr, day_t, a1, a1d)
    for t in tr:
        t["a1"] = t.get("state"); t["a1_day_in"] = t.get("day_in", 0)
        j = t.get("state_i", -1)
        t["a2"] = a2[j] if 0 <= j < len(a2) else "NORMAL"
        t["a2_day_in"] = int(a2d[j]) if 0 <= j < len(a2d) else 0
        od, q = expiry_offset(t["t_in"], expiries)
        t["exp_off"] = od if od is not None else "out"
        t["exp_q"] = bool(q)
    return tr

def run_asset(label, d_1h, fund, flows, expiries, k8d, have_fund, have_etf):
    t_a = time.time()
    print(f"  {label}: engines ...", flush=True)
    eng, D = run_engines(d_1h, fund)
    day_t, _ = daily_index(D)
    a1, a1meta = label_A1(D)
    a2, a2meta = label_A2(D)
    a1d, a2d = day_in_state(a1), day_in_state(a2)
    for nm, tr in eng.items():
        tag_asset_trades(tr, a1, a1d, a2, a2d, day_t, expiries)
    print(f"  {label}: { {k: len(v) for k,v in eng.items()} }  ({time.time()-t_a:.0f}s)", flush=True)

    r1, p1 = eval_protocol("A1", a1, A1_STATES, eng, day_t, seed=_seed(label + "A1"))
    r2, p2 = eval_protocol("A2", a2, A2_STATES, eng, day_t, seed=_seed(label + "A2"))
    passed = {**p1, **p2}
    ev_rows, n_ex = coil_exit_study(a2, eng, day_t, n_plac=200, seed=_seed(label + "coil"))

    # A3 offsets
    a3_rows = a3_offset_table(eng, expiries, n_plac=200, seed=_seed(label + "A3"))
    lo, hi, why = choose_a3_window(a3_rows, ("C1", "C2"))
    # any other engine with mean z <= -1.5 in the same window (monthly)?
    extra = []
    for e in LIVE_ENGINES:
        sub = [r for r in a3_rows if r["engine"] == e and r["cal"] == "mth"
               and r["offset"] != "out" and lo <= r["offset"] <= hi and r["n"] >= 5]
        if not sub:
            continue
        z = np.nansum([r["z"] * r["n"] for r in sub]) / max(1, sum(r["n"] for r in sub))
        if e not in ("C1", "C2") and z <= -1.5:
            extra.append(e)
    a3_engs = ["C1", "C2"] + extra
    fn_half = a3_mult_fn(lo, hi, a3_engs, "half")
    fn_skip = a3_mult_fn(lo, hi, a3_engs, "skip")

    def pack_sizes(kind, a3=None):
        return lambda nm, t: sizes_fn(kind, passed, a3)(nm, t)

    base = basket_curve(eng, day_t, pack_sizes("base"))
    rows_b = []
    def addb(name, st):
        rows_b.append(dict(overlay=name, ret=st["ret"], maxDD=st["maxDD"], MAR=st["MAR"],
                           n=st["n"], d_ret=st["ret"] - base["ret"], d_MAR=st["MAR"] - base["MAR"] if np.isfinite(st["MAR"]) and np.isfinite(base["MAR"]) else np.nan))
    addb("baseline", base)
    addb("A1 proposed", basket_curve(eng, day_t, pack_sizes("A1")))
    addb("A1 passed-only", basket_curve(eng, day_t, pack_sizes("A1pass")))
    addb("A2 proposed", basket_curve(eng, day_t, pack_sizes("A2")))
    addb("A2 passed-only", basket_curve(eng, day_t, pack_sizes("A2pass")))
    addb(f"A3 half {lo}..{hi} ({'+'.join(a3_engs)})", basket_curve(eng, day_t, pack_sizes("A3", fn_half)))
    addb(f"A3 skip {lo}..{hi}", basket_curve(eng, day_t, pack_sizes("A3", fn_skip)))
    addb("stack A1+A2+A3half", basket_curve(eng, day_t, pack_sizes("stack", fn_half)))

    # C1 ToM
    fund3 = funding_3s(fund)
    use_f = bool(have_fund and fund3 is not None)
    tom00 = simulate_tom(d_1h, D, 0, fund3, use_f, 0)
    tom22 = simulate_tom(d_1h, D, 22, fund3, use_f, 0)
    tom_m7 = simulate_tom(d_1h, D, 0, fund3, use_f, -7)
    tom_p7 = simulate_tom(d_1h, D, 0, fund3, use_f, +7)
    tom_plc = tom_m7 + tom_p7

    # C2 ETF
    etf_main = etf_plc = []
    etf_sweep = []
    if have_etf and flows is not None:
        etf_main = simulate_etf(d_1h, D, flows, 1e9)
        rng = np.random.default_rng(_seed(label + "etf"))
        plc = []
        for s in range(20):
            def sh(flow, dts, _rng=np.random.default_rng(_seed(label + "etf") + s + 1)):
                return window_shuffle_flows(flow, dts, _rng, 30)
            plc.extend(simulate_etf(d_1h, D, flows, 1e9, flow_shift=sh))
        etf_plc = plc
        for th in (0.5e9, 1.0e9, 1.5e9, 2.0e9):
            tt = simulate_etf(d_1h, D, flows, th)
            st = tstats(_window(_tframe(tt), "2024-01-01"))
            etf_sweep.append(dict(thresh_B=th / 1e9, n=st["tr"], PF=st["pf"], ret=st["ret"], avgR=st["avgR"]))
    else:
        etf_main = None

    return dict(
        label=label, eng=eng, D=D, day_t=day_t, a1=a1, a2=a2, a1meta=a1meta, a2meta=a2meta,
        proto_A1=r1, proto_A2=r2, passed=passed, coil=ev_rows, n_coil=n_ex,
        a3=a3_rows, a3_win=(lo, hi, why, a3_engs), basket=rows_b, base=base,
        tom00=tom00, tom22=tom22, tom_plc=tom_plc, use_fund=use_f,
        etf=etf_main, etf_plc=etf_plc, etf_sweep=etf_sweep, have_etf=have_etf and flows is not None,
        k8d=k8d, runtime=time.time() - t_a,
    )

def print_offset_compact(rows, engines):
    print("\n=== A3 expiry offsets (monthly / quarterly) avgR (z, n) ===")
    for eng in engines:
        bits = []
        for od in range(-7, 4):
            m = next((r for r in rows if r["engine"] == eng and r["offset"] == od and r["cal"] == "mth"), None)
            q = next((r for r in rows if r["engine"] == eng and r["offset"] == od and r["cal"] == "qtr"), None)
            def cell(r):
                if r is None or r["n"] == 0: return "·"
                return f"{fmt(r['avgR'],2)}/{fmt_z(r['z'])}/{r['n']}"
            bits.append(f"{od:+d}:{cell(m)}|{cell(q)}")
        print(f"  {eng:5s} " + "  ".join(bits))

def robustness_tom(d_1h, D, fund3, use_f):
    rows = []
    for m, hd, sm in ((0.8, 2, 1.6), (1.0, 3, 2.0), (1.2, 4, 2.4)):
        tr = simulate_tom(d_1h, D, 0, fund3, use_f, 0, stop_mult=sm, hold_days=hd)
        st = tstats(_window(_tframe(tr), HEADLINE_START))
        rows.append(dict(scale=m, hold=hd, stop=sm, n=st["tr"], PF=st["pf"], ret=st["ret"]))
    return rows

def run_all(btc, eth, fund, flows, have_fund, have_etf):
    expiries = last_friday_expiries("2013-01-01")
    set_asset(btc)
    k8_btc = k8_daily(btc)
    # k8_daily already set_asset; normalize index to dates
    if not isinstance(k8_btc.index, pd.DatetimeIndex):
        k8_btc.index = _floor_day(pd.to_datetime(np.asarray(k8_btc.index) * D1, unit="ms", utc=True))
    AB = run_asset("BTC", btc, fund, flows, expiries, k8_btc, have_fund, have_etf)
    set_asset(eth)
    k8_eth = k8_daily(eth)
    if not isinstance(k8_eth.index, pd.DatetimeIndex):
        k8_eth.index = _floor_day(pd.to_datetime(np.asarray(k8_eth.index) * D1, unit="ms", utc=True))
    AE = run_asset("ETH", eth, fund, flows, expiries, k8_eth, False, have_etf)  # no ETH funding file

    for lab, A in (("BTC", AB), ("ETH", AE)):
        print(f"\n########## {lab} ##########")
        # state occupancy
        for name, st in (("A1", A["a1"]), ("A2", A["a2"])):
            s = pd.Series(st)
            mask = A["day_t"] >= ms(HEADLINE_START)
            vc = s[mask].value_counts(normalize=True).mul(100)
            print(f"  {name} occupancy 2017+ (%): " + ", ".join(f"{k} {vc.get(k,0):.1f}" for k in (A1_STATES if name=='A1' else A2_STATES)))
        print_proto(A["proto_A1"], f"{lab} A1 next-30d R by state (z vs 1000 block-shuffles)")
        print_proto(A["proto_A2"], f"{lab} A2 next-30d R by state (z vs 1000 block-shuffles)")
        print(f"\n=== {lab} A2 COIL-exit event study (engine R in next 30d, n={A['n_coil']} exits) ===")
        ev = pd.DataFrame(A["coil"])
        ev["fwd30"] = ev["fwd30"].map(fmt_z); ev["placebo"] = ev["placebo"].map(fmt_z); ev["z"] = ev["z"].map(fmt_z)
        print(ev.to_string(index=False))
        print_offset_compact(A["a3"], LIVE_ENGINES)
        lo, hi, why, engs = A["a3_win"]
        print(f"  A3 window: offsets {lo}..{hi} on {engs}  ({why})")
        print_basket(A["basket"], f"{lab} basket overlay vs baseline (live risks, 2017+)")

    # standalone C1 / C2 with ETH PF
    rows = []
    def add_idea(name, btc_tr, btc_plc, eth_tr, k8d, note=""):
        row = idea_row(name, btc_tr, btc_plc, k8d)
        eth_s = tstats(_window(_tframe(eth_tr), HEADLINE_START if "ETF" not in name else "2024-01-01"))
        row["_eth_pf"] = eth_s["pf"]
        row["ETH PF"] = fmt(eth_s["pf"], 2)
        row["note"] = note
        v, fails = verdict_of(row)
        row["verdict"] = v
        row["_fails"] = fails
        rows.append(row)
        return row

    add_idea("C1-TOM 00:00", AB["tom00"], AB["tom_plc"], AE["tom00"], AB["k8d"],
             note=("funding 90/70 filter on" if AB["use_fund"] else "NO funding filter (data missing)"))
    add_idea("C1-TOM 22:00", AB["tom22"], AB["tom_plc"], AE["tom22"], AB["k8d"],
             note="entry at 22:00 UTC close")
    if AB["have_etf"] and AB["etf"] is not None:
        # C2 is 2024+; idea_row uses 2017+ headline — override windows by tagging start
        # Use HEADLINE but almost all trades are 2024+; ETH uses BTC flows as cross-asset.
        add_idea("C2-ETF $1B", AB["etf"], AB["etf_plc"], AE["etf"] or [], AB["k8d"],
                 note="T+1 Farside US spot BTC ETF flows; ETH uses the same BTC flow series")
    else:
        print("\nC2 ETF flow tilt: SKIPPED (could not load hosted/local btc_etf_flows.csv.gz)")

    show(rows, "STANDALONE ideas")
    if AB["have_etf"] and AB["etf_sweep"]:
        print("\n=== C2 threshold sweep (BTC, 2024+) ===")
        sw = pd.DataFrame(AB["etf_sweep"])
        sw["PF"] = sw["PF"].map(lambda x: fmt(x, 2)); sw["ret"] = sw["ret"].map(lambda x: fmt(x, 1)); sw["avgR"] = sw["avgR"].map(lambda x: fmt(x, 2))
        print(sw.to_string(index=False))

    # KEEP robustness
    keeps = [r for r in rows if r["verdict"] == "KEEP"]
    if any(r["idea"].startswith("C1-TOM 00:00") for r in keeps):
        print("\n=== KEEP robustness (C1-TOM 00:00, hold/stop +-20%) ===")
        fund3 = funding_3s(fund)
        set_asset(btc)
        rb = robustness_tom(btc, AB["D"], fund3, AB["use_fund"])
        print(pd.DataFrame(rb).to_string(index=False))

    print("\n=== VERDICTS ===")
    for r in rows:
        v, fails = r["verdict"], r["_fails"]
        print(f"  {v:5s}  {r['idea']}: BTC PF {fmt(r['_pf'],2)} n={r['_n']}; ETH PF {r['ETH PF']}; corrK8 {r['corrK8']}"
              + (f"  fails {fails}" if fails else "") + (f"  [{r['note']}]" if r.get("note") else ""))

    print("\n=== PLAIN WORDS ===")
    # A1/A2 passed mappings
    def passed_list(proto, card):
        hits = [f"{p['engine']}/{p['state']}" for p in proto if p["pass_"] == "yes"]
        return hits
    for lab, A in (("BTC", AB), ("ETH", AE)):
        h1, h2 = passed_list(A["proto_A1"], "A1"), passed_list(A["proto_A2"], "A2")
        print(f"  {lab} A1 mappings that passed z>=2 and both halves: " + (", ".join(h1) if h1 else "none") + ".")
        print(f"  {lab} A2 mappings that passed z>=2 and both halves: " + (", ".join(h2) if h2 else "none") + ".")
        # highlight coil-exit
        coil_ok = [x["engine"] for x in A["coil"] if np.isfinite(x.get("z", np.nan)) and x["z"] >= 2]
        print(f"  {lab} A2 COIL-exit 30d R beat placebo (z>=2): " + (", ".join(coil_ok) if coil_ok else "none") + ".")
        lo, hi, why, engs = A["a3_win"]
        print(f"  {lab} A3 best window offsets {lo}..{hi} for {engs} ({why}).")
        # basket punchline
        b = {r["overlay"]: r for r in A["basket"]}
        def punch(name):
            r = b.get(name) or next((x for x in A["basket"] if x["overlay"].startswith(name[:2])), None)
            return r
        for key in ("A1 proposed", "A2 proposed"):
            r = b.get(key)
            if not r: continue
            direction = "helps" if (np.isfinite(r["d_MAR"]) and r["d_MAR"] > 0 and r["d_ret"] > 0) else "does not improve"
            print(f"  {lab} {key} {direction} the live-risk basket (Δret {fmt(r['d_ret'],1)} pts, ΔMAR {fmt(r['d_MAR'],2)}).")
    if rows:
        for r in rows:
            print(f"  {r['verdict']}  {r['idea']}: " +
                  (f"passes the pre-declared tests (BTC PF {fmt(r['_pf'],2)}, ETH {r['ETH PF']})."
                   if r["verdict"]=="KEEP" else
                   f"fails {r['_fails']}."))
    print("  Paper-trade any KEEP before it gets money; overlays resize existing engines, they are not new signals.")
    print("  A1 is the baseline every fancier state must beat: if ER/ADX does not split engine R with z>=2, ignore A2 decorations.")

    # write compact csv
    try:
        pd.DataFrame(AB["proto_A1"] + AB["proto_A2"] + AE["proto_A1"] + AE["proto_A2"]).to_csv(OUT_DIR / "batch10_protocol.csv", index=False)
        pd.DataFrame(AB["basket"] + [dict(overlay=r["overlay"], asset="ETH", **{k:r[k] for k in r if k!='overlay'}) for r in AE["basket"]]).to_csv(OUT_DIR / "batch10_basket.csv", index=False)
        if rows:
            keep_cols = [c for c in rows[0] if not str(c).startswith("_") or c in ()]
            pd.DataFrame([{k: r[k] for k in r if not str(k).startswith("_")} | {"verdict": r["verdict"]} for r in rows]).to_csv(OUT_DIR / "batch10_ideas.csv", index=False)
        print(f"\nWrote batch10_protocol/basket/ideas.csv to {OUT_DIR} | runtime {time.time()-T0:.0f}s")
    except Exception as e:
        print(f"  csv write failed: {e}")
    return AB, AE, rows

# ---------------------------------------------------------------------------
# Smoke (synthetic only) and main
# ---------------------------------------------------------------------------
def synthetic_1h(n=9000, seed=7, start="2017-01-02"):
    """Regime-rich synthetic 1h series: trend, chop, vol expansion, plus month structure."""
    rng = np.random.default_rng(seed)
    t0 = ms(start)
    t = t0 + np.arange(n, dtype="int64") * H1
    # piecewise drift / vol
    day = np.arange(n) // 24
    regime = (day // 40) % 5  # 0 trend-up, 1 chop, 2 trend-dn, 3 expansion, 4 coil-ish
    drift = np.where(regime == 0, 0.00025, np.where(regime == 2, -0.00025, 0.0))
    vol = np.where(regime == 3, 0.012, np.where(regime == 4, 0.003, np.where(regime == 1, 0.005, 0.006)))
    # occasional shock days
    shock = rng.random(n) < 0.002
    vol = vol + shock * 0.02
    r = drift + vol * rng.normal(size=n)
    close = 1000.0 * np.exp(np.cumsum(r))
    open_ = np.r_[close[0], close[:-1]]
    wh = np.abs(rng.normal(0, 1, n)) * vol * close
    high = np.maximum(open_, close) + wh
    low = np.minimum(open_, close) - wh
    low = np.maximum(low, 1e-6)
    volm = rng.lognormal(8, 0.4, n)
    return pd.DataFrame({"time": t, "open": open_, "high": high, "low": low, "close": close, "volume": volm, "source": "synth"})

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

def synthetic_etf(start="2024-01-11", end="2026-11-20", seed=5):
    rng = np.random.default_rng(seed)
    days = pd.date_range(start, end, freq="D", tz="UTC")
    # weekdays only have flow; weekends 0. Autocorr bursts.
    e = rng.normal(0, 2e8, len(days))
    for i in range(1, len(e)):
        e[i] = 0.4 * e[i - 1] + e[i]
    e[days.dayofweek >= 5] = 0
    return pd.DataFrame({"date": days.floor("D"), "flow_usd": e})

def run_smoke():
    print("=== batch10 smoke (synthetic only) ===", flush=True)
    d = synthetic_1h()
    # A1/A2 labels
    set_asset(d)
    D = build_day(None); D = market_states(D)
    a1, m1 = label_A1(D); a2, m2 = label_A2(D)
    assert set(np.unique(a1)).issubset(set(A1_STATES)), set(np.unique(a1))
    assert set(np.unique(a2)).issubset(set(A2_STATES)), set(np.unique(a2))
    # expansion override: when atr_ratio >= 1.5, state is EXPANSION
    rat = m1["atr_ratio"]
    hit = np.isfinite(rat) & (rat >= 1.5)
    if hit.any():
        assert np.all(a1[hit] == "EXPANSION")
    # ER in (0,1] when defined
    er = m1["er"]
    ok = np.isfinite(er)
    assert ok.any() and np.nanmin(er[ok]) >= 0 and np.nanmax(er[ok]) <= 1.0001
    # block shuffle preserves frequencies
    rng = np.random.default_rng(0)
    sh = block_shuffle(a1, rng)
    def cnt(s):
        u, c = np.unique(s, return_counts=True)
        return dict(zip(u, c))
    assert cnt(sh) == cnt(a1)
    # engines run
    fund = synthetic_funding(d)
    eng, _ = run_engines(d, fund)
    assert set(LIVE_ENGINES) <= set(eng)
    ntr = {k: len(v) for k, v in eng.items()}
    print("  engine trades:", ntr)
    assert sum(ntr.values()) >= 1, "no engine produced a trade on the synthetic trend/chop series"
    # some engines that fire on trend/vol should usually have trades; don't require all 10
    # protocol + basket
    day_t, _ = daily_index(D)
    a1d, a2d = day_in_state(a1), day_in_state(a2)
    expiries = last_friday_expiries("2017-01-01", "2020-01-01")
    for tr in eng.values():
        tag_asset_trades(tr, a1, a1d, a2, a2d, day_t, expiries)
    r1, p1 = eval_protocol("A1", a1, A1_STATES, eng, day_t, seed=1)
    r2, p2 = eval_protocol("A2", a2, A2_STATES, eng, day_t, seed=2)
    assert len(r1) == 10 * len(A1_STATES) and len(r2) == 10 * len(A2_STATES)
    ev, nex = coil_exit_study(a2, eng, day_t, n_plac=30, seed=3)
    assert len(ev) == 10
    base = basket_curve(eng, day_t, sizes_fn("base"))
    ov = basket_curve(eng, day_t, sizes_fn("A1"))
    assert np.isfinite(base["ret"]) and np.isfinite(ov["ret"])
    # A3
    a3r = a3_offset_table(eng, expiries, n_plac=20, seed=4)
    lo, hi, why = choose_a3_window(a3r)
    assert -7 <= lo <= hi <= 3
    # ToM: roughly one long per month
    tom = simulate_tom(d, D, 0, funding_3s(fund), True, 0)
    months = max(1, int((d["time"].iloc[-1] - d["time"].iloc[0]) / (30 * D1)))
    print(f"  ToM trades={len(tom)} over ~{months} months")
    assert len(tom) >= max(3, months // 4), "ToM should fire on most month ends"
    tom22 = simulate_tom(d, D, 22, funding_3s(fund), True, 0)
    assert len(tom22) >= 1
    plc = simulate_tom(d, D, 0, funding_3s(fund), True, -7) + simulate_tom(d, D, 0, funding_3s(fund), True, 7)
    assert len(plc) >= 1
    # ETF with T+1 lag: construct a +$2B F5 burst and ensure entry is the NEXT open
    t0s = pd.to_datetime(int(d["time"].iloc[0]), unit="ms", utc=True).strftime("%Y-%m-%d")
    t1s = pd.to_datetime(int(d["time"].iloc[-1]), unit="ms", utc=True).strftime("%Y-%m-%d")
    flows = synthetic_etf(t0s, t1s)
    # force a known burst
    if len(flows) > 20:
        flows = flows.copy()
        flows.loc[10:14, "flow_usd"] = 4e8  # 5*0.4e9=2e9
    et = simulate_etf(d, D, flows, 1e9, min_date="2017-01-01")
    print(f"  ETF trades={len(et)}")
    assert len(et) >= 1, "C2 ETF should fire on a forced +$2B F5 burst"
    # T+1: entry time is the NEXT daily open after the signal close
    for tr in et:
        # entry is an hour open; must be strictly after some daily close
        assert tr["t_out"] >= tr["t_in"]
    for th in (0.5e9, 2e9):
        simulate_etf(d, D, flows, th, min_date="2017-01-01")
    # real-data guard is a main() concern
    # state occupancy sanity
    print("  A1 counts", cnt(a1), "A2 counts", cnt(a2), "coil exits", nex)
    print("  basket base ret/MAR", fmt(base["ret"],1), fmt(base["MAR"],2), "A1", fmt(ov["ret"],1), fmt(ov["MAR"],2))
    print("=== smoke ok ===")

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

if __name__ == "__main__" or True:
    # `%run` in Colab sets __name__ to "__main__"; keep a always-on footer like batch 7/8,
    # but refuse real-data runs on the box.
    if "--smoke" in sys.argv:
        run_smoke()
        sys.exit(0)
    if not _in_colab():
        raise SystemExit("batch10.py refuses to backtest real data outside Colab. Use: python3 batch10.py --smoke")
    print("Loading BTC/ETH 1h + funding + ETF flows ...", flush=True)
    btc, bsrc = load_asset("btc")
    eth, esrc = load_asset("eth")
    assert btc is not None and len(btc) > 1000, "BTC 1h data missing"
    assert eth is not None and len(eth) > 1000, "ETH 1h data missing"
    eth = fix_eth_bar(eth)
    print(f"BTC DATA: {bsrc} | {len(btc):,} rows")
    print(f"ETH DATA: {esrc} | {len(eth):,} rows")
    fund = load_funding()
    have_fund = fund is not None and len(fund) > 100
    print(f"FUNDING: {'yes, '+str(len(fund))+' rows' if have_fund else 'NO — C1 ToM will run without the 90/10 and 70th funding gates'}")
    flows = load_etf()
    have_etf = flows is not None and len(flows) > 50
    if have_etf:
        print(f"ETF FLOWS: {len(flows)} days  {pd.to_datetime(flows['date']).min().date()} → {pd.to_datetime(flows['date']).max().date()}  (Farside US spot BTC, T+1 in the tester)")
    else:
        print("ETF FLOWS: missing — C2 will be skipped")
    run_all(btc, eth, fund, flows, have_fund, have_etf)
