#!/usr/bin/env python3
"""Batch15.py — 15 new orthogonal BTC/ETH ideas (Batch 15) built strictly on oslib.py."""
from __future__ import annotations

import subprocess
from pathlib import Path
import numpy as np
import pandas as pd

# 1. Auto-download oslib.py if missing
if not Path("oslib.py").exists():
    url = "https://osom-boba.pages.dev/colab/oslib.py"
    print(f"Downloading {url} ...", flush=True)
    subprocess.run(["wget", "-q", "-O", "oslib.py", url], check=True)

import oslib as osl
from oslib import (
    load, funding, expiry_days, engines, simulate,
    atr, ema, sma, rsi, er, chop, bb_width, resample_ohlcv,
    H1, H4, D1, COST, RISK, LIVE_RISK, HEADLINE_START, standardize
)

assert abs(COST - 0.0012) < 1e-12, f"Expected COST=0.0012, got {COST}"
assert abs(RISK - 0.01) < 1e-12, f"Expected RISK=0.01, got {RISK}"

# ==============================================================================
# Shared Simulation & Alignment Helpers
# ==============================================================================

def map_4h_to_1h(df_1h: pd.DataFrame, df_4h: pd.DataFrame, sig_4h: np.ndarray,
                 stop_px_4h: np.ndarray, target_px_4h: np.ndarray | None = None,
                 exit_cond_4h: np.ndarray | None = None):
    t1 = df_1h["time"].to_numpy(dtype="int64")
    g1 = t1 // H4
    last_1h_of_g = pd.Series(np.arange(len(t1))).groupby(g1).max()

    g4 = df_4h["time"].to_numpy(dtype="int64") // H4
    sig_1h = np.zeros(len(t1), dtype=int)
    stop_1h = np.full(len(t1), np.nan, dtype=float)
    tgt_1h = np.full(len(t1), np.nan, dtype=float) if target_px_4h is not None else None
    ex_1h = np.zeros(len(t1), dtype=bool) if exit_cond_4h is not None else None

    for k, g in enumerate(g4):
        if g not in last_1h_of_g.index:
            continue
        idx1 = int(last_1h_of_g.loc[g])
        if sig_4h[k] != 0:
            sig_1h[idx1] = int(sig_4h[k])
            stop_1h[idx1] = float(stop_px_4h[k])
            if tgt_1h is not None and np.isfinite(target_px_4h[k]):
                tgt_1h[idx1] = float(target_px_4h[k])
        if ex_1h is not None and exit_cond_4h[k]:
            ex_1h[idx1] = True

    return sig_1h, stop_1h, tgt_1h, ex_1h


def map_1d_to_1h(df_1h: pd.DataFrame, df_1d: pd.DataFrame, sig_1d: np.ndarray,
                 stop_px_1d: np.ndarray, target_px_1d: np.ndarray | None = None,
                 exit_cond_1d: np.ndarray | None = None):
    t1 = df_1h["time"].to_numpy(dtype="int64")
    g1 = t1 // D1
    last_1h_of_g = pd.Series(np.arange(len(t1))).groupby(g1).max()

    gd = df_1d["time"].to_numpy(dtype="int64") // D1
    sig_1h = np.zeros(len(t1), dtype=int)
    stop_1h = np.full(len(t1), np.nan, dtype=float)
    tgt_1h = np.full(len(t1), np.nan, dtype=float) if target_px_1d is not None else None
    ex_1h = np.zeros(len(t1), dtype=bool) if exit_cond_1d is not None else None

    for k, g in enumerate(gd):
        if g not in last_1h_of_g.index:
            continue
        idx1 = int(last_1h_of_g.loc[g])
        if sig_1d[k] != 0:
            sig_1h[idx1] = int(sig_1d[k])
            stop_1h[idx1] = float(stop_px_1d[k])
            if tgt_1h is not None and np.isfinite(target_px_1d[k]):
                tgt_1h[idx1] = float(target_px_1d[k])
        if ex_1h is not None and exit_cond_1d[k]:
            ex_1h[idx1] = True

    return sig_1h, stop_1h, tgt_1h, ex_1h


def simulate_with_soft_exit(df_1h: pd.DataFrame, signals: np.ndarray, stop_px: np.ndarray,
                            target_px: np.ndarray | None = None, time_stop: int | None = None,
                            soft_exit_L: np.ndarray | None = None, soft_exit_S: np.ndarray | None = None,
                            src: str = "SIM") -> list[dict]:
    t = df_1h["time"].to_numpy(dtype="int64")
    o = df_1h["open"].to_numpy(dtype=float)
    h = df_1h["high"].to_numpy(dtype=float)
    l = df_1h["low"].to_numpy(dtype=float)
    c = df_1h["close"].to_numpy(dtype=float)
    n = len(t)
    trades = []
    i = 0
    while i < n - 1:
        s = int(signals[i])
        if s == 0:
            i += 1
            continue
        ei = i + 1
        if ei >= n:
            break
        fill = float(o[ei])
        stp = float(stop_px[i])
        if not np.isfinite(stp) or s * (fill - stp) <= 0:
            i = ei + 1
            continue
        risk = abs(fill - stp) / fill
        if not (np.isfinite(risk) and risk > 0):
            i = ei + 1
            continue
        tgt = float(target_px[i]) if (target_px is not None and np.isfinite(target_px[i])) else np.nan
        pend_soft = False
        xi = n - 1
        exit_px = float(c[-1])
        why = "OPEN"

        for j in range(ei, n):
            oo, hh, ll, cc = o[j], h[j], l[j], c[j]
            if pend_soft:
                exit_px, xi, why = float(oo), j, "COND"
                break
            hit_stop = (ll <= stp) if s > 0 else (hh >= stp)
            hit_tgt = np.isfinite(tgt) and ((hh >= tgt) if s > 0 else (ll <= tgt))
            if hit_stop:
                exit_px = float(min(stp, oo) if s > 0 else max(stp, oo))
                xi, why = j, "SL"
                break
            if hit_tgt:
                exit_px = float(max(tgt, oo) if s > 0 else min(tgt, oo))
                xi, why = j, "TP"
                break
            if time_stop is not None and (j - ei) >= int(time_stop):
                exit_px, xi, why = float(cc), j, "TIME"
                break
            if s > 0 and soft_exit_L is not None and soft_exit_L[j]:
                pend_soft = True
            elif s < 0 and soft_exit_S is not None and soft_exit_S[j]:
                pend_soft = True

        ret = s * (exit_px / fill - 1.0) - 2.0 * COST
        R = ret / risk
        trades.append(osl._std_trade(dict(
            src=src, side=s, t_in=int(t[ei]), t_out=int(t[xi]),
            entry=fill, stop=stp, exit=exit_px, net_R=R, ret=ret,
            why=why, risk=risk, weight=1.0, ei=ei, xi=xi
        ), src=src))
        i = xi + 1
    return trades


