# ===== batch17.py - Batch 17: 14 price/volume/calendar continuation ideas through the KEEP gauntlet =====
# Colab:  !wget -q -O batch17.py https://osom-boba.pages.dev/colab/batch17.py
#         %run batch17.py
# Box (synthetic smoke only):  python3 batch17.py --smoke
#
# Conventions (same as basket_gate.py / wf_overlay.py):
#   hosted oslib only, COST 0.12%/side, 1% risk per trade, BTC headline 2017+, ETH as the gate asset.
#   Signals on CLOSED bars (daily = UTC days from 1h, weekly = Monday 00:00 UTC weeks, 4h = UTC 4h grid),
#   fill at the next bar's open. Stops are checked on every 1h bar inside the trade and always win over
#   any close-based exit on the same bar. Close-based exits (trail / cap / calendar) fill at that bar close.
#   One position per idea at a time. Stats by exit time: halves 2017-20 / 2021-26, 2018, 2022, last 30 trades.
#   Placebo = 100 random-entry runs keeping each trade's side, hold (1h bars) and stop distance (basket_gate).
#   Flipped = same entries / holds / stop distances with the side reversed (basket_gate).
#   Corr = daily-R correlation vs K8 and vs the full live basket (oslib.engines with Binance funding, X7 on),
#   basket daily R weighted by LIVE_RISK / RISK.
#   KEEP: PF>1.3 both halves, n>=30, placebo>=90, flipped<1, ETH PF>1.0 (n/a for the pair), corr basket<0.3.
#   DIVERSIFIER: PF>1.15, corr basket<0.1, 2018 ret>0 and 2022 ret>0.
# Idea 4 (turn-of-month) is skipped: already tested in cal1.
import os, sys, time, traceback, subprocess
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-b17/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
from oslib import (load, funding, engines, overlay, standardize, atr, sma, true_range, resample_ohlcv,
                   synthetic_1h, in_colab, tstats, _tframe, _window, fmt,
                   COST, RISK, LIVE_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{oslib.__version__} | cost {100*COST:.2f}%/side | risk {100*RISK:.1f}%", flush=True)

LIVE = ["K8", "C1", "C2", "COCO", "B1G", "S5", "V7", "R0", "MOM30", "D34"]
W1 = 7 * D1
MON_OFF = 4 * D1          # 1970-01-05 00:00 UTC was a Monday
N_PLACEBO = 100

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

def f1(x, nd=1):
    try:
        return "-" if x is None or not np.isfinite(x) else f"{x:.{nd}f}"
    except Exception:
        return "-"

# ---------------------------------------------------------------------------
# Bars
# ---------------------------------------------------------------------------
class Base:
    def __init__(self, df):
        self.df = df
        self.t = df["time"].to_numpy(np.int64)
        self.o = df["open"].to_numpy(float)
        self.h = df["high"].to_numpy(float)
        self.l = df["low"].to_numpy(float)
        self.c = df["close"].to_numpy(float)
        self.v = df["volume"].to_numpy(float) if "volume" in df.columns else np.zeros(len(df))
        self.n = len(self.t)

def htf(B, period, offset=0):
    """Higher-timeframe bars from 1h with 1h index ranges. Drops the last bar if incomplete."""
    g = (B.t - offset) // period
    _, i0 = np.unique(g, return_index=True)
    i1 = np.r_[i0[1:] - 1, B.n - 1]
    X = pd.DataFrame({
        "time": g[i0] * period + offset,
        "open": B.o[i0], "close": B.c[i1],
        "high": np.maximum.reduceat(B.h, i0), "low": np.minimum.reduceat(B.l, i0),
        "volume": np.add.reduceat(B.v, i0), "i0": i0, "i1": i1})
    if len(X) and B.t[-1] + H1 < X["time"].iloc[-1] + period:
        X = X.iloc[:-1].reset_index(drop=True)
    return X

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

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

def clv(X):
    rng = (X["high"] - X["low"]).to_numpy(float)
    with np.errstate(invalid="ignore", divide="ignore"):
        return np.where(rng > 0, (X["close"].to_numpy(float) - X["low"].to_numpy(float)) / rng, np.nan)

def hlc(X):
    return X["high"].to_numpy(float), X["low"].to_numpy(float), X["close"].to_numpy(float)

# ---------------------------------------------------------------------------
# Generic single-position simulator on HTF signals, stops walked on 1h bars
# ---------------------------------------------------------------------------
def run_htf(B, X, side, sig, stop_px=None, stop_dist=None, exit_cond=None, cap=None, time_exit=None, name=""):
    """sig[k] True at close of HTF bar k -> fill at open of bar k+1.
    stop_px[k]: absolute stop price, or stop_dist[k]: distance from the fill (price units).
    exit_cond[j] / time_exit[j]: exit at close of bar j. cap: max HTF bars held (fill bar = 1)."""
    nX = len(X)
    i0 = X["i0"].to_numpy(int); i1 = X["i1"].to_numpy(int)
    sig = np.asarray(sig, bool)
    ex = np.zeros(nX, bool) if exit_cond is None else np.nan_to_num(np.asarray(exit_cond, float), nan=0).astype(bool)
    te = np.zeros(nX, bool) if time_exit is None else np.asarray(time_exit, bool)
    trades = []
    free = 0
    for k in range(nX - 1):
        if not sig[k] or k < free:
            continue
        a = i0[k + 1]
        fill = float(B.o[a])
        if stop_px is not None and np.isfinite(stop_px[k]):
            stp = float(stop_px[k])
        elif stop_dist is not None and np.isfinite(stop_dist[k]) and stop_dist[k] > 0:
            stp = fill - side * float(stop_dist[k])
        else:
            continue
        if not (np.isfinite(fill) and fill > 0 and side * (fill - stp) > 0):
            continue
        risk = abs(fill - stp) / fill
        xi, xpx, why, jx = B.n - 1, float(B.c[-1]), "OPEN", nX - 1
        for j in range(k + 1, nX):
            s0, s1 = i0[j], i1[j] + 1
            hit = np.flatnonzero(B.l[s0:s1] <= stp) if side > 0 else np.flatnonzero(B.h[s0:s1] >= stp)
            if len(hit):
                q = s0 + int(hit[0])
                xi = q; xpx = float(min(stp, B.o[q]) if side > 0 else max(stp, B.o[q])); why = "SL"; jx = j
                break
            held = j - k
            if te[j] or ex[j] or (cap is not None and held >= cap):
                xi = i1[j]; xpx = float(B.c[i1[j]]); jx = j
                why = "TIME" if te[j] else ("TRAIL" if ex[j] else "CAP")
                break
        ret = side * (xpx / fill - 1.0) - 2 * COST
        trades.append(dict(entry_time=int(B.t[a]), exit_time=int(B.t[xi]), side=int(side), entry=fill, stop=stp,
                           exit=xpx, risk=risk, ret=ret, R=ret / risk, why=why, src=name,
                           ei=int(a), xi=int(xi), gross=100.0 * abs(xpx / fill - 1.0)))
        free = jx
    return trades

# ---------------------------------------------------------------------------
# Ideas (single asset). Each returns trades.
# ---------------------------------------------------------------------------
def i01(B):
    X = htf(B, D1); h, l, c = hlc(X); a14 = atr(h, l, c, 14)
    ll20 = prior_min(l, 20)
    sig = (l < ll20) & (c > ll20)
    return run_htf(B, X, 1, sig, stop_px=l - 0.25 * a14, exit_cond=c < prior_min(l, 3), cap=30, name="I01")

def i02(B):
    W = htf(B, W1, MON_OFF); D = htf(B, D1)
    wh, wl, wc = hlc(W); dh, dl, dc = hlc(D); da14 = atr(dh, dl, dc, 14)
    wend = W["time"].to_numpy(np.int64) + W1
    jd = np.searchsorted(D["time"].to_numpy(np.int64), wend, side="left") - 1     # last daily bar of each week
    datr = np.where(jd >= 0, da14[np.clip(jd, 0, len(da14) - 1)], np.nan)
    ll10 = prior_min(wl, 10)
    sig = (wl < ll10) & (wc > ll10)
    return run_htf(B, W, 1, sig, stop_px=wl - 1.0 * datr, exit_cond=wc < prior_min(wl, 4), cap=15, name="I02")

def i03(B):
    X = htf(B, D1); h, l, c = hlc(X); o = X["open"].to_numpy(float)
    a20 = atr(h, l, c, 20); tr = true_range(h, l, c)
    sig = (tr >= 2.0 * np.r_[np.nan, a20[:-1]]) & (clv(X) >= 0.85) & (c > o)
    return run_htf(B, X, 1, sig, stop_px=c - 2.0 * a20, exit_cond=c < prior_min(l, 3), cap=15, name="I03")

def i05(B):
    X = htf(B, D1); h, l, c = hlc(X); o = X["open"].to_numpy(float); v = X["volume"].to_numpy(float)
    a20 = atr(h, l, c, 20)
    vs = pd.Series(v).rolling(20, min_periods=20).mean().shift(1).to_numpy()
    sig = (vs > 0) & (v >= 2.5 * vs) & (c > o) & (clv(X) >= 0.70)
    return run_htf(B, X, 1, sig, stop_px=c - 2.0 * a20, exit_cond=c < prior_min(l, 3), cap=15, name="I05")

def i06(B):
    X = htf(B, D1); h, l, c = hlc(X); a14 = atr(h, l, c, 14)
    hh20 = prior_max(h, 20)
    sig = (h > hh20) & (c < hh20)
    return run_htf(B, X, -1, sig, stop_px=h + 0.25 * a14, exit_cond=c > prior_max(h, 3), cap=30, name="I06")

def i07(B):
    X = htf(B, D1); h, l, c = hlc(X); a14 = atr(h, l, c, 14)
    new_low = l < prior_min(l, 59)          # a 60-day low (lowest of this bar + prior 59)
    hh30 = prior_max(h, 30)
    sig = np.zeros(len(X), bool)
    last_low = -10 ** 9; fired = True
    for i in range(len(X)):
        if new_low[i]:
            last_low = i; fired = False
        if (not fired) and (i - last_low) < 60 and np.isfinite(hh30[i]) and c[i] > hh30[i]:
            sig[i] = True; fired = True
    return run_htf(B, X, 1, sig, stop_dist=2.5 * a14, exit_cond=c < prior_min(l, 5), cap=45, name="I07")

def i08(B):
    W = htf(B, W1, MON_OFF); wh, wl, wc = hlc(W)
    sig = wc > prior_max(wh, 10)
    ll5 = pd.Series(wl).rolling(5, min_periods=5).min().to_numpy()   # 5 weeks before the entry week
    return run_htf(B, W, 1, sig, stop_px=ll5, exit_cond=wc < prior_min(wl, 4), cap=None, name="I08")

def i09(B):
    X = htf(B, D1); h, l, c = hlc(X); o = X["open"].to_numpy(float); a14 = atr(h, l, c, 14)
    hc20_prev = pd.Series(c).rolling(20, min_periods=20).max().shift(1).to_numpy()  # max close i-20..i-1
    prev_c = np.r_[np.nan, c[:-1]]
    sig = (prev_c >= hc20_prev) & (c < o) & (c > prior_min(l, 10))
    return run_htf(B, X, 1, sig, stop_px=l - 0.5 * a14, exit_cond=c < prior_min(l, 3), cap=15, name="I09")

def i10(B):
    X = htf(B, D1); h, l, c = hlc(X); a14 = atr(h, l, c, 14)
    up = np.r_[False, c[1:] > c[:-1]]
    streak = np.zeros(len(c), int)
    for i in range(1, len(c)):
        streak[i] = streak[i - 1] + 1 if up[i] else 0
    sig = streak == 6
    return run_htf(B, X, 1, sig, stop_dist=2.5 * a14, exit_cond=c < prior_min(l, 3), cap=12, name="I10")

def i12(B):
    X = htf(B, D1); h, l, c = hlc(X); o = X["open"].to_numpy(float); a14 = atr(h, l, c, 14)
    ts = pd.to_datetime(X["time"].to_numpy(np.int64), unit="ms", utc=True)
    dom = ts.day.to_numpy(); mon = ts.month.to_numpy()
    sig = np.zeros(len(X), bool)
    for i in range(6, len(X)):
        if dom[i] == 7 and dom[i - 6] == 1 and mon[i] == mon[i - 6] and o[i - 6] > 0:
            sig[i] = (c[i] / o[i - 6] - 1.0) >= 0.10
    return run_htf(B, X, 1, sig, stop_dist=3.0 * a14, time_exit=np.asarray(ts.is_month_end), cap=None, name="I12")

def i13(B):
    X = htf(B, D1); h, l, c = hlc(X)
    ath_prev = np.r_[np.nan, np.maximum.accumulate(c)[:-1]]     # running max close incl. all history, to i-1
    fresh = np.r_[False, c[1:] > ath_prev[1:]]
    last_fresh = -10 ** 9; since = np.full(len(c), 10 ** 9)
    for i in range(len(c)):
        since[i] = i - last_fresh          # days since the latest fresh ATH close before today
        if fresh[i]:
            last_fresh = i
    sig = (since >= 1) & (since <= 45) & (~fresh) & (l <= ath_prev * 1.02) & (c >= ath_prev * 0.98)
    return run_htf(B, X, 1, sig, stop_px=ath_prev * 0.94, exit_cond=c < prior_min(l, 3), cap=30, name="I13")

def i14(B):
    X = htf(B, D1); h, l, c = hlc(X); o = X["open"].to_numpy(float); a14 = atr(h, l, c, 14)
    dow = pd.to_datetime(X["time"].to_numpy(np.int64), unit="ms", utc=True).dayofweek.to_numpy()
    sig = np.zeros(len(X), bool)
    for i in range(3, len(X)):
        if dow[i] == 0 and dow[i - 3] == 4 and X["time"].iloc[i] - X["time"].iloc[i - 3] == 3 * D1:
            sig[i] = (c[i] >= o[i] * 1.02) and (c[i] > c[i - 3])
    return run_htf(B, X, 1, sig, stop_dist=2.0 * a14, time_exit=(dow == 4), cap=7, name="I14")

def i15(B):
    X = htf(B, H4); h, l, c = hlc(X); o = X["open"].to_numpy(float)
    a50 = atr(h, l, c, 50); tr = true_range(h, l, c)
    sig = (tr >= 2.5 * np.r_[np.nan, a50[:-1]]) & (c > o) & (clv(X) >= 0.80)
    return run_htf(B, X, 1, sig, stop_dist=1.5 * a50, exit_cond=c < prior_min(l, 6), cap=12, name="I15")

# ---------------------------------------------------------------------------
# Idea 11: ETH/BTC ratio momentum pair (long ETH + short BTC, equal notional)
# ---------------------------------------------------------------------------
class Pair:
    def __init__(self, Be, Bb):
        m = pd.merge(Be.df[["time", "open", "close"]], Bb.df[["time", "open", "close"]], on="time",
                     suffixes=("_e", "_b")).sort_values("time").reset_index(drop=True)
        self.t = m["time"].to_numpy(np.int64)
        self.eo = m["open_e"].to_numpy(float); self.ec = m["close_e"].to_numpy(float)
        self.bo = m["open_b"].to_numpy(float); self.bc = m["close_b"].to_numpy(float)
        self.r = self.ec / self.bc
        self.n = len(self.t)

def i11(Be, Bb):
    P = Pair(Be, Bb)
    # daily ratio bars from the 1h close ratio
    g = P.t // D1
    _, i0 = np.unique(g, return_index=True)
    i1 = np.r_[i0[1:] - 1, P.n - 1]
    if len(i0) and P.t[-1] + H1 < g[i0[-1]] * D1 + D1:
        i0, i1 = i0[:-1], i1[:-1]
    rc = P.r[i1]; rh = np.maximum.reduceat(P.r, i0)[:len(i0)]; rl = np.minimum.reduceat(P.r, i0)[:len(i0)]
    ra14 = atr(rh, rl, rc, 14)
    s30 = sma(rc, 30); s10 = sma(rc, 10)
    cross = np.r_[False, (rc[1:] > s30[1:]) & (rc[:-1] <= s30[:-1])]
    r20 = np.r_[np.full(20, np.nan), rc[20:] / rc[:-20] - 1.0]
    sig = cross & (r20 >= 0.03)
    stop_r = rc - 1.5 * ra14
    ex = rc < s10
    trades = []; free = 0; nX = len(i0)
    for k in range(nX - 1):
        if not sig[k] or k < free or not np.isfinite(stop_r[k]):
            continue
        a = i0[k + 1]
        e0, b0 = P.eo[a], P.bo[a]
        rf = e0 / b0; stp = stop_r[k]
        if not (rf > stp > 0):
            continue
        risk = (rf - stp) / rf
        xi, why, jx = P.n - 1, "OPEN", nX - 1
        for j in range(k + 1, nX):
            s0, s1 = i0[j], i1[j] + 1
            hit = np.flatnonzero(P.r[s0:s1] <= stp)
            if len(hit):
                xi = s0 + int(hit[0]); why = "SL"; jx = j
                break
            if ex[j] or (j - k) >= 40:
                xi = i1[j]; why = "TRAIL" if ex[j] else "CAP"; jx = j
                break
        gross = (P.ec[xi] / e0 - 1.0) - (P.bc[xi] / b0 - 1.0)
        ret = gross - 4 * COST
        trades.append(dict(entry_time=int(P.t[a]), exit_time=int(P.t[xi]), side=1, entry=rf, stop=float(stp),
                           exit=float(P.r[xi]), risk=risk, ret=ret, R=ret / risk, why=why, src="I11",
                           ei=int(a), xi=int(xi), gross=100.0 * abs(gross)))
        free = jx
    return trades, P

# ---------------------------------------------------------------------------
# Placebo / flipped (basket_gate style: same side, hold in 1h bars, stop distance)
# ---------------------------------------------------------------------------
def _path_R(B, ei, side, hold, risk):
    fill = B.o[ei]
    if not (np.isfinite(fill) and fill > 0):
        return np.nan
    stp = fill * (1.0 - side * risk)
    mj = min(B.n - 1, ei + hold)
    seg = B.l[ei:mj + 1] if side > 0 else B.h[ei:mj + 1]
    hit = np.flatnonzero(seg <= stp) if side > 0 else np.flatnonzero(seg >= stp)
    if len(hit):
        q = ei + int(hit[0])
        px = min(stp, B.o[q]) if side > 0 else max(stp, B.o[q])
    else:
        px = B.c[mj]
    return (side * (px / fill - 1.0) - 2 * COST) / risk

def _pair_path_R(P, ei, side, hold, risk):
    e0, b0 = P.eo[ei], P.bo[ei]
    mj = min(P.n - 1, ei + hold)
    pr = side * ((P.ec[ei:mj + 1] / e0 - 1.0) - (P.bc[ei:mj + 1] / b0 - 1.0))
    hit = np.flatnonzero(pr <= -risk)
    g = pr[hit[0]] if len(hit) else pr[-1]
    return (g - 4 * COST) / risk

def _pf(arr):
    a = np.asarray(arr, float); a = a[np.isfinite(a)]
    g = a[a > 0].sum(); ls = -a[a < 0].sum()
    return (g / ls) if ls > 0 else (np.inf if g > 0 else np.nan)

def _win(trades, start=HEADLINE_START):
    t0 = ms(start)
    return [t for t in trades if t["exit_time"] >= t0 and np.isfinite(t["R"])]

def flipped_pf(B, trades, pair=False):
    w = _win(trades)
    if not w:
        return np.nan
    f = _pair_path_R if pair else _path_R
    return _pf([f(B, t["ei"], -t["side"], max(1, t["xi"] - t["ei"]), t["risk"]) for t in w])

def placebo_pct(B, trades, real_pf, pair=False, n_runs=N_PLACEBO, seed=20261122):
    w = _win(trades)
    if not w or not np.isfinite(real_pf):
        return np.nan
    f = _pair_path_R if pair else _path_R
    i_start = int(np.searchsorted(B.t, ms(HEADLINE_START), side="left"))
    rng = np.random.default_rng(seed)
    pfs = np.empty(n_runs)
    for k in range(n_runs):
        rs = []
        for t in w:
            hold = max(1, t["xi"] - t["ei"])
            hi = max(i_start + 1, B.n - hold - 1)
            rs.append(f(B, int(rng.integers(i_start, hi)), t["side"], hold, t["risk"]))
        pfs[k] = _pf(rs)
    pfs = np.where(np.isfinite(pfs), pfs, 0.0)
    return float(100.0 * np.mean(real_pf > pfs))

# ---------------------------------------------------------------------------
# Metrics, correlation, basket
# ---------------------------------------------------------------------------
def tstat_window(trades, a, z=None):
    tr = sorted(standardize(trades), key=lambda x: x["exit_time"])
    return tstats(_window(_tframe(tr), a, z))

def metrics(trades):
    w = sorted(_win(trades), key=lambda x: x["exit_time"])
    st = tstat_window(w, HEADLINE_START)
    h1 = tstat_window(w, "2017-01-01", "2021-01-01"); h2 = tstat_window(w, "2021-01-01")
    y18 = tstat_window(w, "2018-01-01", "2019-01-01"); y22 = tstat_window(w, "2022-01-01", "2023-01-01")
    last30 = _pf([t["R"] for t in w[-30:]]) if w else np.nan
    return dict(n=int(st["tr"]), win=st["win"], pf=st["pf"], avgR=st["avgR"], ret=st["ret"], dd=st["dd"],
                gross=float(np.mean([t["gross"] for t in w])) if w else np.nan,
                pf_h1=h1["pf"], n_h1=int(h1["tr"]), pf_h2=h2["pf"], n_h2=int(h2["tr"]), pf_l30=last30,
                ret18=(y18["ret"] if y18["tr"] else 0.0), n18=int(y18["tr"]),
                ret22=(y22["ret"] if y22["tr"] else 0.0), n22=int(y22["tr"]))

def daily_R(trades, w=1.0):
    t0 = ms(HEADLINE_START)
    rows = [(pd.Timestamp(int(t["exit_time"]), unit="ms", tz="UTC").floor("D"), w * float(t["R"]))
            for t in standardize(trades) if t["exit_time"] >= t0 and np.isfinite(t["R"])]
    if not rows:
        return pd.Series(dtype=float)
    return pd.DataFrame(rows, columns=["d", "R"]).groupby("d")["R"].sum()

def basket_daily(eng):
    parts = [daily_R(eng[nm], LIVE_RISK.get(nm, RISK) / RISK) for nm in LIVE if nm in eng]
    parts = [p for p in parts if len(p)]
    return pd.concat(parts, axis=1).fillna(0.0).sum(axis=1) if parts else pd.Series(dtype=float)

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

def basket_curve(eng, extra=None, extra_risk=0.01, start=HEADLINE_START):
    """Same math as oslib.overlay: pnl = R * min(risk_pct, trade stop frac), summed per exit stamp, compounded."""
    t0 = ms(start); by = {}
    def add(trs, rp):
        for t in standardize(trs):
            if t["exit_time"] < t0 or not (np.isfinite(t["risk"]) and t["risk"] > 0 and np.isfinite(t["R"])):
                continue
            by[t["exit_time"]] = by.get(t["exit_time"], 0.0) + t["R"] * min(rp, t["risk"])
    for nm, trs in eng.items():
        add(trs, LIVE_RISK.get(nm, RISK))
    if extra:
        add(extra, extra_risk)
    eq = 1.0; pk = 1.0; mdd = 0.0
    for ts in sorted(by):
        eq *= 1.0 + by[ts]; pk = max(pk, eq); mdd = min(mdd, eq / pk - 1.0)
    ret, dd = 100 * (eq - 1.0), 100 * mdd
    return dict(ret=ret, maxDD=dd, MAR=(ret / abs(dd) if dd < 0 else np.nan))

def overlap_pct(A, Bt):
    """% of A's trades whose holding window overlaps any trade of B."""
    if not A or not Bt:
        return np.nan
    bi = np.array([t["entry_time"] for t in Bt]); bo = np.array([t["exit_time"] for t in Bt])
    hit = sum(1 for t in A if np.any((bi <= t["exit_time"]) & (bo >= t["entry_time"])))
    return 100.0 * hit / len(A)

# ---------------------------------------------------------------------------
# Main
# ---------------------------------------------------------------------------
IDEAS = [
    ("I01", "bear trap: 20d-low sweep + reclaim (long, 1d)", i01),
    ("I02", "weekly 10w-low sweep + reclaim (long, 1w)", i02),
    ("I03", "wide-range trend day continuation (long, 1d)", i03),
    ("I05", "volume explosion continuation (long, 1d)", i05),
    ("I06", "bull trap: 20d-high sweep + reject (short, 1d)", i06),
    ("I07", "structure shift after 60d low (long, 1d)", i07),
    ("I08", "weekly 10w Donchian momentum (long, 1w)", i08),
    ("I09", "fresh-high red-day pullback (long, 1d)", i09),
    ("I10", "6 higher closes streak (long, 1d)", i10),
    ("I11", "ETH/BTC ratio momentum pair (long ETH/short BTC)", None),
    ("I12", "month open-drive +10% in 7d (long, 1d)", i12),
    ("I13", "ATH retest hold (long, 1d)", i13),
    ("I14", "green Monday +2% (long Tue-Fri, 1d)", i14),
    ("I15", "4h wide-range continuation (long, 4h)", i15),
]

def gates(m, plc, flp, eth_pf, cb, pair):
    fails = []
    if not (np.isfinite(m["pf_h1"]) and m["pf_h1"] > 1.3): fails.append(f"PF17-20 {f1(m['pf_h1'],2)}")
    if not (np.isfinite(m["pf_h2"]) and m["pf_h2"] > 1.3): fails.append(f"PF21-26 {f1(m['pf_h2'],2)}")
    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"flipped {f1(flp,2)}")
    if not pair and not (np.isfinite(eth_pf) and eth_pf > 1.0): fails.append(f"ETH {f1(eth_pf,2)}")
    if not (np.isfinite(cb) and cb < 0.3): fails.append(f"corrBasket {f1(cb,2)}")
    return fails

