# ===== TEST 1 — COCO VARIANTS (coil 2-of-4 vs 3-of-4, box 5/7/10 days, trail 2.5/3.0/3.5 ATR) on BTC + ETH, with placebos — paste this WHOLE cell into ONE Colab cell =====
# Kubu research cell (takes over Colab backtesting from Bobo). Research only: touches no server, no exchange, no orders.
# Engine/definitions copied from Bobo's risk_combos2.py (data loaders, market states QUAKE/EXHAUST/RIDE/COIL, K8, coil_setups,
#   sim_leg, first_touch, the batch-4 OCO bracket with ONE re-arm), so BASE-LIVE* should reproduce the live COCO sleeve.
# Rules: costs 0.07% fee + 0.05% slip per side | stop-entry fills at the level (or the open if gapped through) | stop first
#   when a bar touches stop and target | CAP10 (stop > 10% from entry moved to 10%) | trades with stop < 1.5% SKIPPED (every
#   row except BASE-LIVE*, which is Bobo's live sleeve exactly as it runs: CAP10, no 1.5% skip) | real BTC funding charged
#   per 8h settlement while a position is open (2020+, where data exists; ETH has no funding file -> none charged).
# Sizing: $10,000 from 2017-01-01, 3% risk per trade (COCO's live risk), notional <= 3x equity (3x isolated), margin =
#   notional/3; if free margin is short the trade is shrunk (skipped if < 25% fits) — same rule as risk_combos2.
import os, io, gzip, time, warnings, math
from pathlib import Path
from urllib.request import urlopen, Request
import numpy as np
import pandas as pd
warnings.filterwarnings("ignore")
pd.set_option("display.width", 250); pd.set_option("display.max_columns", 40); pd.set_option("display.max_rows", 300)

T0 = time.time()
H1 = 3_600_000; D1 = 24 * H1; H4 = 4 * H1; H12 = 12 * H1
FEE, SLIP = 0.0007, 0.0005
COST = FEE + SLIP
RISK = 0.01
MAX_NOTIONAL = 1.0
SITE = "https://osom-boba.pages.dev/colab/"
OUT_DIR = Path("/content") if Path("/content").exists() else Path(".")
STATES = ["QUAKE", "EXHAUST", "RIDE", "COIL", "CHOP"]
SCODE = {s: i for i, s in enumerate(STATES)}
RNG = np.random.default_rng(20261117)
STOP_RULE = None
MAX_HOLD = 30 * 24
MIN_STOP = 0.015; MIN_ON = True
HEADLINE_START = "2017-01-01"

# ---------------------------------------------------------------------------------------------
# DATA
# ---------------------------------------------------------------------------------------------
def _fetch(url):
    with urlopen(Request(url, headers={"User-Agent": "Mozilla/5.0 (colab specialists)"}), timeout=120) 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")] if p.exists()]:
        d = _norm(pd.read_csv(p))
        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 wilder(x, n):
    return pd.Series(x).ewm(alpha=1.0 / n, adjust=False).mean().values

def atr(h, l, c, n=14):
    pc = np.r_[np.nan, c[:-1]]
    tr = np.nanmax(np.vstack([h - l, np.abs(h - pc), np.abs(l - pc)]), axis=0)
    return wilder(tr, n)

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

# ---------------------------------------------------------------------------------------------
# asset context (module globals so the engine stays fast and simple)
# ---------------------------------------------------------------------------------------------
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 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

# ---------------- ENGINE (Bobo's run(), used here for K8 only) ----------------
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 = s; pend_stop = stop_dist[i]; 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 ms(s): return pd.Timestamp(s).value // 1_000_000

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

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