def align_funding_to_bars(bar_times_ms: np.ndarray, bar_period_ms: int, fund_df: pd.DataFrame) -> np.ndarray:
    f = fund_df.sort_values("time").reset_index(drop=True)
    ft = f["time"].to_numpy(dtype="int64")
    fv = f["funding"].to_numpy(dtype=float)
    bar_close = bar_times_ms + int(bar_period_ms)
    idx = np.searchsorted(ft, bar_close, side="right") - 1
    out = np.full(len(bar_times_ms), np.nan, dtype=float)
    valid = idx >= 0
    out[valid] = fv[idx[valid]]
    stale = valid & ((bar_close - ft[np.maximum(idx, 0)]) > 16 * H1)
    out[stale] = np.nan
    return out


# ==============================================================================
# 15 NEW ORTHOGONAL IDEAS (Batch 15)
# ==============================================================================

def build_b15_01(df_1h: pd.DataFrame, flip_dir: bool = False) -> list[dict]:
    """B15_01: Monthly Options Expiry Max-Pain Snapback (Calendar/Session + Mean Reversion, 1H).
    Uses oslib.expiry_days() (last Friday of month 08:00 UTC).
    Entry: At 04:00 UTC on expiry Friday (signal on 03:00 UTC close -> 04:00 next_open),
           if 24H return |(C_03 - C_{-24}) / C_{-24}| >= 0.035 AND ER_24 >= 0.35, fade the pin-drift.
    Stop: Entry +/- 1.8 * ATR14 (1H).
    Exit: 09:00 UTC close (5 bars hold after 04:00 fill — 1h post-Deribit/CME settlement) OR 65% retracement."""
    t = df_1h["time"].to_numpy(dtype="int64")
    o = df_1h["open"].to_numpy(dtype=float)
    h = df_1h["high"].to_numpy(dtype=float)
    l = df_1h["low"].to_numpy(dtype=float)
    c = df_1h["close"].to_numpy(dtype=float)
    a14 = atr(h, l, c, 14)
    er24 = er(c, 24)

    exps = expiry_days("2017-01-01", "2027-01-01")
    # Signal bar is 03:00 UTC on expiry Friday (5 hours before 08:00 UTC expiry)
    sig_times = {int(e.value // 1_000_000) - 5 * H1 for e in exps}

    n = len(df_1h)
    sig = np.zeros(n, dtype=int)
    stp_px = np.full(n, np.nan, dtype=float)
    tgt_px = np.full(n, np.nan, dtype=float)

    for i in range(24, n - 1):
        if int(t[i]) in sig_times and np.isfinite(a14[i]) and np.isfinite(er24[i]):
            ret24 = (c[i] - c[i - 24]) / c[i - 24]
            if abs(ret24) >= 0.035 and er24[i] >= 0.35:
                s = -1 if ret24 > 0 else 1
                if flip_dir:
                    s = -s
                sig[i] = s
                stp_px[i] = o[i + 1] - s * 1.8 * a14[i]
                tgt_px[i] = o[i + 1] + s * 0.65 * abs(c[i] - c[i - 24])

    return simulate(df_1h, sig, stop=stp_px, target=tgt_px, time_stop=5, entry="next_open", check=False)


def build_b15_02(df_1h: pd.DataFrame, fund_df: pd.DataFrame, flip_dir: bool = False) -> list[dict]:
    """B15_02: 7-Day Cumulative Funding Z-Score Exhaustion Fade (Funding/Basis Extreme, 4H, 2019+).
    Entry: Compute rolling 21-bar (7d) sum of 8h funding S7 and its 270-bar (90d) Z-score Z_f.
           On 4H close, SHORT if Z_f >= +2.3 AND C > EMA20(C) + 1.5*ATR14 AND C < O;
           LONG if Z_f <= -2.3 AND C < EMA20(C) - 1.5*ATR14 AND C > O.
    Stop: Entry +/- 2.5 * ATR14. Exit: |Z_f| <= 0.5 OR C crosses EMA20(C), max hold 24 bars (96H)."""
    d4 = resample_ohlcv(df_1h, H4)
    o4 = d4["open"].to_numpy(dtype=float)
    h4 = d4["high"].to_numpy(dtype=float)
    l4 = d4["low"].to_numpy(dtype=float)
    c4 = d4["close"].to_numpy(dtype=float)
    a14 = atr(h4, l4, c4, 14)
    e20 = ema(c4, 20)

    # Build 7d sum and 90d z-score directly on 8h funding table, then align causally
    f = fund_df.sort_values("time").reset_index(drop=True)
    s7 = f["funding"].rolling(21, min_periods=15).sum()
    zf = (s7 - s7.rolling(270, min_periods=180).mean()) / s7.rolling(270, min_periods=180).std()
    f_z_df = pd.DataFrame({"time": f["time"], "funding": zf})
    zf4 = align_funding_to_bars(d4["time"].to_numpy(dtype="int64"), H4, f_z_df)

    ok = np.isfinite(zf4) & np.isfinite(a14) & np.isfinite(e20)
    sig4 = np.zeros(len(d4), dtype=int)
    sig4[ok & (zf4 >= 2.3) & (c4 > e20 + 1.5 * a14) & (c4 < o4)] = -1
    sig4[ok & (zf4 <= -2.3) & (c4 < e20 - 1.5 * a14) & (c4 > o4)] = 1
    if flip_dir:
        sig4 = -sig4

    stp4 = np.where(sig4 != 0, c4 - sig4 * 2.5 * a14, np.nan)
    exL4 = (np.isfinite(zf4) & (zf4 >= -0.5)) | (np.isfinite(e20) & (c4 >= e20))
    exS4 = (np.isfinite(zf4) & (zf4 <= 0.5)) | (np.isfinite(e20) & (c4 <= e20))

    sig1, stp1, _, exL1 = map_4h_to_1h(df_1h, d4, sig4, stp4, exit_cond_4h=exL4)
    _, _, _, exS1 = map_4h_to_1h(df_1h, d4, sig4, stp4, exit_cond_4h=exS4)
    return simulate_with_soft_exit(df_1h, sig1, stp1, time_stop=96, soft_exit_L=exL1, soft_exit_S=exS1, src="B15_02_FundZ7d")


def build_b15_03(df_1h: pd.DataFrame, flip_dir: bool = False) -> list[dict]:
    """B15_03: Post-Shock Vol-Contraction Mid-Range Fade (Liquidation/Volatility Shock, 1H).
    Entry: A 1H shock bar (H-L >= 3.2*ATR24) occurred exactly 2 bars ago (t-2), followed by
           two inside/quiet bars whose combined range <= 0.55*(H_{t-2}-L_{t-2}).
           Fade the shock bar direction (SHORT if C_{t-2} > O_{t-2}, LONG if C_{t-2} < O_{t-2}).
    Stop: H_{t-2} + 0.4*ATR24 (short) or L_{t-2} - 0.4*ATR24 (long).
    Exit: Midpoint of shock bar 0.5*(H_{t-2}+L_{t-2}) OR 10 bars time stop."""
    o = df_1h["open"].to_numpy(dtype=float)
    h = df_1h["high"].to_numpy(dtype=float)
    l = df_1h["low"].to_numpy(dtype=float)
    c = df_1h["close"].to_numpy(dtype=float)
    a24 = atr(h, l, c, 24)
    n = len(df_1h)

    sig = np.zeros(n, dtype=int)
    stp_px = np.full(n, np.nan, dtype=float)
    tgt_px = np.full(n, np.nan, dtype=float)

    for i in range(26, n - 1):
        if not np.isfinite(a24[i - 2]):
            continue
        rng_shk = h[i - 2] - l[i - 2]
        if rng_shk < 3.2 * a24[i - 2]:
            continue
        hi_after = max(h[i - 1], h[i])
        lo_after = min(l[i - 1], l[i])
        if (hi_after - lo_after) <= 0.55 * rng_shk and hi_after <= h[i - 2] and lo_after >= l[i - 2]:
            body = c[i - 2] - o[i - 2]
            if abs(body) > 0.25 * rng_shk:
                s = -1 if body > 0 else 1
                if flip_dir:
                    s = -s
                sig[i] = s
                stp_px[i] = (h[i - 2] + 0.4 * a24[i - 2]) if s < 0 else (l[i - 2] - 0.4 * a24[i - 2])
                tgt_px[i] = 0.5 * (h[i - 2] + l[i - 2])

    return simulate(df_1h, sig, stop=stp_px, target=tgt_px, time_stop=10, entry="next_open", check=False)


def build_b15_04(df_1h: pd.DataFrame, flip_dir: bool = False) -> list[dict]:
    """B15_04: Asia Session Sweep & London Reclaim Reversal (Calendar/Session Effect, 1H).
    Entry: At 08:00 UTC close (enters 09:00 UTC), compute Asia range [00:00..06:00 UTC].
           If bar 07:00 or 08:00 swept above Asia high by >= 0.4*ATR14 and 08:00 closed back below
           Asia high -> SHORT; symmetric sweep below Asia low + reclaim above -> LONG.
    Stop: Sweep extreme +/- 0.5*ATR14. Exit: 15:00 UTC (6 bars hold) OR opposite Asia boundary."""
    t = df_1h["time"].to_numpy(dtype="int64")
    h = df_1h["high"].to_numpy(dtype=float)
    l = df_1h["low"].to_numpy(dtype=float)
    c = df_1h["close"].to_numpy(dtype=float)
    a14 = atr(h, l, c, 14)

    dt = pd.to_datetime(t, unit="ms", utc=True)
    hr = dt.hour.to_numpy()
    day_id = t // D1
    n = len(df_1h)

    sig = np.zeros(n, dtype=int)
    stp_px = np.full(n, np.nan, dtype=float)
    tgt_px = np.full(n, np.nan, dtype=float)

    for i in range(8, n - 1):
        if hr[i] == 8 and day_id[i] == day_id[i - 8] and hr[i - 8] == 0 and np.isfinite(a14[i]):
            asia_hi = np.max(h[i - 8:i - 1])  # 00:00..06:00 inclusive (7 bars)
            asia_lo = np.min(l[i - 8:i - 1])
            swp_hi = max(h[i - 1], h[i])
            swp_lo = min(l[i - 1], l[i])
            s = 0
            if (swp_hi - asia_hi) >= 0.4 * a14[i] and c[i] < asia_hi:
                s = -1
            elif (asia_lo - swp_lo) >= 0.4 * a14[i] and c[i] > asia_lo:
                s = 1
            if s != 0:
                if flip_dir:
                    s = -s
                sig[i] = s
                stp_px[i] = (swp_hi + 0.5 * a14[i]) if s < 0 else (swp_lo - 0.5 * a14[i])
                tgt_px[i] = asia_lo if s < 0 else asia_hi

    return simulate(df_1h, sig, stop=stp_px, target=tgt_px, time_stop=6, entry="next_open", check=False)


def build_b15_05(df_btc_1h: pd.DataFrame, df_eth_1h: pd.DataFrame, flip_dir: bool = False) -> list[dict]:
    """B15_05: ETH/BTC Rolling Correlation Breakdown Reversion (Multi-Asset Binance-Only, 4H).
    Entry: Compute 30-bar rolling Pearson correlation corr_30 between 4H log-returns of BTC and ETH.
           When corr_30 drops <= 0.45 (decoupling shock) AND BTC 3-bar return <= -0.025 while
           ETH 3-bar return >= -0.005 (BTC idiosyncratic dump), LONG BTC.
    Stop: Entry - 2.0*ATR14. Exit: corr_30 >= 0.75 OR +2.5*ATR14 target, max hold 12 bars (48H)."""
    b4 = resample_ohlcv(df_btc_1h, H4)
    e4 = resample_ohlcv(df_eth_1h, H4)
    m = pd.merge(b4, e4[["time", "close"]], on="time", how="inner", suffixes=("", "_eth"))
    cb = m["close"].to_numpy(dtype=float)
    ce = m["close_eth"].to_numpy(dtype=float)
    hb = m["high"].to_numpy(dtype=float)
    lb = m["low"].to_numpy(dtype=float)
    a14 = atr(hb, lb, cb, 14)

    rb = pd.Series(np.log(np.maximum(cb, 1e-12))).diff()
    re = pd.Series(np.log(np.maximum(ce, 1e-12))).diff()
    corr30 = rb.rolling(30, min_periods=30).corr(re).to_numpy()

    ret3_b = (cb - np.roll(cb, 3)) / np.maximum(np.roll(cb, 3), 1e-12)
    ret3_e = (ce - np.roll(ce, 3)) / np.maximum(np.roll(ce, 3), 1e-12)
    ret3_b[:3] = np.nan
    ret3_e[:3] = np.nan

    cond = np.isfinite(corr30) & np.isfinite(a14) & np.isfinite(ret3_b) &            (corr30 <= 0.45) & (ret3_b <= -0.025) & (ret3_e >= -0.005)
    sig4 = np.where(cond, (-1 if flip_dir else 1), 0).astype(int)
    stp4 = np.where(sig4 != 0, cb - sig4 * 2.0 * a14, np.nan)
    tgt4 = np.where(sig4 != 0, cb + sig4 * 2.5 * a14, np.nan)
    ex4 = np.isfinite(corr30) & (corr30 >= 0.75)

    sig1, stp1, tgt1, ex1 = map_4h_to_1h(df_btc_1h, m, sig4, stp4, target_px_4h=tgt4, exit_cond_4h=ex4)
    return simulate_with_soft_exit(df_btc_1h, sig1, stp1, target_px=tgt1, time_stop=48,
                                   soft_exit_L=ex1, soft_exit_S=ex1, src="B15_05_CorrDecoup")


def build_b15_06(df_1h: pd.DataFrame, flip_dir: bool = False) -> list[dict]:
    """B15_06: High-Chop Keltner Channel Mean Reversion (Mean Reversion, 4H).
    Entry: Chop_14 >= 62.0 (confirmed range/chop regime — opposite of MOM30's chop < 30).
           SHORT when C > EMA20 + 2.2*ATR14 AND RSI_6 >= 78;
           LONG when C < EMA20 - 2.2*ATR14 AND RSI_6 <= 22.
    Stop: Entry +/- 1.8*ATR14. Exit: C crosses EMA20, max hold 10 bars (40H)."""
    d4 = resample_ohlcv(df_1h, H4)
    h4 = d4["high"].to_numpy(dtype=float)
    l4 = d4["low"].to_numpy(dtype=float)
    c4 = d4["close"].to_numpy(dtype=float)
    ch = chop(h4, l4, c4, 14)
    e20 = ema(c4, 20)
    a14 = atr(h4, l4, c4, 14)
    r6 = rsi(c4, 6)

    ok = np.isfinite(ch) & np.isfinite(e20) & np.isfinite(a14) & np.isfinite(r6) & (ch >= 62.0)
    sig4 = np.zeros(len(d4), dtype=int)
    sig4[ok & (c4 > e20 + 2.2 * a14) & (r6 >= 78.0)] = -1
    sig4[ok & (c4 < e20 - 2.2 * a14) & (r6 <= 22.0)] = 1
    if flip_dir:
        sig4 = -sig4

    stp4 = np.where(sig4 != 0, c4 - sig4 * 1.8 * a14, np.nan)
    exL4 = np.isfinite(e20) & (c4 >= e20)
    exS4 = np.isfinite(e20) & (c4 <= e20)

    sig1, stp1, _, exL1 = map_4h_to_1h(df_1h, d4, sig4, stp4, exit_cond_4h=exL4)
    _, _, _, exS1 = map_4h_to_1h(df_1h, d4, sig4, stp4, exit_cond_4h=exS4)
    return simulate_with_soft_exit(df_1h, sig1, stp1, time_stop=40, soft_exit_L=exL1, soft_exit_S=exS1, src="B15_06_HiChopKC")


def build_b15_07(df_1h: pd.DataFrame, flip_dir: bool = False) -> list[dict]:
    """B15_07: Turn-of-Month Institutional Rebalance Long (Calendar/Session + Long-Only, Daily).
    Entry: On the close of trading day T-2 before month-end (2 calendar days before last day of month),
           if Daily C < SMA20(C) (month-to-date pullback creates underweight rebalance demand), go LONG.
    Stop: Entry - 2.5*ATR14 (Daily). Exit: Close of day +3 of the new month (approx 5 days = 120H)."""
    d1 = resample_ohlcv(df_1h, D1)
    h1d = d1["high"].to_numpy(dtype=float)
    l1d = d1["low"].to_numpy(dtype=float)
    c1d = d1["close"].to_numpy(dtype=float)
    a14 = atr(h1d, l1d, c1d, 14)
    s20 = sma(c1d, 20)

    dt = pd.to_datetime(d1["time"].to_numpy(dtype="int64"), unit="ms", utc=True)
    days_in_m = dt.days_in_month.to_numpy()
    dom = dt.day.to_numpy()
    # Signal 2 days before month end (e.g., day 28 of 30, day 29 of 31)
    tom_sig_day = (dom == (days_in_m - 2))

    cond = tom_sig_day & np.isfinite(a14) & np.isfinite(s20) & (c1d < s20)
    sig_d = np.where(cond, (-1 if flip_dir else 1), 0).astype(int)
    stp_d = np.where(sig_d != 0, c1d - sig_d * 2.5 * a14, np.nan)

    sig1, stp1, _, _ = map_1d_to_1h(df_1h, d1, sig_d, stp_d)
    return simulate(df_1h, sig1, stop=stp1, target=None, time_stop=120, entry="next_open", check=False)


def build_b15_08(df_1h: pd.DataFrame, fund_df: pd.DataFrame, flip_dir: bool = False) -> list[dict]:
    """B15_08: Funding-Rate Sign-Flip Capitulation Trigger (Funding/Basis Extreme, 4H, 2019+).
    Entry: 3-bar rolling average funding was >= +0.0004 (crowded longs), and current FR drops <= -0.0001
           (abrupt sentiment/perp basis inversion) while C < EMA12(C). Go LONG.
    Stop: Entry - 2.0*ATR14. Exit: FR >= +0.0001 OR +2.5*ATR14 target, max hold 15 bars (60H)."""
    d4 = resample_ohlcv(df_1h, H4)
    h4 = d4["high"].to_numpy(dtype=float)
    l4 = d4["low"].to_numpy(dtype=float)
    c4 = d4["close"].to_numpy(dtype=float)
    a14 = atr(h4, l4, c4, 14)
    e12 = ema(c4, 12)
    fr4 = align_funding_to_bars(d4["time"].to_numpy(dtype="int64"), H4, fund_df)

    fr_prev3 = pd.Series(fr4).shift(1).rolling(3, min_periods=3).mean().to_numpy()
    cond = np.isfinite(fr4) & np.isfinite(fr_prev3) & np.isfinite(a14) & np.isfinite(e12) &            (fr_prev3 >= 0.0004) & (fr4 <= -0.0001) & (c4 < e12)
    sig4 = np.where(cond, (-1 if flip_dir else 1), 0).astype(int)
    stp4 = np.where(sig4 != 0, c4 - sig4 * 2.0 * a14, np.nan)
    tgt4 = np.where(sig4 != 0, c4 + sig4 * 2.5 * a14, np.nan)
    ex4 = np.isfinite(fr4) & (fr4 >= 0.0001)

    sig1, stp1, tgt1, ex1 = map_4h_to_1h(df_1h, d4, sig4, stp4, target_px_4h=tgt4, exit_cond_4h=ex4)
    return simulate_with_soft_exit(df_1h, sig1, stp1, target_px=tgt1, time_stop=60,
                                   soft_exit_L=ex1, soft_exit_S=ex1, src="B15_08_FundFlip")


def build_b15_09(df_1h: pd.DataFrame, flip_dir: bool = False) -> list[dict]:
    """B15_09: Parabolic Blow-Off Top Short Specialist (Short-Only Regime Specialist, Daily).
    Entry: Daily return (C_t - C_{t-5})/C_{t-5} >= +0.22 (22% 5-day surge) AND RSI_5 >= 90
           AND upper wick (H_t - max(O_t, C_t)) >= 0.35 * (H_t - L_t). Go SHORT.
    Stop: H_t + 0.5*ATR14 (Daily). Exit: C_t <= EMA10(C_t) OR 7 days (168H)."""
    d1 = resample_ohlcv(df_1h, D1)
    o1d = d1["open"].to_numpy(dtype=float)
    h1d = d1["high"].to_numpy(dtype=float)
    l1d = d1["low"].to_numpy(dtype=float)
    c1d = d1["close"].to_numpy(dtype=float)
    a14 = atr(h1d, l1d, c1d, 14)
    r5 = rsi(c1d, 5)
    e10 = ema(c1d, 10)

    ret5 = (c1d - np.roll(c1d, 5)) / np.maximum(np.roll(c1d, 5), 1e-12)
    ret5[:5] = np.nan
    rng = np.maximum(h1d - l1d, 1e-12)
    uwick = (h1d - np.maximum(o1d, c1d)) / rng

    cond = np.isfinite(ret5) & np.isfinite(r5) & np.isfinite(a14) &            (ret5 >= 0.22) & (r5 >= 90.0) & (uwick >= 0.35)
    sig_d = np.where(cond, (1 if flip_dir else -1), 0).astype(int)
    stp_d = np.where(sig_d < 0, h1d + 0.5 * a14, np.where(sig_d > 0, l1d - 0.5 * a14, np.nan))
    ex_d = np.isfinite(e10) & ((c1d <= e10) if not flip_dir else (c1d >= e10))

    sig1, stp1, _, ex1 = map_1d_to_1h(df_1h, d1, sig_d, stp_d, exit_cond_1d=ex_d)
    return simulate_with_soft_exit(df_1h, sig1, stp1, time_stop=168, soft_exit_L=ex1, soft_exit_S=ex1, src="B15_09_BlowoffShort")


def build_b15_10(df_1h: pd.DataFrame, flip_dir: bool = False) -> list[dict]:
    """B15_10: Crash-Rebound Capitulation Long Specialist (Long-Only Regime Specialist, Daily).
    Entry: Daily return (C_t - C_{t-4})/C_{t-4} <= -0.18 (-18% 4-day crash) AND RSI_4 <= 12
           AND lower wick (min(O_t, C_t) - L_t) >= 0.35 * (H_t - L_t). Go LONG.
    Stop: L_t - 0.5*ATR14 (Daily). Exit: C_t >= EMA10(C_t) OR 7 days (168H)."""
    d1 = resample_ohlcv(df_1h, D1)
    o1d = d1["open"].to_numpy(dtype=float)
    h1d = d1["high"].to_numpy(dtype=float)
    l1d = d1["low"].to_numpy(dtype=float)
    c1d = d1["close"].to_numpy(dtype=float)
    a14 = atr(h1d, l1d, c1d, 14)
    r4 = rsi(c1d, 4)
    e10 = ema(c1d, 10)

    ret4 = (c1d - np.roll(c1d, 4)) / np.maximum(np.roll(c1d, 4), 1e-12)
    ret4[:4] = np.nan
    rng = np.maximum(h1d - l1d, 1e-12)
    lwick = (np.minimum(o1d, c1d) - l1d) / rng

    cond = np.isfinite(ret4) & np.isfinite(r4) & np.isfinite(a14) &            (ret4 <= -0.18) & (r4 <= 12.0) & (lwick >= 0.35)
    sig_d = np.where(cond, (-1 if flip_dir else 1), 0).astype(int)
    stp_d = np.where(sig_d > 0, l1d - 0.5 * a14, np.where(sig_d < 0, h1d + 0.5 * a14, np.nan))
    ex_d = np.isfinite(e10) & ((c1d >= e10) if not flip_dir else (c1d <= e10))

    sig1, stp1, _, ex1 = map_1d_to_1h(df_1h, d1, sig_d, stp_d, exit_cond_1d=ex_d)
    return simulate_with_soft_exit(df_1h, sig1, stp1, time_stop=168, soft_exit_L=ex1, soft_exit_S=ex1, src="B15_10_CrashLong")


def build_b15_11(df_1h: pd.DataFrame, flip_dir: bool = False) -> list[dict]:
    """B15_11: Sunday Liquidity Vacuum Breakout-Fade (Weekend/Monday Gaps, 1H).
    Entry: Sunday 18:00 UTC close (enters 19:00 UTC), if Sunday 00:00..18:00 range > 1.8*ATR24
           and price is at top 15% of Sunday range -> SHORT; bottom 15% -> LONG.
    Stop: Sunday extreme +/- 0.8*ATR24. Exit: Monday 07:00 UTC (12 bars hold) OR Sunday open."""
    t = df_1h["time"].to_numpy(dtype="int64")
    o = df_1h["open"].to_numpy(dtype=float)
    h = df_1h["high"].to_numpy(dtype=float)
    l = df_1h["low"].to_numpy(dtype=float)
    c = df_1h["close"].to_numpy(dtype=float)
    a24 = atr(h, l, c, 24)

    dt = pd.to_datetime(t, unit="ms", utc=True)
    dow = dt.dayofweek.to_numpy()
    hr = dt.hour.to_numpy()
    n = len(df_1h)

    sig = np.zeros(n, dtype=int)
    stp_px = np.full(n, np.nan, dtype=float)
    tgt_px = np.full(n, np.nan, dtype=float)

    for i in range(18, n - 1):
        if dow[i] == 6 and hr[i] == 18 and dow[i - 18] == 6 and hr[i - 18] == 0 and np.isfinite(a24[i]):
            sun_hi = np.max(h[i - 18:i + 1])
            sun_lo = np.min(l[i - 18:i + 1])
            sun_rng = sun_hi - sun_lo
            if sun_rng >= 1.8 * a24[i] and sun_rng > 0:
                pos_in_rng = (c[i] - sun_lo) / sun_rng
                s = 0
                if pos_in_rng >= 0.85:
                    s = -1
                elif pos_in_rng <= 0.15:
                    s = 1
                if s != 0:
                    if flip_dir:
                        s = -s
                    sig[i] = s
                    stp_px[i] = (sun_hi + 0.8 * a24[i]) if s < 0 else (sun_lo - 0.8 * a24[i])
                    tgt_px[i] = o[i - 18]  # Sunday 00:00 open

    return simulate(df_1h, sig, stop=stp_px, target=tgt_px, time_stop=12, entry="next_open", check=False)


def build_b15_12(df_btc_1h: pd.DataFrame, df_eth_1h: pd.DataFrame, flip_dir: bool = False) -> list[dict]:
    """B15_12: ETH/BTC Ratio Bollinger Extremes Switch (Multi-Asset Binance-Only, Daily).
    Entry: Daily ratio R = C_ETH / C_BTC. Compute 30-day BB(30, 2.2) on R.
           When R > BB_upper(30, 2.2) and R_t < R_{t-1} (ETH overextended vs BTC, turning down) -> LONG BTC;
           When R < BB_lower(30, 2.2) and R_t > R_{t-1} (ETH oversold vs BTC, turning up) -> SHORT BTC.
    Stop: Entry +/- 2.5*ATR14 (Daily BTC). Exit: R crosses SMA30(R) OR 10 days (240H)."""
    bd = resample_ohlcv(df_btc_1h, D1)
    ed = resample_ohlcv(df_eth_1h, D1)
    m = pd.merge(bd, ed[["time", "close"]], on="time", how="inner", suffixes=("", "_eth"))
    cb = m["close"].to_numpy(dtype=float)
    ce = m["close_eth"].to_numpy(dtype=float)
    hb = m["high"].to_numpy(dtype=float)
    lb = m["low"].to_numpy(dtype=float)
    a14 = atr(hb, lb, cb, 14)

    r = ce / np.maximum(cb, 1e-12)
    rp = np.r_[np.nan, r[:-1]]
    ru, rm, rl, _ = bb_width(r, 30, 2.2)

    ok = np.isfinite(ru) & np.isfinite(rp) & np.isfinite(a14)
    sig_d = np.zeros(len(m), dtype=int)
    sig_d[ok & (r > ru) & (r < rp)] = 1
    sig_d[ok & (r < rl) & (r > rp)] = -1
    if flip_dir:
        sig_d = -sig_d

    stp_d = np.where(sig_d != 0, cb - sig_d * 2.5 * a14, np.nan)
    exL_d = np.isfinite(rm) & (r <= rm)
    exS_d = np.isfinite(rm) & (r >= rm)

    sig1, stp1, _, exL1 = map_1d_to_1h(df_btc_1h, m, sig_d, stp_d, exit_cond_1d=exL_d)
    _, _, _, exS1 = map_1d_to_1h(df_btc_1h, m, sig_d, stp_d, exit_cond_1d=exS_d)
    return simulate_with_soft_exit(df_btc_1h, sig1, stp1, time_stop=240, soft_exit_L=exL1, soft_exit_S=exS1, src="B15_12_RatioBB")


def build_b15_13(df_1h: pd.DataFrame, flip_dir: bool = False) -> list[dict]:
    """B15_13: Consecutive 4H Exhaustion Candle Count Reversal (Mean Reversion, 4H).
    Entry: 6 consecutive 4H bars closing in the same direction (all C > O or all C < O)
           with cumulative 6-bar move >= 3.5*ATR14 and bar 6 body < bar 5 body (deceleration). Fade it.
    Stop: Entry +/- 2.0*ATR14. Exit: +2.0*ATR14 target OR 8 bars (32H)."""
    d4 = resample_ohlcv(df_1h, H4)
    o4 = d4["open"].to_numpy(dtype=float)
    h4 = d4["high"].to_numpy(dtype=float)
    l4 = d4["low"].to_numpy(dtype=float)
    c4 = d4["close"].to_numpy(dtype=float)
    a14 = atr(h4, l4, c4, 14)

    up = (c4 > o4).astype(int)
    dn = (c4 < o4).astype(int)
    up6 = pd.Series(up).rolling(6).sum().to_numpy() == 6
    dn6 = pd.Series(dn).rolling(6).sum().to_numpy() == 6
    move6 = c4 - np.roll(o4, 5)
    move6[:5] = np.nan
    body = np.abs(c4 - o4)
    decel = body < np.r_[np.nan, body[:-1]]

    ok = np.isfinite(a14) & np.isfinite(move6) & decel
    sig4 = np.zeros(len(d4), dtype=int)
    sig4[ok & up6 & (move6 >= 3.5 * a14)] = -1
    sig4[ok & dn6 & (-move6 >= 3.5 * a14)] = 1
    if flip_dir:
        sig4 = -sig4

    stp4 = np.where(sig4 != 0, c4 - sig4 * 2.0 * a14, np.nan)
    tgt4 = np.where(sig4 != 0, c4 + sig4 * 2.0 * a14, np.nan)
    sig1, stp1, tgt1, _ = map_4h_to_1h(df_1h, d4, sig4, stp4, target_px_4h=tgt4)
    return simulate(df_1h, sig1, stop=stp1, target=tgt1, time_stop=32, entry="next_open", check=False)


def build_b15_14(df_1h: pd.DataFrame, flip_dir: bool = False) -> list[dict]:
    """B15_14: Volume-Weighted Intraday VWAP Band Fade in Low-ER Regime (Mean Reversion, 1H).
    Entry: Rolling 48H VWAP and 48H close std sd48. When ER_48 <= 0.20 (choppy drift),
           SHORT if C > VWAP48 + 2.5*sd48; LONG if C < VWAP48 - 2.5*sd48.
    Stop: Entry +/- 2.0*ATR14 (1H). Exit: C crosses VWAP48 OR 18 bars (18H)."""
    h = df_1h["high"].to_numpy(dtype=float)
    l = df_1h["low"].to_numpy(dtype=float)
    c = df_1h["close"].to_numpy(dtype=float)
    v = np.maximum(df_1h["volume"].to_numpy(dtype=float), 1e-9)
    a14 = atr(h, l, c, 14)
    er48 = er(c, 48)

    tp = (h + l + c) / 3.0
    vwap48 = (pd.Series(tp * v).rolling(48, min_periods=48).sum() /
              pd.Series(v).rolling(48, min_periods=48).sum()).to_numpy()
    sd48 = pd.Series(c - vwap48).rolling(48, min_periods=48).std().to_numpy()

    ok = np.isfinite(vwap48) & np.isfinite(sd48) & np.isfinite(a14) & np.isfinite(er48) & (er48 <= 0.20)
    sig = np.zeros(len(df_1h), dtype=int)
    sig[ok & (c > vwap48 + 2.5 * sd48)] = -1
    sig[ok & (c < vwap48 - 2.5 * sd48)] = 1
    if flip_dir:
        sig = -sig

    stp_px = np.where(sig != 0, c - sig * 2.0 * a14, np.nan)
    exL = np.isfinite(vwap48) & (c >= vwap48)
    exS = np.isfinite(vwap48) & (c <= vwap48)
    return simulate_with_soft_exit(df_1h, sig, stp_px, time_stop=18, soft_exit_L=exL, soft_exit_S=exS, src="B15_14_VWAP48Fade")


def build_b15_15(df_1h: pd.DataFrame, fund_df: pd.DataFrame, flip_dir: bool = False) -> list[dict]:
    """B15_15: Post-Liquidation Negative-Funding Double-Confirmation Bounce (Shock + Funding, 1H, 2019+).
    Entry: 1H drop (C - O)/O <= -0.025 with volume >= 3.5*SMA48(V) AND lower wick >= 0.30*(H-L)
           AND current 8h funding FR <= -0.0002 (crowded shorts trapped in panic). Go LONG.
    Stop: L - 0.5*ATR14 (1H). Exit: +2.0*ATR14 target OR 12 bars (12H)."""
    o = df_1h["open"].to_numpy(dtype=float)
    h = df_1h["high"].to_numpy(dtype=float)
    l = df_1h["low"].to_numpy(dtype=float)
    c = df_1h["close"].to_numpy(dtype=float)
    v = df_1h["volume"].to_numpy(dtype=float)
    a14 = atr(h, l, c, 14)
    vs48 = sma(v, 48)
    fr1 = align_funding_to_bars(df_1h["time"].to_numpy(dtype="int64"), H1, fund_df)

    ret1 = (c - o) / np.maximum(o, 1e-12)
    rng = np.maximum(h - l, 1e-12)
    lwick = (np.minimum(o, c) - l) / rng

    cond = np.isfinite(a14) & np.isfinite(vs48) & np.isfinite(fr1) &            (ret1 <= -0.025) & (v >= 3.5 * vs48) & (lwick >= 0.30) & (fr1 <= -0.0002)
    sig = np.where(cond, (-1 if flip_dir else 1), 0).astype(int)
    stp_px = np.where(sig > 0, l - 0.5 * a14, np.where(sig < 0, h + 0.5 * a14, np.nan))
    tgt_px = np.where(sig != 0, c + sig * 2.0 * a14, np.nan)
    return simulate(df_1h, sig, stop=stp_px, target=tgt_px, time_stop=12, entry="next_open", check=False)


# ==============================================================================
# Placebo, Metrics, Correlation & Overlap Pipeline
# ==============================================================================

def placebo_pf_percentile(trades: list[dict], real_pf: float, n_runs: int = 100, seed: int = 20261123) -> float:
    if not trades or not np.isfinite(real_pf):
        return np.nan
    rng = np.random.default_rng(seed)
    valid_t = [t for t in trades if np.isfinite(t.get("R", np.nan))]
    if not valid_t:
        return np.nan
    r_vals = np.array([float(t["R"]) for t in valid_t], dtype=float)
    fee_r = np.array([
        (2.0 * COST) / float(t["risk"]) if (np.isfinite(t.get("risk", np.nan)) and t["risk"] > 0) else 0.0
        for t in valid_t
    ], dtype=float)
    gross_r = r_vals + fee_r

    pfs = np.empty(n_runs, dtype=float)
    for k in range(n_runs):
        signs = rng.choice([-1.0, 1.0], size=len(gross_r))
        sim_r = signs * gross_r - fee_r
        g = sim_r[sim_r > 0].sum()
        ls = -sim_r[sim_r < 0].sum()
        pfs[k] = (g / ls) if ls > 0 else (np.inf if g > 0 else 0.0)
    return float(100.0 * np.mean(real_pf > pfs))


def basket_daily_R(eng_map: dict[str, list[dict]], start: str = HEADLINE_START) -> pd.Series:
    t0 = osl.ms(start)
    parts = []
    for nm, trs in eng_map.items():
        w = LIVE_RISK.get(nm, RISK) / RISK
        std = standardize(trs, src=nm)
        rows = [(pd.Timestamp(t["exit_time"], unit="ms", tz="UTC").floor("D"), w * float(t["R"]))
                for t in std if t["exit_time"] >= t0 and np.isfinite(t.get("R", np.nan))]
        if rows:
            s = pd.DataFrame(rows, columns=["day", "R"]).groupby("day")["R"].sum()
            parts.append(s)
    if not parts:
        return pd.Series(dtype=float)
    return pd.concat(parts, axis=1).fillna(0.0).sum(axis=1)


def idea_daily_R(trades: list[dict], start: str = HEADLINE_START) -> pd.Series:
    t0 = osl.ms(start)
    std = standardize(trades)
    rows = [(pd.Timestamp(t["exit_time"], unit="ms", tz="UTC").floor("D"), float(t["R"]))
            for t in std if t["exit_time"] >= t0 and np.isfinite(t.get("R", np.nan))]
    if not rows:
        return pd.Series(dtype=float)
    return pd.DataFrame(rows, columns=["day", "R"]).groupby("day")["R"].sum()


def daily_corr(s1: pd.Series, s2: pd.Series) -> float:
    if len(s1) == 0 or len(s2) == 0:
        return np.nan
    idx = s1.index.union(s2.index)
    a = s1.reindex(idx).fillna(0.0)
    b = s2.reindex(idx).fillna(0.0)
    if a.std() <= 1e-12 or b.std() <= 1e-12:
        return np.nan
    return float(a.corr(b))


def compute_metrics(trades: list[dict], start: str = HEADLINE_START) -> dict:
    tf = osl._window(osl._tframe(standardize(trades)), start)
    st = osl.tstats(tf)
    h1 = osl.tstats(osl._window(tf, "2017-01-01", "2021-01-01"))
    h2 = osl.tstats(osl._window(tf, "2021-01-01", "2100-01-01"))
    std_w = [t for t in standardize(trades) if t["exit_time"] >= osl.ms(start)]
    gross_moves = [
        100.0 * abs(t["exit"] - t["entry"]) / t["entry"]
        for t in std_w if np.isfinite(t["entry"]) and t["entry"] > 0 and np.isfinite(t["exit"])
    ]
    avg_gross_pct = float(np.mean(gross_moves)) if gross_moves else np.nan
    return dict(
        n=st["tr"], win=st["win"], pf=st["pf"], avgR=st["avgR"],
        ret=st["ret"], maxDD=st["dd"], avg_gross_pct=avg_gross_pct,
        pf_h1=h1["pf"], n_h1=h1["tr"], pf_h2=h2["pf"], n_h2=h2["tr"]
    )


def pairwise_overlap_pct(trades_a: list[dict], trades_b: list[dict]) -> float:
    if not trades_a or not trades_b:
        return 0.0
    spans_b = [(t["entry_time"], t["exit_time"]) for t in trades_b]
    ov = 0
    for ta in trades_a:
        a0, a1 = ta["entry_time"], ta["exit_time"]
        if any(a0 < b1 and b0 < a1 for b0, b1 in spans_b):
            ov += 1
    return 100.0 * ov / len(trades_a)


# ==============================================================================
# Main Execution
# ==============================================================================

def main() -> None:
    print("=== Batch 15: 15 New Orthogonal Mean-Reversion / Calendar / Funding / Shock / Pair Ideas ===", flush=True)
    btc_1h = load("btc", "1h")
    eth_1h = load("eth", "1h")
    btc_fund = funding("btc", "binance")
    eth_fund = funding("eth", "binance")

    print("\nBuilding oslib live basket & K8 benchmark on BTC 2017+ ...", flush=True)
    btc_engines = engines(btc_1h, fund=btc_fund)
    k8_daily_r = idea_daily_R(btc_engines["K8"], start=HEADLINE_START)
    bsk_daily_r = basket_daily_R(btc_engines, start=HEADLINE_START)

    specs = [
        ("B15_01_ExpiryPin",   "2017-01-01", lambda d, f, fl: build_b15_01(d, fl),    "single"),
        ("B15_02_FundZ7d",     "2019-01-01", lambda d, f, fl: build_b15_02(d, f, fl), "single_fund"),
        ("B15_03_PostShock",   "2017-01-01", lambda d, f, fl: build_b15_03(d, fl),    "single"),
        ("B15_04_AsiaSweep",   "2017-01-01", lambda d, f, fl: build_b15_04(d, fl),    "single"),
        ("B15_05_CorrDecoup",  "2017-01-01", None,                                    "pair"),
        ("B15_06_HiChopKC",    "2017-01-01", lambda d, f, fl: build_b15_06(d, fl),    "single"),
        ("B15_07_TurnOfMonth", "2017-01-01", lambda d, f, fl: build_b15_07(d, fl),    "single"),
        ("B15_08_FundFlip",    "2019-01-01", lambda d, f, fl: build_b15_08(d, f, fl), "single_fund"),
        ("B15_09_BlowoffShort","2017-01-01", lambda d, f, fl: build_b15_09(d, fl),    "single"),
        ("B15_10_CrashLong",   "2017-01-01", lambda d, f, fl: build_b15_10(d, fl),    "single"),
        ("B15_11_SunVacFade",  "2017-01-01", lambda d, f, fl: build_b15_11(d, fl),    "single"),
        ("B15_12_RatioBB",     "2017-01-01", None,                                    "pair"),
        ("B15_13_Consec6Bar",  "2017-01-01", lambda d, f, fl: build_b15_13(d, fl),    "single"),
        ("B15_14_VWAP48Fade",  "2017-01-01", lambda d, f, fl: build_b15_14(d, fl),    "single"),
        ("B15_15_LiqNegFund",  "2019-01-01", lambda d, f, fl: build_b15_15(d, f, fl), "single_fund"),
    ]

    summary_rows = []
    btc_trade_book: dict[str, list[dict]] = {}
    verdicts_lines = []

    for name, start_dt, fn, mode in specs:
        if mode == "single":
            tr_btc = fn(btc_1h, None, False)
            tr_flip = fn(btc_1h, None, True)
            tr_eth = fn(eth_1h, None, False)
        elif mode == "single_fund":
            tr_btc = fn(btc_1h, btc_fund, False)
            tr_flip = fn(btc_1h, btc_fund, True)
            tr_eth = fn(eth_1h, eth_fund, False)
        elif mode == "pair":
            if name == "B15_05_CorrDecoup":
                tr_btc = build_b15_05(btc_1h, eth_1h, False)
                tr_flip = build_b15_05(btc_1h, eth_1h, True)
                tr_eth = build_b15_05(eth_1h, btc_1h, False)
            elif name == "B15_12_RatioBB":
                tr_btc = build_b15_12(btc_1h, eth_1h, False)
                tr_flip = build_b15_12(btc_1h, eth_1h, True)
                tr_eth = build_b15_12(eth_1h, btc_1h, False)

        t_cut = osl.ms(start_dt)
        tr_btc = [t for t in tr_btc if t["exit_time"] >= t_cut]
        tr_flip = [t for t in tr_flip if t["exit_time"] >= t_cut]
        tr_eth = [t for t in tr_eth if t["exit_time"] >= t_cut]
        btc_trade_book[name] = tr_btc

        m_btc = compute_metrics(tr_btc, start=start_dt)
        m_flip = compute_metrics(tr_flip, start=start_dt)
        m_eth = compute_metrics(tr_eth, start=start_dt)

        plc_pct = placebo_pf_percentile(tr_btc, m_btc["pf"], n_runs=100)
        d_idea = idea_daily_R(tr_btc, start=start_dt)
        c_k8 = daily_corr(d_idea, k8_daily_r)
        c_bsk = daily_corr(d_idea, bsk_daily_r)

        fails = []
        if not (np.isfinite(m_btc["pf_h1"]) and m_btc["pf_h1"] > 1.3):
            fails.append(f"PF_17_20={osl.fmt(m_btc['pf_h1'], 2)}<=1.3")
        if not (np.isfinite(m_btc["pf_h2"]) and m_btc["pf_h2"] > 1.3):
            fails.append(f"PF_21_26={osl.fmt(m_btc['pf_h2'], 2)}<=1.3")
        if m_btc["n"] < 30:
            fails.append(f"n={m_btc['n']}<30")
        if not (np.isfinite(plc_pct) and plc_pct >= 90.0):
            fails.append(f"placebo_pct={osl.fmt(plc_pct, 0)}<90")
        if not (np.isfinite(m_flip["pf"]) and m_flip["pf"] < 1.0):
            fails.append(f"flip_PF={osl.fmt(m_flip['pf'], 2)}>=1.0")
        if not (np.isfinite(m_eth["pf"]) and m_eth["pf"] > 1.0):
            fails.append(f"ETH_PF={osl.fmt(m_eth['pf'], 2)}<=1.0")
        if not (np.isfinite(c_bsk) and c_bsk < 0.3):
            fails.append(f"corrBsk={osl.fmt(c_bsk, 2)}>=0.3")

        status = "KEEP" if not fails else "DROP"
        summary_rows.append({
            "idea": name,
            "status": status,
            "n": m_btc["n"],
            "win%": osl.fmt(m_btc["win"], 1),
            "PF": osl.fmt(m_btc["pf"], 2),
            "avgR": osl.fmt(m_btc["avgR"], 3),
            "ret%": osl.fmt(m_btc["ret"], 1),
            "maxDD%": osl.fmt(m_btc["maxDD"], 1),
            "avgGross%": osl.fmt(m_btc["avg_gross_pct"], 2),
            "PF_17_20": f"{osl.fmt(m_btc['pf_h1'], 2)}({m_btc['n_h1']})",
            "PF_21_26": f"{osl.fmt(m_btc['pf_h2'], 2)}({m_btc['n_h2']})",
            "plc_pct": osl.fmt(plc_pct, 0),
            "flip_PF": osl.fmt(m_flip["pf"], 2),
            "ETH_PF": osl.fmt(m_eth["pf"], 2),
            "corrK8": osl.fmt(c_k8, 2),
            "corrBsk": osl.fmt(c_bsk, 2),
        })
        if status == "KEEP":
            verdicts_lines.append(
                f"KEEP  {name}: n={m_btc['n']}, PF={osl.fmt(m_btc['pf'],2)} "
                f"(H1={osl.fmt(m_btc['pf_h1'],2)}, H2={osl.fmt(m_btc['pf_h2'],2)}), "
                f"plc={osl.fmt(plc_pct,0)}%, flipPF={osl.fmt(m_flip['pf'],2)}, "
                f"ETH_PF={osl.fmt(m_eth['pf'],2)}, corrBsk={osl.fmt(c_bsk,2)}."
            )
        else:
            verdicts_lines.append(f"DROP  {name}: failed {', '.join(fails)}.")

    df_res = pd.DataFrame(summary_rows)
    print("\n=== BATCH 15 FULL RESULTS TABLE (0.12%/side taker both legs, 1% risk) ===")
    print(df_res.to_string(index=False))

    keeps = df_res[df_res["status"] == "KEEP"]["idea"].tolist()
    print("\n=== PAIRWISE TRADE-OVERLAP % AMONG KEEPs ===")
    if len(keeps) >= 2:
        ov_mat = pd.DataFrame(index=keeps, columns=keeps, dtype=float)
        for a in keeps:
            for b in keeps:
                ov_mat.loc[a, b] = 100.0 if a == b else round(pairwise_overlap_pct(btc_trade_book[a], btc_trade_book[b]), 1)
        print(ov_mat.to_string())
    elif len(keeps) == 1:
        print(f"Only 1 KEEP ({keeps[0]}); pairwise overlap N/A.")
    else:
        print("0 ideas passed all KEEP criteria; no pairwise overlap matrix.")

    print("\n=== ONE-LINE VERDICTS ===")
    for line in verdicts_lines:
        print(" ", line)


if __name__ == "__main__":
    main()
