# ===== batch16.py - 30 user ideas (5 buckets) + maker-entry test of each idea and of the live basket =====
# Colab:  !wget -q -O batch16.py "https://osom-boba.pages.dev/colab/batch16.py"
#         %run batch16.py
# Box (synthetic smoke only):  python3 batch16.py --smoke
#
# Conventions: signals on closed bars, fill at next bar open (stop-entry ideas fill when the level trades),
# stop beats target inside the same bar, 1% risk per trade, oslib COST 0.12%/side (taker).
# 1D bars = oslib.resample_ohlcv(1h, D1) (UTC days); 4H = resample_ohlcv(1h, H4). ATR = oslib.atr (Wilder, 14).
# Funding ideas (13-18) take signals from 2019-10-01 only (Binance 8h prints, used once the print time <= bar close).
# Gates (taker): PF>1.3 in 2017-20 AND 2021-26 (halves by exit time), n>=30, placebo pct>=90
#   (100 random-entry runs, same side / hold bars / stop distance), flipped PF<1, ETH PF>1.0 (n/a for
#   cross-asset ideas), daily-R corr with the live basket <0.3. corr with K8 is reported only.
# MAKER column: entry limit at signal close -/+ 0.20*ATR (long/short), valid the next 3 bars, skip if not
#   filled; entry cost 0.02%, exit cost 0.12%. Stop-entry ideas: the limit sits 0.20*ATR behind the
#   triggered level and is valid the 3 bars after the trigger bar.
# DIVERSIFIER candidates: fail only the PF-halves gates, overall PF>1.15, corr basket<0.1, ret 2018>0 and 2022>0.
# LIVE BASKET MAKER: oslib.engines trades repriced with the same limit rule on 1h bars (limit = 1h signal-bar
#   close -/+ 0.20*ATR14(1h), next 3 1h bars), same stop price and exit, vs baseline taker basket at LIVE_RISK.
import os, sys, time, subprocess, traceback
from pathlib import Path

T0 = time.time()
OSLIB_URL = "https://osom-boba.pages.dev/colab/oslib.py"

def _ensure_oslib():
    here = Path.cwd() / "oslib.py"
    if not here.exists():
        print("oslib.py missing -> downloading " + OSLIB_URL, flush=True)
        try:
            subprocess.run(["wget", "-q", "-O", str(here), OSLIB_URL], check=True)
        except Exception:
            from urllib.request import urlopen, Request
            raw = urlopen(Request(OSLIB_URL, headers={"User-Agent": "osom-b16/1.0"}), timeout=120).read()
            here.write_bytes(raw)
    if str(Path.cwd()) not in sys.path:
        sys.path.insert(0, str(Path.cwd()))

_ensure_oslib()
import numpy as np
import pandas as pd
import oslib as osl
from oslib import (load, funding, engines, overlay, atr, ema, sma, rsi, er, adx, bb_width, resample_ohlcv,
                   standardize, in_colab, LIVE_RISK, LIVE_ENGINES, COST, RISK, HEADLINE_START, H1, H4, D1)

assert abs(COST - 0.0012) < 1e-12, "Expected COST=0.0012"
assert abs(RISK - 0.01) < 1e-12, "Expected RISK=0.01"
print(f"oslib v{osl.__version__} | cost {100*COST:.2f}%/side | risk {100*RISK:.0f}%", flush=True)

MAKER_IN = 0.0002          # maker entry cost per side
MK_ATR = 0.20              # limit offset in ATR
MK_BARS = 3                # limit valid for the next 3 bars
N_PLACEBO = 100
CAP_DAYS = 90              # hard cap on any hold (safety; no idea asks for more)
TRIM_START = "2016-01-01"  # idea data trimmed here (1y warm-up before the 2017 headline)
FUND_START = "2019-10-01"
H_START = HEADLINE_START
NAN = np.nan

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

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

def sh1(x):
    x = np.asarray(x, dtype=float)
    return np.r_[NAN, x[:-1]]

def shn(x, k):
    x = np.asarray(x, dtype=float)
    return np.r_[np.full(k, NAN), x[:-k]] if k < len(x) else np.full(len(x), NAN)

def rmax(x, n):
    return osl.rolling_max(np.asarray(x, dtype=float), int(n))

def rmin(x, n):
    return osl.rolling_min(np.asarray(x, dtype=float), int(n))

def consec(mask):
    m = np.asarray(mask, dtype=bool).astype(int)
    c = np.cumsum(m)
    reset = np.maximum.accumulate(np.where(m == 0, c, 0))
    return c - reset

def prank(x, n, minp=None):
    return pd.Series(np.asarray(x, dtype=float)).rolling(int(n), min_periods=int(minp or n)).rank(pct=True).to_numpy()

def rcorr(a, b, n):
    return pd.Series(a).rolling(int(n), min_periods=int(n)).corr(pd.Series(b)).to_numpy()

def nz(x):
    return np.where(np.isfinite(x), x, 0.0)

def B_of(df, P, name):
    t = df["time"].to_numpy(dtype="int64")
    o, h, l, c = (df[k].to_numpy(dtype=float) for k in ("open", "high", "low", "close"))
    v = df["volume"].to_numpy(dtype=float) if "volume" in df.columns else np.zeros(len(t))
    return dict(t=t, o=o, h=h, l=l, c=c, v=v, P=int(P), tc=t + int(P), name=name, atr=atr(h, l, c, 14))

def align(src, vals, dst):
    """Value of the last src bar whose close <= dst bar close."""
    idx = np.searchsorted(src["tc"], dst["tc"], side="right") - 1
    vals = np.asarray(vals, dtype=float)
    out = np.full(len(dst["t"]), NAN)
    ok = idx >= 0
    out[ok] = vals[idx[ok]]
    return out