def market_states(D, coil_k=3, m=1.0):   # coil_k / m added for TEST 1 (live = 3, 1.0)
    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 * m).astype(int) + (rng7_pct <= 0.20 * m).astype(int) + (bbw_pct <= 0.20 * m).astype(int) + (voldry <= 0.8 * m).astype(int)
    coil = (cnt >= coil_k) & (er10 < 0.35 * m)
    st = np.full(n, "CHOP", dtype=object); sd = np.zeros(n)
    st[coil] = "COIL"
    st[ride_up | ride_dn] = "RIDE"; sd[ride_up] = 1; sd[ride_dn & ~ride_up] = -1
    exm = ex_up | ex_dn
    st[exm] = "EXHAUST"; sd[ex_up] = 1; sd[ex_dn & ~ex_up] = -1
    st[quake] = "QUAKE"; sd[quake] = qdir[quake]
    warm = ~np.isfinite(atrp_pct) | ~np.isfinite(a20p)
    st[warm] = "WARMUP"; sd[warm] = 0
    rpct = pd.Series((hi20 - lo20) / pc).rolling(365, min_periods=200).rank(pct=True).values
    brk = (rpct <= 0.30) & ((c > hi20) | (c < lo20))
    brk3 = brk | np.r_[False, brk[:-1]] | np.r_[False, False, brk[:-2]]
    D["state"] = st; D["sdir"] = sd; D["brk3"] = brk3
    return D

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

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

def sim_leg(i0, side, entry, stop, tp=np.nan, trail=None, exh=None, fill_bar_stopentry=False, chand=None):
    """Walk 1h bars from i0 (entry bar). Returns (exit_i, exit_px, kind, frac, stop0)."""
    if STOP_RULE is not None and abs(entry - stop) / entry > STOP_RULE[1]:
        if STOP_RULE[0] == "skip": return None
        stop = entry - side * STOP_RULE[1] * entry
    stop0 = stop; risk = abs(entry - stop) / entry
    if 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

# PLACEBO (pre-declared): the coil filter is the edge, so the placebo keeps EVERYTHING else identical (same N-day box
#   = prior N-day high/low, same 10-day arming, same OCO + one re-arm, same stops/trail/time exit, same costs and sizing)
#   but picks the box days at RANDOM from ALL non-warm-up days (any state, coil or not), matched to the real variant's
#   2017+ setup count and the same >= M-day spacing. Seeds fixed (20261117+s); median PF of N_PLAC=10 draws reported.
#   A real box-breakout edge from the coil filter must beat "any 7-day box breakout" by >= 0.3 PF.
def placebo_setups(D, P, S, seed):
    rng = np.random.default_rng(20261117 + seed); t0 = ms(HEADLINE_START)
    st = D["state"].values; at = D["atr"].values; li = D["last_i"].values; hi = D.high.values; lo = D.low.values
    N_, M_ = int(P["N"]), int(P["M"]); k = sum(1 for s in S if s["t"] >= t0)
    d_all = np.arange(N_, len(D)); i0s = li[d_all] + 1
    ok = (st[d_all] != "WARMUP") & np.isfinite(at[d_all]) & (i0s < N - 2)
    ok[ok] &= T[i0s[ok]] >= t0
    cand = d_all[ok]; rng.shuffle(cand); acc = []
    for d in cand:
        if len(acc) >= k: break
        if acc and np.min(np.abs(np.array(acc) - d)) < M_: continue
        acc.append(int(d))
    out = []
    for d in sorted(acc):
        i0 = li[d] + 1
        out.append(dict(d=d, i0=i0, i1=min(N - 1, i0 + M_ * 24), bh=hi[d - N_ + 1:d + 1].max(), bl=lo[d - N_ + 1:d + 1].min(), A=at[d], t=T[i0]))
    return out

def sleeve(trades, fund=True):
    """single-sleeve account: $10k from 2017-01-01, 3% risk, notional <= 3x equity, isolated margin = notional/3."""
    ev = sorted([t for t in trades if t[0] >= ms(HEADLINE_START) and np.isfinite(t[6]) and t[6] > 0], key=lambda x: (x[0], x[1]))
    if not ev: return None
    ti = np.array([t[0] for t in ev], dtype="int64"); to = np.array([t[1] for t in ev], dtype="int64")
    sd = np.array([t[2] for t in ev], dtype=float); mv = np.array([t[5] for t in ev]); rp = np.array([t[6] for t in ev])
    fs = fund_sum(ti, to) if fund else np.zeros(len(ev))
    eq = EQ0; open_ = []; book = []; skipped = 0; peak_mu = 0.0; fpaid = 0.0
    def close_until(tm):
        nonlocal eq, open_
        keep = []
        for o in sorted(open_, key=lambda z: z[0]):
            if o[0] <= tm: eq += o[1]; book.append((o[0], o[1], eq, o[1] / o[3], o[4]))
            else: keep.append(o)
        open_ = keep
    for k in range(len(ev)):
        close_until(ti[k])
        if eq <= 0: break
        notional = min(LEV * eq, eq * RISK_COCO / rp[k]); margin = notional / LEV
        free = eq - sum(o[2] for o in open_)
        if margin > free + 1e-9:
            if free <= 0 or free / margin < MIN_FRAC: skipped += 1; continue
            notional *= free / margin; margin = free
        peak_mu = max(peak_mu, (sum(o[2] for o in open_) + margin) / eq)
        pnl = notional * (mv[k] - sd[k] * fs[k] - 2 * COST); fpaid += notional * sd[k] * fs[k]
        open_.append((to[k], pnl, margin, eq, mv[k]))
    close_until(10**18)
    return dict(book=pd.DataFrame(book, columns=["t", "pnl", "equity", "ret", "mv"]), skipped=skipped, peak_mu=peak_mu, fpaid=fpaid)