def main(smoke=False):
    if smoke:
        print("SMOKE MODE: synthetic data only (no real backtest).", flush=True)
        btc = synthetic_1h(n=24 * 900, seed=9, start="2016-06-01")
        eth = synthetic_1h(n=24 * 900, seed=21, start="2016-06-01", px0=300.0)
        rng = np.random.default_rng(0)
        fb = pd.DataFrame({"time": btc["time"].to_numpy()[::8], "funding": rng.normal(0, 1e-5, (len(btc) + 7) // 8)})
        fe = pd.DataFrame({"time": eth["time"].to_numpy()[::8], "funding": rng.normal(0, 1e-5, (len(eth) + 7) // 8)})
    else:
        btc, eth = load("btc", "1h"), load("eth", "1h")
        fb, fe = funding("btc", "binance"), funding("eth", "binance")
    Bb, Be = Base(btc), Base(eth)
    print("\n=== building BTC live basket (oslib.engines, Binance funding -> X7 on) ...", flush=True)
    eng = engines(btc, fund=fb)
    print("  " + ", ".join(f"{k} {len(v)}" for k, v in eng.items()) + f"  ({time.time()-T0:.0f}s)", flush=True)
    k8d = daily_R(eng.get("K8", []))
    bd = basket_daily(eng)
    base = basket_curve(eng)
    try:
        ov = overlay(eng, lambda nm, t: 1.0, start=HEADLINE_START)["baseline"]
        print(f"  basket baseline ret {f1(base['ret'])}% maxDD {f1(base['maxDD'],2)}% MAR {f1(base['MAR'],2)}"
              f"  (oslib.overlay check: ret {f1(ov['ret'])}% MAR {f1(ov['MAR'],2)})", flush=True)
    except Exception as e:
        print(f"  basket baseline ret {f1(base['ret'])}% MAR {f1(base['MAR'],2)} (overlay check failed: {e})", flush=True)

    rows, TR = [], {}
    for idx, (key, desc, fn) in enumerate(IDEAS):
        t_i = time.time()
        try:
            pair = key == "I11"
            if pair:
                tb, P = i11(Be, Bb)
                te = None
                PB = P
            else:
                tb = fn(Bb); te = fn(Be); PB = Bb
            m = metrics(tb)
            plc = placebo_pct(PB, tb, m["pf"], pair=pair, seed=20261122 + idx)
            flp = flipped_pf(PB, tb, pair=pair)
            me = metrics(te) if te is not None else None
            eth_pf = me["pf"] if me else np.nan
            dR = daily_R(tb)
            ck, cb = dcorr(dR, k8d), dcorr(dR, bd)
            fails = gates(m, plc, flp, eth_pf, cb, pair)
            keep = not fails
            div = (np.isfinite(m["pf"]) and m["pf"] > 1.15 and np.isfinite(cb) and cb < 0.1
                   and m["ret18"] > 0 and m["ret22"] > 0)
            row = dict(idea=key, desc=desc, n=m["n"], win_pct=m["win"], PF=m["pf"], avgR=m["avgR"], ret_pct=m["ret"],
                       maxDD_pct=m["dd"], avg_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_pct=plc,
                       flipped_PF=flp, ETH_PF=eth_pf, ETH_n=(me["n"] if me else np.nan), corrK8=ck, corrBasket=cb,
                       ret_2018=m["ret18"], n_2018=m["n18"], ret_2022=m["ret22"], n_2022=m["n22"],
                       verdict="KEEP" if keep else ("DIVERSIFIER" if div else "DROP"), failed="; ".join(fails))
            if keep or div:
                for rp, tag in ((0.01, "1"), (0.005, "05")):
                    s = basket_curve(eng, extra=tb, extra_risk=rp)
                    row[f"basket_MAR_{tag}"] = s["MAR"]; row[f"basket_ret_{tag}"] = s["ret"]; row[f"basket_DD_{tag}"] = s["maxDD"]
            rows.append(row); TR[key] = tb
            print(f"  {key} {desc}: n {m['n']} PF {f1(m['pf'],2)} | halves {f1(m['pf_h1'],2)}/{f1(m['pf_h2'],2)} | "
                  f"plc {f1(plc,0)} flip {f1(flp,2)} ETH {f1(eth_pf,2)} cB {f1(cb,2)} -> {row['verdict']}  "
                  f"({time.time()-t_i:.0f}s)", flush=True)
        except Exception as e:
            print(f"  {key} ERROR: {type(e).__name__}: {e}", flush=True)
            traceback.print_exc()
            rows.append(dict(idea=key, desc=desc, verdict="ERROR", failed=f"{type(e).__name__}: {e}"))

    out = pd.DataFrame(rows)
    show = ["idea", "n", "win_pct", "PF", "avgR", "ret_pct", "maxDD_pct", "avg_gross_pct", "PF_17_20", "n_17_20",
            "PF_21_26", "n_21_26", "PF_last30", "placebo_pct", "flipped_PF", "ETH_PF", "corrK8", "corrBasket",
            "ret_2018", "ret_2022", "verdict"]
    show = [c for c in show if c in out.columns]
    print("\n=== BATCH 17 SUMMARY (BTC 2017+, 1% risk, 0.12%/side; ETH = gate asset; I11 = pair, ETH gate n/a) ===", flush=True)
    with pd.option_context("display.float_format", lambda x: f"{x:.2f}"):
        print(out[show].to_string(index=False), flush=True)

    sel = out[out["verdict"].isin(["KEEP", "DIVERSIFIER"])] if "verdict" in out.columns else out.iloc[0:0]
    print("\n=== BASKET MAR WITH IDEA ADDED (BTC live basket at LIVE_RISK, 2017+) ===", flush=True)
    print(f"  baseline           ret {f1(base['ret']):>9s}%  maxDD {f1(base['maxDD'],2):>7s}%  MAR {f1(base['MAR'],2)}", flush=True)
    if len(sel) == 0:
        print("  (no KEEP or DIVERSIFIER ideas)", flush=True)
    for _, r in sel.iterrows():
        for tag, lab in (("1", "1.0%"), ("05", "0.5%")):
            print(f"  + {r['idea']} @ {lab:5s}     ret {f1(r.get('basket_ret_'+tag)):>9s}%  maxDD {f1(r.get('basket_DD_'+tag),2):>7s}%  "
                  f"MAR {f1(r.get('basket_MAR_'+tag),2)}  ({r['verdict']})", flush=True)

    keeps = [k for k in out.loc[out["verdict"] == "KEEP", "idea"]] if "verdict" in out.columns else []
    print("\n=== PAIRWISE TRADE OVERLAP AMONG KEEPs (% of row idea's trades overlapping a column idea trade) ===", flush=True)
    if len(keeps) < 2:
        print(f"  (fewer than 2 KEEPs: {', '.join(keeps) if keeps else 'none'})", flush=True)
    else:
        M = pd.DataFrame(index=keeps, columns=keeps, dtype=float)
        for a in keeps:
            for b in keeps:
                M.loc[a, b] = np.nan if a == b else overlap_pct(_win(TR[a]), _win(TR[b]))
        print(M.round(1).to_string(), flush=True)

    print("\n=== VERDICTS ===", flush=True)
    for _, r in out.iterrows():
        v = r.get("verdict", "ERROR")
        if v == "KEEP":
            txt = f"passes all gates; basket MAR {f1(base['MAR'],2)} -> {f1(r.get('basket_MAR_1'),2)} @1% / {f1(r.get('basket_MAR_05'),2)} @0.5%"
        elif v == "DIVERSIFIER":
            txt = (f"fails KEEP ({r.get('failed','')}) but PF {f1(r['PF'],2)}, corrBasket {f1(r['corrBasket'],2)}, 2018 {f1(r['ret_2018'])}% / "
                   f"2022 {f1(r['ret_2022'])}%; basket MAR {f1(base['MAR'],2)} -> {f1(r.get('basket_MAR_1'),2)} @1% / {f1(r.get('basket_MAR_05'),2)} @0.5%")
        elif v == "ERROR":
            txt = str(r.get("failed", ""))
        else:
            txt = "fails " + str(r.get("failed", ""))
        print(f"  {v:11s} {r['idea']} {r['desc']}: {txt}", flush=True)

    out_dir = Path("/content") if Path("/content").exists() else Path(".")
    path = out_dir / ("batch17_smoke.csv" if smoke else "batch17.csv")
    out.to_csv(path, index=False)
    print(f"\nSaved {path} ({len(out)} rows). Total {time.time()-T0:.0f}s", flush=True)
    return out

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