class Fund:
    def __init__(self, fdf):
        f = fdf.sort_values("time")
        self.ft = f["time"].to_numpy(dtype="int64")
        self.fv = f["funding"].to_numpy(dtype=float)
        self.cs = np.r_[0.0, np.cumsum(self.fv)]
        s = pd.Series(self.fv)
        mu, sd = s.rolling(42, min_periods=42).mean(), s.rolling(42, min_periods=42).std()
        self.z = ((s - mu) / sd.replace(0, np.nan)).to_numpy()
        dd = pd.Series(self.fv).groupby(self.ft // D1).sum()
        self.day_ids = dd.index.to_numpy(dtype="int64")
        self.day_sum = dd.to_numpy(dtype=float)

    def idx(self, times):
        return np.searchsorted(self.ft, np.asarray(times, dtype="int64"), side="right") - 1

    def last(self, B):
        i = self.idx(B["tc"])
        return np.where(i >= 0, self.fv[np.clip(i, 0, None)], NAN)

    def sum_n(self, B, n):
        i = self.idx(B["tc"]) + 1
        ok = i - n >= 0
        return np.where(ok, self.cs[np.clip(i, 0, None)] - self.cs[np.clip(i - n, 0, None)], NAN)

    def zlast(self, B):
        i = self.idx(B["tc"])
        return np.where(i >= 0, self.z[np.clip(i, 0, None)], NAN)

    def daily_sum(self, D):
        g = D["t"] // D1
        m = pd.Series(self.day_sum, index=self.day_ids)
        return m.reindex(g).to_numpy(dtype=float)

class Ctx:
    def __init__(self, name, h1df, fdf):
        self.name = name
        d = h1df[h1df["time"] >= ms(TRIM_START)].reset_index(drop=True)
        self.h1 = B_of(d, H1, name)
        self.h4 = B_of(resample_ohlcv(d, H4), H4, name)
        self.d = B_of(resample_ohlcv(d, D1), D1, name)
        self.f = Fund(fdf)

def joint(Ba, Bb, P):
    """Common-time copies of two bar sets (cross-asset ideas)."""
    common = np.intersect1d(Ba["t"], Bb["t"])
    out = []
    for B in (Ba, Bb):
        k = np.searchsorted(B["t"], common)
        df = pd.DataFrame({"time": common, "open": B["o"][k], "high": B["h"][k], "low": B["l"][k],
                           "close": B["c"][k], "volume": B["v"][k]})
        out.append(B_of(df, P, B["name"]))
    return out

# ---------------------------------------------------------------------------
# Simulator: one position at a time per run
# ---------------------------------------------------------------------------
def sim(B, sig=None, *, stop_atr=None, stop_px=None, tgt_atr=None, tgt_px=None, chand=None,
        lvlL=None, lvlS=None, exitL=None, exitS=None, hold=None, up=None, dn=None, valid=1,
        maker=False, start=None, atr_arr=None):
    t, o, h, l, c = B["t"], B["o"], B["h"], B["l"], B["c"]
    A = B["atr"] if atr_arr is None else atr_arr
    n = len(t)
    cap = int(CAP_DAYS * D1 // B["P"])
    cin = MAKER_IN if maker else COST
    cout = COST
    stop_entry = up is not None or dn is not None
    if stop_entry:
        up = np.full(n, NAN) if up is None else np.asarray(up, dtype=float)
        dn = np.full(n, NAN) if dn is None else np.asarray(dn, dtype=float)
        if start is not None:
            k0 = t < ms(start); up = up.copy(); dn = dn.copy(); up[k0] = NAN; dn[k0] = NAN
    else:
        sig = np.asarray(np.nan_to_num(np.asarray(sig, dtype=float)), dtype=float)
        sig = np.sign(sig).astype(int)
        if start is not None:
            sig = sig.copy(); sig[t < ms(start)] = 0
    trades, misses, tries = [], 0, 0
    i = 0
    while i < n - 1:
        if stop_entry:
            u, d_ = up[i], dn[i]
            if not (np.isfinite(u) or np.isfinite(d_)):
                i += 1; continue
            found = None
            for k in range(i + 1, min(n, i + 1 + int(valid))):
                hu = np.isfinite(u) and h[k] >= u
                hd = np.isfinite(d_) and l[k] <= d_
                if hu and hd:
                    found = (0, k, NAN); break
                if hu:
                    found = (1, k, max(o[k], u)); break
                if hd:
                    found = (-1, k, min(o[k], d_)); break
            if found is None or found[0] == 0:
                i += 1; continue
            s, k, px = found
            intrabar = True
            tries += 1
            if maker:
                lvl = u if s > 0 else d_
                lim = lvl - s * MK_ATR * A[i]
                fk = None
                for k2 in range(k + 1, min(n, k + 1 + MK_BARS)):
                    if (s > 0 and l[k2] <= lim) or (s < 0 and h[k2] >= lim):
                        fk = k2; px = min(o[k2], lim) if s > 0 else max(o[k2], lim); break
                if fk is None:
                    misses += 1; i = k; continue
                k = fk
            ek = k
        else:
            s = int(sig[i])
            if s == 0:
                i += 1; continue
            tries += 1
            if maker:
                lim = c[i] - s * MK_ATR * A[i]
                fk = None
                if np.isfinite(lim):
                    for k2 in range(i + 1, min(n, i + 1 + MK_BARS)):
                        if (s > 0 and l[k2] <= lim) or (s < 0 and h[k2] >= lim):
                            fk = k2; px = min(o[k2], lim) if s > 0 else max(o[k2], lim); break
                if fk is None:
                    misses += 1; i += 1; continue
                ek = fk; intrabar = True
            else:
                ek = i + 1; px = o[ek]; intrabar = False
        if stop_px is not None:
            stp0 = float(stop_px[i])
        else:
            stp0 = px - s * float(stop_atr) * A[i]
        if not (np.isfinite(stp0) and np.isfinite(px) and px > 0 and s * (px - stp0) > 0):
            i += 1; continue
        tgt = NAN
        if tgt_px is not None:
            tgt = float(tgt_px[i])
            if not (np.isfinite(tgt) and s * (tgt - px) > 0):
                i += 1; continue
        elif tgt_atr is not None:
            tgt = px + s * float(tgt_atr) * A[i]
        risk = abs(px - stp0) / px
        stp = stp0
        peak = px
        why = "OPEN"; xi = n - 1; ex = c[-1]
        for j in range(ek, n):
            if j > ek:
                peak = max(peak, h[j - 1]) if s > 0 else min(peak, l[j - 1])
                if chand is not None and np.isfinite(A[j - 1]):
                    cand = peak - s * chand * A[j - 1]
                    stp = max(stp, cand) if s > 0 else min(stp, cand)
                lv = lvlL if s > 0 else lvlS
                if lv is not None and np.isfinite(lv[j - 1]):
                    stp = max(stp, lv[j - 1]) if s > 0 else min(stp, lv[j - 1])
            fillbar = (j == ek and intrabar)
            if s > 0:
                if not fillbar and o[j] <= stp:
                    why, xi, ex = "SL", j, o[j]; break
                if l[j] <= stp:
                    why, xi, ex = "SL", j, stp; break
                if np.isfinite(tgt) and not fillbar and h[j] >= tgt:
                    why, xi, ex = "TP", j, max(o[j], tgt); break
            else:
                if not fillbar and o[j] >= stp:
                    why, xi, ex = "SL", j, o[j]; break
                if h[j] >= stp:
                    why, xi, ex = "SL", j, stp; break
                if np.isfinite(tgt) and not fillbar and l[j] <= tgt:
                    why, xi, ex = "TP", j, min(o[j], tgt); break
            xa = exitL if s > 0 else exitS
            if xa is not None and bool(xa[j]):
                why, xi, ex = "X", j, c[j]; break
            if hold is not None and (j - ek) >= int(hold):
                why, xi, ex = "TIME", j, c[j]; break
            if (j - ek) >= cap:
                why, xi, ex = "CAP", j, c[j]; break
        ret = s * (ex / px - 1.0) - cin - cout
        trades.append(dict(entry_time=int(t[ek]), exit_time=int(t[xi]), side=s, entry=float(px), stop=float(stp0),
                           exit=float(ex), R=float(ret / risk), risk=float(risk), ret=float(ret), why=why,
                           ei=int(ek), xi=int(xi), hold=int(max(1, xi - ek)), bars=B))
        i = max(xi, i + 1)
    return dict(trades=trades, misses=misses, tries=tries)

def booleans(*arrs):
    out = None
    for a in arrs:
        a = np.asarray(a, dtype=bool)
        out = a if out is None else (out | a)
    return out

# ---------------------------------------------------------------------------
# Indicator helpers on bar dicts
# ---------------------------------------------------------------------------
def fractals(B):
    h, l = B["h"], B["l"]
    n = len(h)
    fh = np.zeros(n, bool); fl = np.zeros(n, bool)
    if n > 5:
        m = slice(2, n - 2)
        fh[m] = (h[m] > h[1:n - 3]) & (h[m] > h[0:n - 4]) & (h[m] > h[3:n - 1]) & (h[m] > h[4:n])
        fl[m] = (l[m] < l[1:n - 3]) & (l[m] < l[0:n - 4]) & (l[m] < l[3:n - 1]) & (l[m] < l[4:n])
    return fh, fl

def known_level(vals, flags, n):
    """Value of the most recent fractal, known 2 bars after it (at confirmation close)."""
    a = np.full(n, NAN)
    idx = np.flatnonzero(flags)
    for j in idx:
        if j + 2 < n:
            a[j + 2] = vals[j]
    return pd.Series(a).ffill().to_numpy()

# ---------------------------------------------------------------------------
# The 30 ideas. Each returns a list of (label, sim-kwargs) runs on a bar dict.
# A = traded asset context, O = other asset context (only idea 27 uses O).
# ---------------------------------------------------------------------------
def i01(A, O):
    D = A.d; h, l = D["h"], D["l"]; r = h - l
    nr7 = r <= rmin(r, 7)
    inside = (h < sh1(h)) & (l > sh1(l))
    s = nr7 & inside
    return [(A.name, dict(B=D, up=np.where(s, h, NAN), dn=np.where(s, l, NAN), valid=3, stop_atr=2.0, chand=3.0))]

def i02(A, O):
    B = A.h4; c = B["c"]
    e20 = ema(c, 20); a20 = atr(B["h"], B["l"], c, 20)
    bu, bm, bl, _ = bb_width(c, 20, 2.0)
    inside = (bu < e20 + 1.5 * a20) & (bl > e20 - 1.5 * a20)
    sq = sh1(consec(inside)) >= 6
    e = er(c, 20) >= 0.35
    sig = np.where(sq & e & (c > bu), 1, np.where(sq & e & (c < bl), -1, 0))
    return [(A.name, dict(B=B, sig=sig, stop_atr=2.2, exitL=c < e20, exitS=c > e20))]

def i03(A, O):
    D = A.d; c = D["c"]
    ap = D["atr"] / c
    comp = prank(ap, 180) <= 0.10
    armed = rmax(comp.astype(float), 10) > 0
    hh, ll = sh1(rmax(D["h"], 10)), sh1(rmin(D["l"], 10))
    sig = np.where(armed & (c > hh), 1, np.where(armed & (c < ll), -1, 0))
    return [(A.name, dict(B=D, sig=sig, stop_atr=2.5, lvlL=rmin(D["l"], 15), lvlS=rmax(D["h"], 15)))]

def i04(A, O):
    B = A.h1; t = B["t"]
    hour = (t // H1) % 24; day = t // D1
    df = pd.DataFrame({"day": day, "hour": hour, "h": B["h"], "l": B["l"]})
    a = df[df.hour < 12].groupby("day").agg(hi=("h", "max"), lo=("l", "min"), n=("h", "size"))
    a = a[a.n == 12]
    a["ar"] = (a.hi - a.lo) / a.lo
    full = pd.DataFrame(index=np.arange(a.index.min(), a.index.max() + 1)).join(a)
    full["med"] = full["ar"].shift(1).rolling(30, min_periods=20).median()
    ok = full[(full.ar / full.med) < 0.55]
    up = np.full(len(t), NAN); dn = np.full(len(t), NAN)
    arm = hour == 12
    m = pd.Series(np.arange(len(t)))[arm]
    for i in m.to_numpy():
        dd = int(day[i])
        if dd in ok.index:
            up[i] = ok.at[dd, "hi"]; dn[i] = ok.at[dd, "lo"]
    xit = hour == 20
    return [(A.name, dict(B=B, up=up, dn=dn, valid=8, stop_atr=1.8, tgt_atr=2.8, exitL=xit, exitS=xit))]

def i05(A, O):
    B = A.h4; t = B["t"]; n = len(t)
    days = t // D1; dow = (days + 3) % 7; hour = (t // H1) % 24
    inbox = (dow == 5) | ((dow == 6) & (hour < 20))
    sig = np.zeros(n, int)
    i = 0
    while i < n:
        if not inbox[i]:
            i += 1; continue
        j = i
        while j + 1 < n and inbox[j + 1] and (t[j + 1] - t[j]) == H4:
            j += 1
        if (j - i + 1) == 11:
            hi, lo = B["h"][i:j + 1].max(), B["l"][i:j + 1].min()
            if np.isfinite(B["atr"][j]) and (hi - lo) < 1.2 * B["atr"][j]:
                k = j + 1
                while k < n and not (dow[k] == 5 and k > j + 6):
                    if B["c"][k] > hi:
                        sig[k] = 1; break
                    if B["c"][k] < lo:
                        sig[k] = -1; break
                    k += 1
        i = j + 1
    return [(A.name, dict(B=B, sig=sig, stop_atr=2.0, hold=18, chand=2.0))]

def i06(A, O):
    D = A.d; o, h, l, c = D["o"], D["h"], D["l"], D["c"]
    doji = np.abs(c - o) < 0.30 * (h - l)
    three = doji & (sh1(doji) > 0) & (shn(doji, 2) > 0)
    s50 = sma(c, 50)
    ab = (c > s50); be = (c < s50)
    allab = ab & (sh1(ab) > 0) & (shn(ab, 2) > 0)
    allbe = be & (sh1(be) > 0) & (shn(be, 2) > 0)
    up = np.where(three & allab, rmax(h, 3), NAN)
    dn = np.where(three & allbe, rmin(l, 3), NAN)
    return [(A.name, dict(B=D, up=up, dn=dn, valid=3, stop_atr=2.0, tgt_atr=3.5))]

def i07(A, O):
    B, D = A.h4, A.d; o, h, l, c = B["o"], B["h"], B["l"], B["c"]
    de = ema(D["c"], 50); slope = de - sh1(de)
    dea, sla = align(D, de, B), align(D, slope, B)
    e50 = ema(c, 50)
    cond = (c < dea) & (sla < 0) & (h >= e50) & ((h - rmin(l, 12)) >= 1.8 * B["atr"]) & (c < o) & (c < sh1(c))
    sig = np.where(cond, -1, 0)
    return [(A.name, dict(B=B, sig=sig, stop_px=rmax(h, 3) + 1.8 * B["atr"], chand=2.5))]

def i08(A, O):
    B = A.h4; h, l, c, a = B["h"], B["l"], B["c"], B["atr"]; n = len(c)
    drop = (rmax(h, 4) - c) >= 3.5 * a
    e12 = er(c, 12)
    sig = np.zeros(n, int)
    kd = -10 ** 9
    for i in range(1, n):
        if drop[i - 1]:
            kd = i - 1
        m = i - 1 - kd
        if 5 <= m <= 12 and not drop[i]:
            chl = l[kd + 1:i].min()
            if c[i - 1] > c[kd] and np.isfinite(e12[i - 1]) and e12[i - 1] <= 0.25 and c[i] < chl:
                sig[i] = -1
                kd = -10 ** 9
    return [(A.name, dict(B=B, sig=sig, stop_atr=2.0, tgt_atr=3.2))]

def i09(A, O):
    B, D = A.h4, A.d; h, l, c, a = B["h"], B["l"], B["c"], B["atr"]; n = len(c)
    dn_ = align(D, (D["c"] < sma(D["c"], 100)).astype(float), B) > 0
    fh, fl = fractals(B)
    SH = sh1(known_level(h, fh, n)); SL = sh1(known_level(l, fl, n))
    cond = dn_ & (h > SH) & ((h - SH) < 0.6 * a) & (c < SH)
    sig = np.where(cond, -1, 0)
    return [(A.name, dict(B=B, sig=sig, stop_px=h + 1.5 * a, tgt_px=SL))]

def i10(A, O):
    D = A.d; h, c = D["h"], D["c"]; n = len(c)
    e20, e50 = ema(c, 20), ema(c, 50)
    cross = (e20 < e50) & (sh1(e20) >= sh1(e50))
    sig = np.zeros(n, int); k = -10 ** 9; used = True
    for i in range(n):
        if cross[i]:
            k = i; used = False; continue
        if not used and 0 < i - k <= 15 and e20[i] < e50[i] and h[i] >= e20[i] and c[i] < e20[i]:
            sig[i] = -1; used = True
    return [(A.name, dict(B=D, sig=sig, stop_atr=2.2, exitS=c > sh1(rmax(h, 10))))]

def i11(A, O):
    D = A.d; o, h, l, c = D["o"], D["h"], D["l"], D["c"]
    cond = ((c / shn(c, 7) - 1) >= 0.20) & (rsi(c, 5) >= 88) & ((h - np.maximum(o, c)) >= 0.40 * (h - l))
    return [(A.name, dict(B=D, sig=np.where(cond, -1, 0), stop_px=h + 0.6 * D["atr"], exitS=c < ema(c, 10)))]

def i12(A, O):
    D = A.d; h, l, c = D["h"], D["l"], D["c"]
    hh, ll = sh1(rmax(h, 12)), sh1(rmin(l, 12))
    box = (hh - ll) / ll < 0.08
    below = sh1(rmin((c < sma(c, 200)).astype(float), 12)) > 0
    cond = box & below & (c < sh1(rmin(l, 30)))
    return [(A.name, dict(B=D, sig=np.where(cond, -1, 0), stop_atr=2.2, hold=14, chand=2.2))]

def i13(A, O):
    B = A.h4; c = B["c"]
    f3 = A.f.sum_n(B, 9)
    hh, ll = sh1(rmax(B["h"], 20)), sh1(rmin(B["l"], 20))
    sig = np.where((c > hh) & (f3 < 0.0002), 1, np.where((c < ll) & (f3 > -0.0001), -1, 0))
    return [(A.name, dict(B=B, sig=sig, stop_atr=2.5, chand=3.0, start=FUND_START))]

def i14(A, O):
    B, D = A.h4, A.d; c = B["c"]
    dea = align(D, ema(D["c"], 50), B)
    cond = (c > dea) & (B["l"] <= ema(c, 20)) & (rsi(c, 6) <= 30) & (A.f.last(B) <= -0.0001)
    return [(A.name, dict(B=B, sig=np.where(cond, 1, 0), stop_atr=2.0, tgt_atr=2.5, hold=12, start=FUND_START))]

def i15(A, O):
    B = A.h4; h, l, c, v, a = B["h"], B["l"], B["c"], B["v"], B["atr"]
    z = A.f.zlast(B)
    hh = sh1(rmax(h, 60))
    newhi = (h > hh) & ((h - hh) <= 0.5 * a) & (v < sh1(sma(v, 20))) & (z >= 2.2)
    armed = rmax(newhi.astype(float), 4) > 0
    cond = armed & (c < sh1(l))
    return [(A.name, dict(B=B, sig=np.where(cond, -1, 0), stop_atr=2.2, exitS=z < 0.5, start=FUND_START))]

def i16(A, O):
    B = A.h4; o, c, a = B["o"], B["c"], B["atr"]; n = len(c); F = A.f
    ic = F.idx(B["tc"]); io = F.idx(B["t"])
    fall = (o - c) >= 2.5 * a
    fall2 = fall | (sh1(fall) > 0)
    sig = np.zeros(n, int)
    for i in range(n):
        k = ic[i]
        if k > io[i] and k >= 3 and F.fv[k] <= -0.00015 and F.fv[k - 3:k].mean() >= 0.0004 and fall2[i]:
            for j in range(i + 1, min(n, i + 7)):
                if c[j] > o[j]:
                    sig[j] = 1; break
    return [(A.name, dict(B=B, sig=sig, stop_atr=2.0, tgt_atr=3.0, start=FUND_START))]

def i17(A, O):
    D = A.d; c = D["c"]
    fs = A.f.daily_sum(D)
    neg = np.where(np.isfinite(fs), fs < 0, False).astype(float)
    pos = np.where(np.isfinite(fs), fs > 0, False)
    cond = (rmin(neg, 5) > 0) & (c > sma(c, 20))
    return [(A.name, dict(B=D, sig=np.where(cond, 1, 0), stop_atr=2.2, exitL=pos & (sh1(pos) > 0), start=FUND_START))]

def i18(A, O):
    D = A.d; c = D["c"]
    fl = A.f.last(D); e30 = ema(c, 30)
    st = np.where((c > e30) & (fl <= 0.0001), 1, np.where((c < e30) & (fl >= -0.0001), -1, 0))
    return [(A.name, dict(B=D, sig=st, stop_atr=2.5, exitL=st != 1, exitS=st != -1, start=FUND_START))]

def i19(A, O):
    B = A.h4; o, h, l, c = B["o"], B["h"], B["l"], B["c"]
    ax, pdi, mdi = adx(h, l, c, 14)
    e21 = ema(c, 21)
    tL = (l <= e21) | (sh1(l) <= sh1(e21)); tS = (h >= e21) | (sh1(h) >= sh1(e21))
    L = (ax >= 28) & (pdi > mdi) & tL & (c > o) & (c > e21)
    S = (ax >= 28) & (mdi > pdi) & tS & (c < o) & (c < e21)
    return [(A.name, dict(B=B, sig=np.where(L, 1, np.where(S, -1, 0)), stop_atr=2.0, chand=2.8))]

def i20(A, O):
    B, D = A.h4, A.d; c = B["c"]
    up = align(D, (D["c"] > sma(D["c"], 100)).astype(float), B) > 0
    cond = up & (rsi(c, 2) < 10)
    return [(A.name, dict(B=B, sig=np.where(cond, 1, 0), stop_atr=2.2, exitL=c > ema(c, 10)))]

def i21(A, O):
    B = A.h4; t, o, l, c, a = B["t"], B["o"], B["l"], B["c"], B["atr"]; n = len(t)
    days = t // D1; dow = (days + 3) % 7; wk = (days + 3) // 7; hour = (t // H1) % 24
    sig = np.zeros(n, int)
    cw = None; wopen = NAN; mn = NAN; swept = False; done = False
    for i in range(n):
        if wk[i] != cw:
            cw = wk[i]; done = False; swept = False; mn = NAN
            wopen = o[i] if (dow[i] == 0 and hour[i] == 0) else NAN
        if not np.isfinite(wopen) or done:
            continue
        if dow[i] <= 1:
            mn = l[i] if not np.isfinite(mn) else min(mn, l[i])
            if np.isfinite(a[i]) and (wopen - mn) >= 1.2 * a[i]:
                swept = True
        if swept and dow[i] <= 2 and c[i] > wopen:
            sig[i] = 1; done = True
    xit = (dow == 4) & (hour == 16)
    return [(A.name, dict(B=B, sig=sig, stop_atr=1.8, exitL=xit))]

def i22(A, O):
    B = A.h4; h, l, c, a = B["h"], B["l"], B["c"], B["atr"]; n = len(c)
    r14 = rsi(c, 14); e34 = ema(c, 34)
    fh, fl = fractals(B)
    sig = np.zeros(n, int)
    SHs, SLs = [], []
    for cb in range(4, n):
        j = cb - 2
        if fh[j]:
            SHs.append(j); SHs = SHs[-3:]
            if len(SHs) == 3:
                j1, j2, j3 = SHs
                if h[j1] < h[j2] < h[j3] and r14[j1] > r14[j2] > r14[j3] and (j3 - j1) <= 60:
                    lo = l[max(0, j1 - 30):j3 + 1].min()
                    if np.isfinite(a[j3]) and (h[j3] - lo) >= 5 * a[j3]:
                        sig[cb] = -1
        if fl[j]:
            SLs.append(j); SLs = SLs[-3:]
            if len(SLs) == 3:
                j1, j2, j3 = SLs
                if l[j1] > l[j2] > l[j3] and r14[j1] < r14[j2] < r14[j3] and (j3 - j1) <= 60:
                    hi = h[max(0, j1 - 30):j3 + 1].max()
                    if np.isfinite(a[j3]) and (hi - l[j3]) >= 5 * a[j3]:
                        sig[cb] = 1
    return [(A.name, dict(B=B, sig=sig, stop_atr=2.0, exitL=c >= e34, exitS=c <= e34))]

def i23(A, O):
    D = A.d; o, h, l, c = D["o"], D["h"], D["l"], D["c"]
    cond = ((c / shn(c, 4) - 1) <= -0.16) & (rsi(c, 4) <= 15) & ((np.minimum(o, c) - l) >= 0.35 * (h - l))
    return [(A.name, dict(B=D, sig=np.where(cond, 1, 0), stop_px=l - 0.6 * D["atr"], exitL=c > ema(c, 10)))]

def i24(A, O):
    D = A.d; h, l, c, a = D["h"], D["l"], D["c"], D["atr"]; n = len(c)
    e20 = ema(c, 20)
    sig = np.zeros(n, int)
    for side in (1, -1):
        k = -10 ** 9; pb = NAN
        for i in range(1, n):
            if not (np.isfinite(e20[i]) and np.isfinite(a[i])):
                continue
            if i - k > 10:
                k = -10 ** 9; pb = NAN
            if k > -10 ** 9:
                if side * (c[i] - e20[i]) < 0:
                    k = -10 ** 9; pb = NAN
                elif np.isfinite(pb) and side * (c[i] - pb) > 0:
                    sig[i] = side if sig[i] == 0 else 0
                    k = -10 ** 9; pb = NAN; continue
                elif side * (c[i] - c[i - 1]) < 0:
                    pb = h[i] if side > 0 else l[i]
            if side * (c[i] - (e20[i] + side * 2.0 * a[i])) > 0:
                k = i; pb = NAN
    return [(A.name, dict(B=D, sig=sig, stop_atr=2.2, chand=3.5))]

def i25(BT, ET):
    b, e = joint(BT.h4, ET.h4, H4)
    r = e["c"] / b["c"]; be50 = ema(b["c"], 50); re20 = ema(r, 20)
    hh, ll = sh1(rmax(r, 20)), sh1(rmin(r, 20))
    sig = np.where((r > hh) & (b["c"] > be50), 1, np.where((r < ll) & (b["c"] < be50), -1, 0))
    return [("eth", dict(B=e, sig=sig, stop_atr=2.2, exitL=r < re20, exitS=r > re20))]

def i26(BT, ET):
    b, e = joint(BT.h4, ET.h4, H4)
    rb3 = b["c"] / shn(b["c"], 3) - 1; re3 = e["c"] / shn(e["c"], 3) - 1
    cr = rcorr(b["c"] / sh1(b["c"]) - 1, e["c"] / sh1(e["c"]) - 1, 20)
    cond = (rb3 >= 0.03) & (re3 <= 0.01) & (cr >= 0.70)
    return [("eth", dict(B=e, sig=np.where(cond, 1, 0), stop_atr=2.0, exitL=(re3 - rb3) >= 0, hold=9))]

def i27(A, O):
    a_, o_ = joint(A.h4, O.h4, H4)
    evt = (o_["c"] < sh1(rmin(o_["l"], 90))) & (a_["c"] > sh1(rmin(a_["l"], 90)))
    e20 = ema(a_["c"], 20)
    xdn = (a_["c"] < e20) & (sh1(a_["c"]) >= sh1(e20))
    n = len(evt); sig = np.zeros(n, int); last = -10 ** 9
    for i in range(n):
        if evt[i]:
            last = i
        if 0 <= i - last <= 18 and xdn[i]:
            sig[i] = -1; last = -10 ** 9
    return [(A.name, dict(B=a_, sig=sig, stop_atr=2.2, hold=18, chand=2.2))]

def i28(BT, ET):
    b, e = joint(BT.h4, ET.h4, H4)
    cr = rcorr(b["c"] / sh1(b["c"]) - 1, e["c"] / sh1(e["c"]) - 1, 30)
    rb3 = b["c"] / shn(b["c"], 3) - 1; re3 = e["c"] / shn(e["c"], 3) - 1
    lowc = cr <= 0.45; xit = cr >= 0.75
    sB = np.where(lowc & (rb3 <= -0.03) & (re3 >= -0.005), 1, 0)
    sE = np.where(lowc & (re3 <= -0.03) & (rb3 >= -0.005), 1, 0)
    return [("btc", dict(B=b, sig=sB, stop_atr=2.0, exitL=xit, hold=30)),
            ("eth", dict(B=e, sig=sE, stop_atr=2.0, exitL=xit, hold=30))]

def i29(BT, ET):
    b, e = joint(BT.d, ET.d, D1)
    r = e["c"] / b["c"]
    bu, bm, bl, _ = bb_width(r, 30, 2.2)
    sE = np.where((sh1(r) < sh1(bl)) & (r >= bl), 1, 0)
    sB = np.where((sh1(r) > sh1(bu)) & (r <= bu), 1, 0)
    return [("eth", dict(B=e, sig=sE, stop_atr=2.5, exitL=r >= bm, hold=15)),
            ("btc", dict(B=b, sig=sB, stop_atr=2.5, exitL=r <= bm, hold=15))]

def i30(BT, ET):
    b, e = joint(BT.d, ET.d, D1)
    q = (e["atr"] / e["c"]) / (b["atr"] / b["c"])
    pr = prank(q, 365, 180)
    hi, lo = pr >= 0.90, pr <= 0.20
    m3 = e["c"] / shn(e["c"], 3) - 1
    sE = np.where(hi, -np.sign(nz(m3)), 0)
    hh, ll = sh1(rmax(b["h"], 20)), sh1(rmin(b["l"], 20))
    sB = np.where(lo & (b["c"] > hh), 1, np.where(lo & (b["c"] < ll), -1, 0))
    return [("eth", dict(B=e, sig=sE, stop_atr=2.2, hold=5)),
            ("btc", dict(B=b, sig=sB, stop_atr=2.2, lvlL=rmin(b["l"], 10), lvlS=rmax(b["h"], 10)))]

# (num, name, tf, fn, kind, start) kind: 's' single asset, 'x' cross asset
IDEAS = [
    (1, "NR7 inside-bar breakout", "1D", i01, "s", None),
    (2, "BB-in-Keltner squeeze release", "4H", i02, "s", None),
    (3, "ATR%<=p10 then 10d Donchian", "1D", i03, "s", None),
    (4, "Asia-range compression -> US", "1H", i04, "s", None),
    (5, "Weekend quiet-box breakout", "4H", i05, "s", None),
    (6, "3-doji coil break", "1D", i06, "s", None),
    (7, "Failed rally into falling EMA50", "4H", i07, "s", None),
    (8, "Bear-flag channel breakdown", "4H", i08, "s", None),
    (9, "Lower-high sweep short", "4H", i09, "s", None),
    (10, "Death-cross first pullback short", "1D", i10, "s", None),
    (11, "Parabolic rejection short", "1D", i11, "s", None),
    (12, "Distribution-shelf breakdown", "1D", i12, "s", None),
    (13, "Healthy-funding Donchian", "4H", i13, "s", FUND_START),
    (14, "Neg-funding pullback long", "4H", i14, "s", FUND_START),
    (15, "Funding-z marginal-high short", "4H", i15, "s", FUND_START),
    (16, "Funding flip capitulation long", "4H", i16, "s", FUND_START),
    (17, "5d neg funding above SMA20", "1D", i17, "s", FUND_START),
    (18, "Funding carry + EMA30 trend", "1D", i18, "s", FUND_START),
    (19, "ADX pullback to EMA21", "4H", i19, "s", None),
    (20, "1D>SMA100 + 4H RSI2<10", "4H", i20, "s", None),
    (21, "Weekly-open reclaim", "4H", i21, "s", None),
    (22, "Three-push divergence reversal", "4H", i22, "s", None),
    (23, "Post-crash panic hammer", "1D", i23, "s", None),
    (24, "Keltner re-acceleration", "1D", i24, "s", None),
    (25, "ETH/BTC ratio breakout (ETH)", "4H", i25, "x", None),
    (26, "BTC-first ETH catch-up (ETH)", "4H", i26, "x", None),
    (27, "ETH-led weakness short BTC", "4H", i27, "s", None),
    (28, "Corr-breakdown laggard long", "4H", i28, "x", None),
    (29, "Ratio BB hook (oversold leg)", "1D", i29, "x", None),
    (30, "ATR%-spread regime switch", "1D", i30, "x", None),
]

def run_idea(fn, X, Y, maker, start):
    out = {"trades": [], "misses": 0, "tries": 0, "assets": set()}
    for label, kw in fn(X, Y):
        kw = dict(kw)
        B = kw.pop("B")
        st = kw.pop("start", start)
        r = sim(B, maker=maker, start=st, **kw)
        for tr in r["trades"]:
            tr["asset"] = label
        out["trades"] += r["trades"]; out["misses"] += r["misses"]; out["tries"] += r["tries"]
        out["assets"].add(label)
    out["trades"].sort(key=lambda d: (d["exit_time"], d["entry_time"]))
    return out

# ---------------------------------------------------------------------------
# Metrics / placebo / flip / correlations (basket_gate style)
# ---------------------------------------------------------------------------
def tf_of(trs):
    return osl._tframe(standardize([{k: v for k, v in d.items() if k != "bars"} for d in trs]))

def win(trs, a=None, b=None):
    lo = ms(a) if a else -10 ** 18; hi = ms(b) if b else 10 ** 18
    return [d for d in trs if lo <= d["exit_time"] < hi]

def stats(trs):
    return osl.tstats(tf_of(trs)) if trs else osl.tstats(None)

def metrics(trs):
    w = win(trs, H_START)
    st = stats(w)
    h1, h2 = stats(win(w, "2017-01-01", "2021-01-01")), stats(win(w, "2021-01-01"))
    l30 = stats(w[-30:])
    y18, y22 = stats(win(w, "2018-01-01", "2019-01-01")), stats(win(w, "2022-01-01", "2023-01-01"))
    gm = [100 * abs(d["exit"] - d["entry"]) / d["entry"] for d in w]
    return dict(n=st["tr"], win=st["win"], pf=st["pf"], avgR=st["avgR"], ret=st["ret"], dd=st["dd"],
                gross=float(np.mean(gm)) if gm else NAN, pf_h1=h1["pf"], n_h1=h1["tr"], pf_h2=h2["pf"],
                n_h2=h2["tr"], pf_l30=l30["pf"], r18=y18["ret"] if y18["tr"] else NAN,
                r22=y22["ret"] if y22["tr"] else NAN)

def path_R(B, ei, s, hold, risk):
    o, h, l, c = B["o"], B["h"], B["l"], B["c"]
    n = len(o)
    idx = np.minimum(ei[:, None] + np.arange(hold + 1)[None, :], n - 1)
    fill = o[ei]
    stp = fill * (1.0 - s * risk)
    hit = (l[idx] <= stp[:, None]) if s > 0 else (h[idx] >= stp[:, None])
    anyh = hit.any(axis=1)
    first = hit.argmax(axis=1)
    jj = idx[np.arange(len(ei)), first]
    sx = np.minimum(stp, o[jj]) if s > 0 else np.maximum(stp, o[jj])
    ex = np.where(anyh, sx, c[idx[:, -1]])
    return (s * (ex / fill - 1.0) - 2.0 * COST) / risk

def pf_of(R):
    R = np.asarray(R, float); R = R[np.isfinite(R)]
    g, ls = R[R > 0].sum(), -R[R < 0].sum()
    return g / ls if ls > 0 else (np.inf if g > 0 else NAN)

def placebo_flip(trs, real_pf, start, seed):
    w = win(trs, H_START)
    if not w or not np.isfinite(real_pf):
        return NAN, NAN
    rng = np.random.default_rng(seed)
    G = np.zeros(N_PLACEBO); L = np.zeros(N_PLACEBO); fl = []
    for d in w:
        B = d["bars"]; n = len(B["o"]); hold = int(d["hold"])
        i0 = int(np.searchsorted(B["t"], ms(start or H_START)))
        hi = max(i0 + 1, n - hold - 1)
        ei = rng.integers(i0, hi, size=N_PLACEBO)
        R = path_R(B, ei, d["side"], hold, d["risk"])
        R = np.where(np.isfinite(R), R, 0.0)
        G += np.where(R > 0, R, 0.0); L += np.where(R < 0, -R, 0.0)
        fl.append(path_R(B, np.array([d["ei"]]), -d["side"], hold, d["risk"])[0])
    pfs = np.where(L > 0, G / np.where(L > 0, L, 1), np.inf)
    return float(100.0 * np.mean(real_pf > pfs)), float(pf_of(fl))

def daily_R(trs, weight=1.0):
    rows = [(d["exit_time"] // D1, weight * d["R"]) for d in win(trs, H_START) if np.isfinite(d["R"])]
    if not rows:
        return pd.Series(dtype=float)
    return pd.DataFrame(rows, columns=["day", "R"]).groupby("day")["R"].sum()

def eng_daily(trs, weight=1.0):
    rows = [(int(t["exit_time"]) // D1, weight * float(t["R"])) for t in trs
            if int(t["exit_time"]) >= ms(H_START) and np.isfinite(t.get("R", NAN))]
    if not rows:
        return pd.Series(dtype=float)
    return pd.DataFrame(rows, columns=["day", "R"]).groupby("day")["R"].sum()

def dcorr(a, b):
    if len(a) == 0 or len(b) == 0:
        return NAN
    idx = a.index.union(b.index)
    x, y = a.reindex(idx).fillna(0.0), b.reindex(idx).fillna(0.0)
    if x.std() <= 1e-12 or y.std() <= 1e-12:
        return NAN
    return float(x.corr(y))

# ---------------------------------------------------------------------------
# Live basket: maker reprice of oslib.engines trades on 1h bars
# ---------------------------------------------------------------------------
def basket_curve(events, start=H_START):
    """Same math as oslib.overlay: pnl = R * min(live risk, stop distance), compounded by exit time."""
    t0 = ms(start)
    by = {}
    for ts, pnl in events:
        if ts >= t0:
            by[ts] = by.get(ts, 0.0) + pnl
    eq = 1.0; peak = 1.0; mdd = 0.0
    for ts in sorted(by):
        eq *= (1.0 + by[ts]); peak = max(peak, eq); mdd = min(mdd, eq / peak - 1.0)
    ret, dd = 100 * (eq - 1.0), 100 * mdd
    return dict(ret=ret, maxDD=dd, MAR=(ret / abs(dd) if dd < 0 else NAN), n=len(events))

def maker_reprice(eng, h1df):
    t = h1df["time"].to_numpy(dtype="int64")
    o, h, l, c = (h1df[k].to_numpy(dtype=float) for k in ("open", "high", "low", "close"))
    a1 = atr(h, l, c, 14)
    n = len(t)
    base_ev, mk_ev, per = [], [], {}
    for nm in LIVE_ENGINES:
        trs = eng.get(nm, [])
        lr = LIVE_RISK.get(nm, RISK)
        be, me = [], []
        miss = 0; tot = 0; unpriced = 0
        for tt in standardize(trs, src=nm):
            if tt["exit_time"] < ms(H_START):
                continue
            R, rk = tt["R"], tt["risk"]
            if not (np.isfinite(R) and np.isfinite(rk) and rk > 0):
                continue
            tot += 1
            be.append((tt["exit_time"], R * min(lr, rk)))
            s = int(tt["side"]); ent = tt["entry"]; stp = tt["stop"]
            if not (np.isfinite(ent) and ent > 0 and s != 0):
                unpriced += 1; me.append((tt["exit_time"], R * min(lr, rk))); continue
            if not np.isfinite(stp):
                stp = ent - s * rk * ent
            ret = R * rk  # net price return (run()-style engines store ret at 1% equity, so use R*risk)
            gross = ret + 2 * COST
            xeff = ent * (1.0 + s * gross)
            ei = int(np.searchsorted(t, tt["entry_time"]))
            if ei <= 0 or ei >= n:
                unpriced += 1; me.append((tt["exit_time"], R * min(lr, rk))); continue
            lim = c[ei - 1] - s * MK_ATR * a1[ei - 1]
            fill = None
            for k in range(ei, min(n, ei + MK_BARS)):
                if t[k] > tt["exit_time"]:
                    break
                if (s > 0 and l[k] <= lim) or (s < 0 and h[k] >= lim):
                    fill = min(o[k], lim) if s > 0 else max(o[k], lim); break
            if fill is None or not (s * (fill - stp) > 0):
                miss += 1; continue
            rk2 = abs(fill - stp) / fill
            ret2 = s * (xeff / fill - 1.0) - MAKER_IN - COST
            me.append((tt["exit_time"], (ret2 / rk2) * min(lr, rk2)))
        base_ev += be; mk_ev += me
        per[nm] = dict(base=basket_curve(be), maker=basket_curve(me), n=tot, missed=miss, unpriced=unpriced)
    return basket_curve(base_ev), basket_curve(mk_ev), per

# ---------------------------------------------------------------------------
# Data (Colab) / synthetic (smoke)
# ---------------------------------------------------------------------------
def synth(seed, start="2019-01-01", n=30000, base=None, px0=10000.0):
    rng = np.random.default_rng(seed)
    t0 = ms(start)
    t = t0 + np.arange(n, dtype=np.int64) * H1
    vol = 0.006 * np.exp(np.cumsum(rng.normal(0, 0.02, n)) * 0.3)
    vol = np.clip(vol, 0.002, 0.03)
    z = rng.standard_t(4, n) * 0.7
    if base is not None:
        z = 0.8 * base + 0.6 * z
    r = vol * z + rng.normal(0.00002, 0.0005, n)
    jumps = rng.random(n) < 0.002
    r[jumps] += rng.normal(0, 0.05, jumps.sum())
    close = px0 * np.exp(np.cumsum(r))
    open_ = np.r_[close[0], close[:-1]]
    high = np.maximum(open_, close) * (1 + np.abs(rng.normal(0, 0.003, n)))
    low = np.minimum(open_, close) * (1 - np.abs(rng.normal(0, 0.003, n)))
    v = rng.uniform(100, 1000, n) * (1 + 5 * np.abs(r) / 0.01)
    df = pd.DataFrame({"time": t, "open": open_, "high": high, "low": low, "close": close, "volume": v})
    return df, z

def synth_fund(h1, seed):
    rng = np.random.default_rng(seed)
    t = h1["time"].to_numpy()[::8]
    f = 0.0001 + rng.normal(0, 0.0002, len(t))
    spikes = rng.random(len(t)) < 0.03
    f[spikes] = rng.normal(0, 0.0008, spikes.sum())
    return pd.DataFrame({"time": t, "funding": f})

def main(smoke=False):
    if smoke:
        print("SMOKE MODE: synthetic data only (no real backtest).", flush=True)
        b1, zb = synth(1)
        e1, _ = synth(2, base=zb, px0=500.0)
        bf, ef = synth_fund(b1, 3), synth_fund(e1, 4)
        global N_PLACEBO
        N_PLACEBO = 20
    else:
        b1, e1 = load("btc", "1h"), load("eth", "1h")
        bf, ef = funding("btc", "binance"), funding("eth", "binance")
    BT, ET = Ctx("btc", b1, bf), Ctx("eth", e1, ef)
    print(f"Data ready ({time.time()-T0:.0f}s). Building live engines (X7 on via funding) ...", flush=True)
    engB = engines(b1, fund=bf)
    engE = engines(e1, fund=ef)
    k8d = eng_daily(engB["K8"], 1.0)
    parts = [eng_daily(engB[nm], LIVE_RISK.get(nm, RISK) / RISK) for nm in LIVE_ENGINES if nm in engB]
    parts = [p for p in parts if len(p)]
    bask = pd.concat(parts, axis=1).fillna(0.0).sum(axis=1) if parts else pd.Series(dtype=float)
    print(f"Engines ready ({time.time()-T0:.0f}s). Running 30 ideas ...", flush=True)

    rows = []
    for num, name, tfn, fn, kind, start in IDEAS:
        t_i = time.time()
        try:
            cross = kind == "x"
            tk = run_idea(fn, BT, ET, False, start)
            mk = run_idea(fn, BT, ET, True, start)
            m = metrics(tk["trades"])
            plc, flp = placebo_flip(tk["trades"], m["pf"], start, 20261122 + num)
            if cross:
                eth_pf, eth_n = NAN, 0
            else:
                te = run_idea(fn, ET, BT, False, start)
                me_ = metrics(te["trades"]); eth_pf, eth_n = me_["pf"], me_["n"]
            dR = daily_R(tk["trades"])
            ck, cb = dcorr(dR, k8d), dcorr(dR, bask)
            mm = metrics(mk["trades"])
            fails = []
            if not (np.isfinite(m["pf_h1"]) and m["pf_h1"] > 1.3):
                fails.append(f"PF_17_20={f1(m['pf_h1'])}")
            if not (np.isfinite(m["pf_h2"]) and m["pf_h2"] > 1.3):
                fails.append(f"PF_21_26={f1(m['pf_h2'])}")
            if m["n"] < 30:
                fails.append(f"n={m['n']}")
            if not (np.isfinite(plc) and plc >= 90):
                fails.append(f"placebo={f1(plc, 0)}")
            if not (np.isfinite(flp) and flp < 1.0):
                fails.append(f"flipPF={f1(flp)}")
            if not cross and not (np.isfinite(eth_pf) and eth_pf > 1.0):
                fails.append(f"ETH_PF={f1(eth_pf)}")
            if not (np.isfinite(cb) and cb < 0.3):
                fails.append(f"corrBasket={f1(cb)}")
            half_only = bool(fails) and all(x.startswith("PF_17_20") or x.startswith("PF_21_26") for x in fails)
            divers = (half_only and np.isfinite(m["pf"]) and m["pf"] > 1.15 and np.isfinite(cb) and cb < 0.1
                      and np.isfinite(m["r18"]) and m["r18"] > 0 and np.isfinite(m["r22"]) and m["r22"] > 0)
            traded = "+".join(sorted(a.upper() for a in tk["assets"]))
            rows.append(dict(idea=num, name=name, tf=tfn, traded=traded, n=m["n"], win=m["win"], PF=m["pf"],
                             avgR=m["avgR"], ret=m["ret"], maxDD=m["dd"], gross_pct=m["gross"],
                             PF_17_20=m["pf_h1"], n_17_20=m["n_h1"], PF_21_26=m["pf_h2"], n_21_26=m["n_h2"],
                             PF_last30=m["pf_l30"], placebo=plc, flipPF=flp,
                             ETH_PF=("n/a" if cross else eth_pf), ETH_n=("n/a" if cross else eth_n),
                             corr_K8=ck, corr_basket=cb, ret_2018=m["r18"], ret_2022=m["r22"],
                             n_maker=mm["n"], PF_maker=mm["pf"], ret_maker=mm["ret"],
                             maker_missed=mk["misses"], gate="PASS" if not fails else "FAIL",
                             fails="; ".join(fails), diversifier=bool(divers)))
            print(f"  #{num:2d} {name:34s} n {m['n']:4d}  PF {f1(m['pf'])}  ret {f1(m['ret'],1)}%  "
                  f"plc {f1(plc,0)}  flip {f1(flp)}  ETH {f1(eth_pf) if not cross else 'n/a'}  "
                  f"cB {f1(cb)}  maker n {mm['n']} PF {f1(mm['pf'])}  "
                  f"{'PASS' if not fails else 'FAIL'}  ({time.time()-t_i:.0f}s)", flush=True)
        except Exception as ex:
            print(f"  #{num:2d} {name:34s} ERROR {type(ex).__name__}: {ex}", flush=True)
            traceback.print_exc(limit=2)
            rows.append(dict(idea=num, name=name, tf=tfn, gate="ERROR", fails=f"{type(ex).__name__}: {ex}"))

    R = pd.DataFrame(rows)
    fmt_cols = {"win": 1, "PF": 2, "avgR": 3, "ret": 1, "maxDD": 1, "gross_pct": 2, "PF_17_20": 2, "PF_21_26": 2,
                "PF_last30": 2, "placebo": 0, "flipPF": 2, "corr_K8": 2, "corr_basket": 2, "ret_2018": 1,
                "ret_2022": 1, "PF_maker": 2, "ret_maker": 1}
    show = R.copy()
    for k, nd in fmt_cols.items():
        if k in show.columns:
            show[k] = show[k].map(lambda x, nd=nd: f1(x, nd) if isinstance(x, (float, int, np.floating, np.integer)) else x)
    if "ETH_PF" in show.columns:
        show["ETH_PF"] = show["ETH_PF"].map(lambda x: f1(x) if isinstance(x, (float, np.floating)) else x)
    c1 = [k for k in ["idea", "name", "tf", "traded", "n", "win", "PF", "avgR", "ret", "maxDD", "gross_pct",
                      "PF_17_20", "n_17_20", "PF_21_26", "n_21_26", "PF_last30"] if k in show.columns]
    c2 = [k for k in ["idea", "placebo", "flipPF", "ETH_PF", "ETH_n", "corr_K8", "corr_basket", "ret_2018",
                      "ret_2022", "n_maker", "PF_maker", "ret_maker", "maker_missed", "gate"] if k in show.columns]
    print("\n=== BATCH16 IDEAS - TAKER (2017+, 1% risk, 0.12%/side; funding ideas 2019-10+) ===", flush=True)
    print(show[c1].to_string(index=False), flush=True)
    print("\n=== BATCH16 IDEAS - TESTS + MAKER (entry 0.02% limit -/+0.20 ATR, 3 bars; exit 0.12%) ===", flush=True)
    print(show[c2].to_string(index=False), flush=True)
    print("\n=== GATES (PF>1.3 both halves, n>=30, placebo>=90, flipped<1, ETH PF>1.0, corr basket<0.3) ===", flush=True)
    for r in rows:
        if r.get("gate") == "PASS":
            print(f"  PASS  #{r['idea']:2d} {r['name']}", flush=True)
    for r in rows:
        if r.get("gate") != "PASS":
            print(f"  {r.get('gate','FAIL'):5s} #{r['idea']:2d} {r['name']} -> {r.get('fails','')}", flush=True)
    print("\n=== DIVERSIFIER candidates (fail only PF-halves, PF>1.15, corr basket<0.1, 2018>0 and 2022>0) ===", flush=True)
    dv = [r for r in rows if r.get("diversifier")]
    if not dv:
        print("  none", flush=True)
    for r in dv:
        print(f"  #{r['idea']:2d} {r['name']}: PF {f1(r['PF'])}, corr basket {f1(r['corr_basket'])}, "
              f"2018 {f1(r['ret_2018'],1)}%, 2022 {f1(r['ret_2022'],1)}%, fails {r['fails']}", flush=True)

    print("\n=== LIVE BASKET: MAKER ENTRY (limit -/+0.20 ATR14 1h, next 3 1h bars, 0.02% in / 0.12% out) vs TAKER ===", flush=True)
    brows = []
    for lab, eng, h1df in (("BTC", engB, b1), ("ETH", engE, e1)):
        try:
            base, mkr, per = maker_reprice(eng, h1df)
            chk = overlay(eng, 1.0)["baseline"]
            print(f"  {lab}: check vs oslib.overlay baseline ret {f1(chk['ret'],1)}% / maxDD {f1(chk['maxDD'],1)}% "
                  f"(this script {f1(base['ret'],1)}% / {f1(base['maxDD'],1)}%)", flush=True)
            print(f"  {lab:3s} {'engine':6s} {'n':>5s} {'missed%':>8s} {'ret_tkr%':>11s} {'DD_tkr%':>8s} {'MAR_tkr':>8s} "
                  f"{'ret_mkr%':>11s} {'DD_mkr%':>8s} {'MAR_mkr':>8s}", flush=True)
            tn = tm = 0
            for nm in LIVE_ENGINES:
                p = per[nm]; tn += p["n"]; tm += p["missed"]
                mp = 100.0 * p["missed"] / p["n"] if p["n"] else NAN
                print(f"  {lab:3s} {nm:6s} {p['n']:5d} {f1(mp,1):>8s} {f1(p['base']['ret'],1):>11s} "
                      f"{f1(p['base']['maxDD'],1):>8s} {f1(p['base']['MAR']):>8s} {f1(p['maker']['ret'],1):>11s} "
                      f"{f1(p['maker']['maxDD'],1):>8s} {f1(p['maker']['MAR']):>8s}", flush=True)
                brows.append(dict(asset=lab, engine=nm, n=p["n"], missed_pct=mp, unpriced=p["unpriced"],
                                  ret_taker=p["base"]["ret"], dd_taker=p["base"]["maxDD"], mar_taker=p["base"]["MAR"],
                                  ret_maker=p["maker"]["ret"], dd_maker=p["maker"]["maxDD"], mar_maker=p["maker"]["MAR"]))
            mpt = 100.0 * tm / tn if tn else NAN
            print(f"  {lab:3s} {'TOTAL':6s} {tn:5d} {f1(mpt,1):>8s} {f1(base['ret'],1):>11s} {f1(base['maxDD'],1):>8s} "
                  f"{f1(base['MAR']):>8s} {f1(mkr['ret'],1):>11s} {f1(mkr['maxDD'],1):>8s} {f1(mkr['MAR']):>8s}", flush=True)
            brows.append(dict(asset=lab, engine="TOTAL", n=tn, missed_pct=mpt, ret_taker=base["ret"],
                              dd_taker=base["maxDD"], mar_taker=base["MAR"], ret_maker=mkr["ret"],
                              dd_maker=mkr["maxDD"], mar_maker=mkr["MAR"]))
        except Exception as ex:
            print(f"  {lab} basket maker ERROR {type(ex).__name__}: {ex}", flush=True)
            traceback.print_exc(limit=2)

    out_dir = Path("/content") if Path("/content").exists() else Path(".")
    out = out_dir / ("batch16_smoke.csv" if smoke else "batch16.csv")
    R.to_csv(out, index=False)
    out2 = out_dir / ("batch16_basket_maker_smoke.csv" if smoke else "batch16_basket_maker.csv")
    pd.DataFrame(brows).to_csv(out2, index=False)
    print(f"\nSaved {out} ({len(R)} rows) and {out2}. Total {time.time()-T0:.0f}s", flush=True)

if __name__ == "__main__":
    _smoke = ("--smoke" in sys.argv) or (not in_colab() and os.environ.get("OSLIB_ALLOW_REAL") != "1")
    main(smoke=_smoke)