def metrics(sl):
    if sl is None or not len(sl["book"]):
        return dict(final=EQ0, pf=np.nan, n=0, win=np.nan, dd=np.nan, b1=np.nan, b2=np.nan, y26=np.nan, adv=np.nan, skip=0, mu=np.nan, daily=pd.Series(dtype=float), fpaid=0.0)
    b = sl["book"]; eqs = np.r_[EQ0, b.equity.values]; pk = np.maximum.accumulate(eqs)
    g = b.ret[b.ret > 0].sum(); ls = -b.ret[b.ret < 0].sum()
    def eq_at(day):
        x = b[b.t < ms(day)]; return x.equity.iloc[-1] if len(x) else EQ0
    blk = lambda a, z: 100 * (eq_at(z) / eq_at(a) - 1)
    return dict(final=b.equity.iloc[-1], pf=(g / ls if ls > 0 else np.inf), n=len(b), win=100 * (b.ret > 0).mean(),
                dd=100 * (eqs / pk - 1).min(), b1=blk("2017-01-01", "2021-01-01"), b2=blk("2021-01-01", "2100-01-01"),
                y26=blk("2026-01-01", "2027-01-01"), adv=float((-b.mv).max()), skip=sl["skipped"], mu=100 * sl["peak_mu"],
                daily=b.groupby(b.t // D1).ret.sum(), fpaid=sl["fpaid"])

def k8_daily(D):
    """live K8 exactly as risk_combos2 builds it (CAP10), daily realised returns by exit day."""
    global STOP_RULE
    STOP_RULE = ("cap", 0.10)
    try:
        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"]))
    finally:
        STOP_RULE = None
    t = pd.DataFrame(engine_trades(res), columns=["t_in", "t_out", "side", "ret", "kind", "move", "risk"])
    return t.groupby(t.t_out // D1).ret.sum()

# ---------------------------------------------------------------------------------------------
# LOAD
# ---------------------------------------------------------------------------------------------
A = {}
btc, SRC = load_asset("btc")
if btc is None or _bar_ms(btc) > H1: raise SystemExit("Needs BTC 1h data (hosted btc_1h_full.csv.gz).")
FUND = load_funding()
eth, ESRC = load_asset("eth")
print(f"BTC: {len(btc):,} 1h rows {pd.to_datetime(btc.time.iloc[0], unit='ms'):%Y-%m-%d}..{pd.to_datetime(btc.time.iloc[-1], unit='ms'):%Y-%m-%d} | "
      f"funding: {0 if FUND is None else len(FUND):,} settlements" + ("" if FUND is None else f" from {pd.to_datetime(FUND.time.min(), unit='ms'):%Y-%m-%d}"))
for nm, d, fund in (("BTC", btc, FUND), ("ETH", eth, None)):
    if d is None or _bar_ms(d) > H1: print(f"{nm}: no 1h data -> skipped"); continue
    if nm == "ETH":
        d = fix_eth_bar_exact(d)
        print(f"ETH: {len(d):,} 1h rows {pd.to_datetime(d.time.iloc[0], unit='ms'):%Y-%m-%d}..{pd.to_datetime(d.time.iloc[-1], unit='ms'):%Y-%m-%d} | no ETH funding file -> none charged")
    set_asset(d); DB = build_day(fund)
    A[nm] = dict(df=d, day=DB, fund=fund, chand=to_base(DB, DB["atr"].values, D1), states={})
set_asset(A["BTC"]["df"]); K8D = k8_daily(market_states(A["BTC"]["day"].copy()))
IDX = np.arange(ms(HEADLINE_START) // D1, int(T[-1] // D1) + 1)

def use(nm):
    global CHAND
    set_asset(A[nm]["df"]); set_funding(A[nm]["fund"]); CHAND = A[nm]["chand"]

def states(nm, k, m):
    key = (k, round(m, 3))
    if key not in A[nm]["states"]: A[nm]["states"][key] = market_states(A[nm]["day"].copy(), coil_k=k, m=m)
    return A[nm]["states"][key]

def eval_variant(v, m=1.0, placebo=True):
    """m scales every numeric parameter (box days, arming days, trail ATR, max hold, coil thresholds, ER) for robustness."""
    global MAX_HOLD, MIN_ON, STOP_RULE
    out = {}
    STOP_RULE = ("cap", 0.10)                       # CAP10, as build_sleeves() runs the live COCO
    P = dict(N=max(2, int(round(v["N"] * m))), M=max(2, int(round(10 * m))))
    MAX_HOLD = int(round(30 * 24 * m)); MIN_ON = v.get("min", True)
    try:
        for nm in A:
            use(nm); D = states(nm, v["k"], m); S = coil_setups(D, P)
            r = metrics(sleeve(sys_coco(S, v["trail"] * m))); out[nm] = r
            if nm == "BTC":
                out["corr"] = r["daily"].reindex(IDX).fillna(0).corr(K8D.reindex(IDX).fillna(0)) if r["n"] else np.nan
                if placebo:
                    pf = [metrics(sleeve(sys_coco(placebo_setups(D, P, S, s), v["trail"] * m)))["pf"] for s in range(N_PLAC)]
                    out["ppf"] = float(np.nanmedian(np.where(np.isfinite(pf), pf, np.nan)))
    finally:
        MAX_HOLD = 30 * 24; MIN_ON = True; STOP_RULE = None
    return out

def judge(o):
    b = o["BTC"]; e = o.get("ETH", {"pf": np.nan}); f = []
    if not (b["pf"] >= 1.3 and b["n"] >= 30): f.append(f"PF {fmt(b['pf'],2)}/n {b['n']}")
    if not (np.isfinite(o.get("ppf", np.nan)) and b["pf"] - o["ppf"] >= 0.3): f.append(f"placebo {fmt(o.get('ppf', np.nan),2)}")
    if not (b["b1"] > 0 and b["b2"] > 0): f.append(f"17-20/21+ {fmt(b['b1'],0)}/{fmt(b['b2'],0)}%")
    if not (e["pf"] >= 1.1): f.append(f"ETH PF {fmt(e['pf'],2)}")
    if not (np.isfinite(o["corr"]) and o["corr"] < 0.3): f.append(f"corrK8 {fmt(o['corr'],2)}")
    return ("KEEP" if not f else "WATCH" if len(f) == 1 else "DROP"), f

# ---------------------------------------------------------------------------------------------
# VARIANTS (one-at-a-time from the live baseline + 4 combos). k = coil count needed of 4, N = box days, trail = x ATR20.
# ---------------------------------------------------------------------------------------------
VARIANTS = [dict(name="BASE-LIVE*", k=3, N=7, trail=3.0, min=False), dict(name="BASE", k=3, N=7, trail=3.0),
            dict(name="C2", k=2, N=7, trail=3.0), dict(name="N5", k=3, N=5, trail=3.0), dict(name="N10", k=3, N=10, trail=3.0),
            dict(name="T2.5", k=3, N=7, trail=2.5), dict(name="T3.5", k=3, N=7, trail=3.5),
            dict(name="C2-N5", k=2, N=5, trail=3.0), dict(name="C2-N10", k=2, N=10, trail=3.0),
            dict(name="N5-T2.5", k=3, N=5, trail=2.5), dict(name="N10-T3.5", k=3, N=10, trail=3.5)]

print("\nPRE-DECLARED VERDICT (written before results): KEEP if (1) BTC 2017+ PF >= 1.3 with >= 30 trades, (2) PF beats its")
print("  placebo PF by >= 0.3, (3) 2017-20 AND 2021+ net both > 0, (4) ETH PF >= 1.1, (5) daily corr with K8 < 0.3.")
print("  WATCH = fails exactly one, DROP = fails 2+. KEEPs get +-20% robustness (all numeric params x0.8 / x1.2; robust if")
print("  BTC PF >= 1.15 and net > 0 both ways). Placebo = same boxes/exits on random non-coil-filtered days (count-matched).")

rows = []; RES = {}
for v in VARIANTS:
    o = eval_variant(v); RES[v["name"]] = o; vd, f = judge(o); b = o["BTC"]; e = o.get("ETH", metrics(None))
    rows.append({"variant": v["name"], "BTC $": f"{b['final']:,.0f}", "PF": fmt(b["pf"], 2), "n": b["n"], "win%": fmt(b["win"], 0),
                 "DD%": fmt(b["dd"], 0), "17-20%": fmt(b["b1"], 0), "21+%": fmt(b["b2"], 0), "2026%": fmt(b["y26"], 1),
                 "ETH $": f"{e['final']:,.0f}", "ETH PF": fmt(e["pf"], 2), "ETH n": e["n"], "plac PF": fmt(o.get("ppf", np.nan), 2),
                 "corrK8": fmt(o["corr"], 2), "verdict": vd, "_f": f, "_v": v})
R = pd.DataFrame(rows)
print(f"\n=== COCO VARIANTS — $10,000 from 2017-01-01 at 3% risk, realised equity (DD% at closes) | costs+funding | CAP10 ===")
print(R[[c for c in R.columns if not c.startswith("_")]].to_string(index=False))
print("  * BASE-LIVE = live COCO as it runs (no 1.5% skip), reference only; all other rows skip stops < 1.5%.")
FL = [f"{r['variant']}: {'; '.join(r['_f'])}" for _, r in R.iterrows() if r["_f"]]
print("\nFAILS: " + (" | ".join(FL[:4]) if FL else "none"))
for k in range(4, len(FL), 4): print("       " + " | ".join(FL[k:k + 4]))
adv = max(RES[n][a]["adv"] for n in RES for a in A if np.isfinite(RES[n][a]["adv"]))
sk = sum(RES[n][a]["skip"] for n in RES for a in A); mu = max(RES[n][a]["mu"] for n in RES for a in A if np.isfinite(RES[n][a]["mu"]))
fp = RES["BASE"]["BTC"]["fpaid"]
print(f"LIQUIDATION CHECK: worst adverse exit move {100*adv:.1f}% vs ~{100*LIQ_MOVE:.1f}% liq at 3x isolated -> "
      f"{'SAFE' if adv < LIQ_MOVE else 'NOT SAFE'} | peak margin use {mu:.0f}% of equity | margin-skipped trades {sk} | BASE BTC net funding paid ${fp:,.0f}")

ROB = []
for _, r in R[(R.verdict == "KEEP") & (R.variant != "BASE-LIVE*")].iterrows():
    row = {"variant": r["variant"]}; ok = True
    for m in (0.8, 1.2):
        o = eval_variant(r["_v"], m, placebo=False); b = o["BTC"]; e = o.get("ETH", metrics(None))
        row[f"x{m} BTC $/PF/n"] = f"{b['final']:,.0f}/{fmt(b['pf'],2)}/{b['n']}"; row[f"x{m} ETH PF"] = fmt(e["pf"], 2)
        ok &= bool(b["pf"] >= 1.15 and b["final"] > EQ0)
    row["robust"] = "yes" if ok else "NO"; ROB.append(row)
if ROB:
    print("\n=== KEEP robustness (+-20% on box days, arm days, trail, max hold, coil thresholds, ER) ===")
    print(pd.DataFrame(ROB).to_string(index=False))
else:
    print("\nNo KEEP (excluding BASE-LIVE*) -> no robustness run.")
kv = R[R.variant != "BASE-LIVE*"]
print(f"\nSUMMARY: KEEP {(kv.verdict=='KEEP').sum()} | WATCH {(kv.verdict=='WATCH').sum()} | DROP {(kv.verdict=='DROP').sum()} "
      f"| best BTC $: {kv.iloc[kv['BTC $'].str.replace(',', '').astype(float).argmax()]['variant']} | runtime {time.time()-T0:.0f}s")
R.drop(columns=["_f", "_v"]).to_csv(OUT_DIR / "test1_coco_variants.csv", index=False)
