#!/usr/bin/env python3
"""Batch14.py — Standalone Colab backtest of Batch 14 orthogonal BTC/ETH ideas using oslib.py."""
from __future__ import annotations

import os
import sys
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, engines, simulate, evaluate, verdict, report,
    atr, ema, sma, rsi, bb_width, resample_ohlcv,
    H1, H4, D1, COST, RISK, LIVE_ENGINES, 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}"

# ==============================================================================
# Helper utilities (strictly built on oslib primitives & 1h/4h/1d dataframes)
# ==============================================================================

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) -> tuple[np.ndarray, np.ndarray, np.ndarray | None, np.ndarray | None]:
    """Place 4H bar-close signals onto the last 1H bar of each completed 4H bucket so
    oslib.simulate(..., entry='next_open') fills at the exact next 4H open."""
    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 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]:
    """Bar-accurate 1H simulator matching oslib.simulate (0.12%/side COST, stop-first intrabar,
    next_open entry) with support for condition-based exits evaluated on bar close (filled next 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)
    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:
    """Strictly causal alignment: latest funding rate whose timestamp <= bar close time (t + period)."""
    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]]
    # Do not leak stale funding before funding data begins (>16h gap)
    stale = valid & ((bar_close - ft[np.maximum(idx, 0)]) > 16 * H1)
    out[stale] = np.nan
    return out


# ==============================================================================
# Idea Builders (Ideas 1, 3, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)
# ==============================================================================

def build_idea_01(df_1h: pd.DataFrame, fund_df: pd.DataFrame, flip_dir: bool = False) -> list[dict]:
    """Idea 1: Negative Funding Capitulation Snapback (4H, 2019+ funding).
    Entry: FR <= -0.0005 AND FR < Percentile_180(FR, 5) AND C < EMA20(C) - 1.5*ATR14.
    Stop: Entry - 2.2*ATR14. Exit: FR >= 0.00005 OR C >= EMA20(C), max hold 12 bars (48H)."""
    d4 = resample_ohlcv(df_1h, H4)
    c4 = d4["close"].to_numpy(dtype=float)
    h4 = d4["high"].to_numpy(dtype=float)
    l4 = d4["low"].to_numpy(dtype=float)
    fr4 = align_funding_to_bars(d4["time"].to_numpy(dtype="int64"), H4, fund_df)
    e20 = ema(c4, 20)
    a14 = atr(h4, l4, c4, 14)
    p5 = pd.Series(fr4).rolling(180, min_periods=90).quantile(0.05).to_numpy()

    cond_long = np.isfinite(fr4) & np.isfinite(p5) & np.isfinite(e20) & np.isfinite(a14) &                 (fr4 <= -0.0005) & (fr4 < p5) & (c4 < (e20 - 1.5 * a14))
    sig4 = np.where(cond_long, (-1 if flip_dir else 1), 0).astype(int)
    # Approximate stop price at signal close for next-open entry
    stp4 = np.where(sig4 > 0, c4 - 2.2 * a14, np.where(sig4 < 0, c4 + 2.2 * a14, np.nan))
    ex4 = (np.isfinite(fr4) & (fr4 >= 0.00005)) | (np.isfinite(e20) & (c4 >= e20))

    sig1, stp1, _, ex1 = map_4h_to_1h(df_1h, d4, sig4, stp4, exit_cond_4h=ex4)
    return simulate_with_soft_exit(df_1h, sig1, stp1, time_stop=48, soft_exit_L=ex1, soft_exit_S=ex1, src="I01_NegFundSnap")


def build_idea_03(df_1h: pd.DataFrame, flip_dir: bool = False) -> list[dict]:
    """Idea 3: Weekend-to-Monday CME-Proxy Drift Fade (1H).
    Entry: Monday 00:00 UTC open (signal on Sun 23:00 UTC bar close).
           Weekend return = (C_Sun23 - C_Fri21) / C_Fri21. >= +3% -> SHORT; <= -3% -> LONG.
    Stop: 1.5 * |Weekend Return| away from entry (capped at 4.5% max loss).
    Exit: Monday 14:30 UTC (14:00 bar close / 15:00 open -> 14 bars hold) OR 70% retracement."""
    t = df_1h["time"].to_numpy(dtype="int64")
    c = df_1h["close"].to_numpy(dtype=float)
    o = df_1h["open"].to_numpy(dtype=float)
    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)

    fri21_close = np.nan
    for i in range(n):
        if dow[i] == 4 and hr[i] == 21:
            fri21_close = c[i]
        elif dow[i] == 6 and hr[i] == 23 and np.isfinite(fri21_close) and fri21_close > 0 and i + 1 < n:
            wk_ret = (c[i] - fri21_close) / fri21_close
            if abs(wk_ret) >= 0.03:
                s = -1 if wk_ret >= 0.03 else 1
                if flip_dir:
                    s = -s
                sig[i] = s
                next_o = o[i + 1]
                stop_pct = min(0.045, 1.5 * abs(wk_ret))
                stp_px[i] = next_o * (1.0 - s * stop_pct)
                move_pts = abs(c[i] - fri21_close)
                tgt_px[i] = next_o + s * (0.70 * move_pts)
            fri21_close = np.nan

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


def build_idea_06(df_btc_1h: pd.DataFrame, df_eth_1h: pd.DataFrame, flip_dir: bool = False) -> list[dict]:
    """Idea 6: ETH/BTC Ratio Lead-Lag Catch-Up (4H).
    Entry: R = C_ETH/C_BTC. Long BTC if (R_t - R_{t-6})/R_{t-6} >= +3.5% AND
           BTC 6-bar return in [-1%, +1%] AND C_BTC > SMA50(C_BTC).
    Stop: Entry - 1.8*ATR14. Exit: 6 bars (24H) OR +2.2*ATR14 target."""
    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)

    ratio = ce / np.maximum(cb, 1e-12)
    r_chg = (ratio - np.roll(ratio, 6)) / np.maximum(np.roll(ratio, 6), 1e-12)
    b_chg = (cb - np.roll(cb, 6)) / np.maximum(np.roll(cb, 6), 1e-12)
    r_chg[:6] = np.nan
    b_chg[:6] = np.nan
    s50 = sma(cb, 50)
    a14 = atr(hb, lb, cb, 14)

    cond = np.isfinite(r_chg) & np.isfinite(s50) & np.isfinite(a14) &            (r_chg >= 0.035) & (b_chg >= -0.01) & (b_chg <= 0.01) & (cb > s50)
    sig4 = np.where(cond, (-1 if flip_dir else 1), 0).astype(int)
    stp4 = np.where(sig4 > 0, cb - 1.8 * a14, np.where(sig4 < 0, cb + 1.8 * a14, np.nan))
    tgt4 = np.where(sig4 > 0, cb + 2.2 * a14, np.where(sig4 < 0, cb - 2.2 * a14, np.nan))

    sig1, stp1, tgt1, _ = map_4h_to_1h(df_btc_1h, m, sig4, stp4, target_px_4h=tgt4)
    return simulate(df_btc_1h, sig1, stop=stp1, target=tgt1, time_stop=24, entry="next_open", check=False)


def build_idea_07(df_1h: pd.DataFrame, flip_dir: bool = False) -> list[dict]:
    """Idea 7: US Session Open Overreaction Fade (1H).
    Entry: Measure 08:00..13:00 close move d_EU = (C_13 - O_08)/O_08.
           At 14:00 UTC close, if d_EU >= +2.2% AND (C_14 - O_14) < 0 -> SHORT;
           if d_EU <= -2.2% AND (C_14 - O_14) > 0 -> LONG.
    Stop: max(H_08..14) + 0.5*ATR14 (short) or min(L_08..14) - 0.5*ATR14 (long).
    Exit: 20:00 UTC (5 bars hold from 15:00 open) OR 60% retracement of d_EU."""
    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)

    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(6, n - 1):
        if hr[i] == 14 and day_id[i] == day_id[i - 6] and hr[i - 6] == 8 and np.isfinite(a14[i]):
            o08 = o[i - 6]
            c13 = c[i - 1]
            d_eu = (c13 - o08) / o08
            s = 0
            if d_eu >= 0.022 and (c[i] - o[i]) < 0:
                s = -1
            elif d_eu <= -0.022 and (c[i] - o[i]) > 0:
                s = 1
            if s != 0:
                if flip_dir:
                    s = -s
                sig[i] = s
                hi_win = np.max(h[i - 6:i + 1])
                lo_win = np.min(l[i - 6:i + 1])
                stp_px[i] = (hi_win + 0.5 * a14[i]) if s < 0 else (lo_win - 0.5 * a14[i])
                tgt_px[i] = o[i + 1] + s * 0.60 * abs(c13 - o08)

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


def build_idea_08_check_only(df_1h: pd.DataFrame) -> bool:
    """Idea 8 requires TakerBuyQuoteAssetVolume, which is absent in oslib's normalized OHLCV schema."""
    cols = {c.lower() for c in df_1h.columns}
    return any("taker" in c for c in cols)


def build_idea_09(df_1h: pd.DataFrame, flip_dir: bool = False) -> list[dict]:
    """Idea 9: Bear-Regime Relief Rally Fader (4H + Daily regime).
    Entry: Daily C_d < SMA100(C_d) AND SMA20(C_d) < SMA100(C_d).
           On 4H close, SHORT when RSI4(C) >= 85 AND C > BB_upper(20, 2.0).
    Stop: Entry + 2.0*ATR14. Exit: C <= SMA20(C) OR RSI4(C) <= 30, max hold 18 bars (72H)."""
    d1 = resample_ohlcv(df_1h, D1)
    dc = d1["close"].to_numpy(dtype=float)
    ds20 = sma(dc, 20)
    ds100 = sma(dc, 100)
    bear_d = np.isfinite(ds100) & (dc < ds100) & (ds20 < ds100)

    d4 = resample_ohlcv(df_1h, H4)
    c4 = d4["close"].to_numpy(dtype=float)
    h4 = d4["high"].to_numpy(dtype=float)
    l4 = d4["low"].to_numpy(dtype=float)
    r4 = rsi(c4, 4)
    bb_u, bb_m, _, _ = bb_width(c4, 20, 2.0)
    a14 = atr(h4, l4, c4, 14)

    # Map completed daily regime onto 4H bars causally
    d_close_ms = d1["time"].to_numpy(dtype="int64") + D1
    b4_close_ms = d4["time"].to_numpy(dtype="int64") + H4
    d_idx = np.searchsorted(d_close_ms, b4_close_ms, side="right") - 1
    bear_4h = np.zeros(len(d4), dtype=bool)
    ok = d_idx >= 0
    bear_4h[ok] = bear_d[d_idx[ok]]

    cond = bear_4h & np.isfinite(r4) & np.isfinite(bb_u) & np.isfinite(a14) & (r4 >= 85.0) & (c4 > bb_u)
    sig4 = np.where(cond, (1 if flip_dir else -1), 0).astype(int)
    stp4 = np.where(sig4 < 0, c4 + 2.0 * a14, np.where(sig4 > 0, c4 - 2.0 * a14, np.nan))
    ex4 = (np.isfinite(bb_m) & (c4 <= bb_m)) | (np.isfinite(r4) & (r4 <= 30.0))

    sig1, stp1, _, ex1 = map_4h_to_1h(df_1h, d4, sig4, stp4, exit_cond_4h=ex4)
    return simulate_with_soft_exit(df_1h, sig1, stp1, time_stop=72, soft_exit_L=ex1, soft_exit_S=ex1, src="I09_BearFade")


def build_idea_10(df_1h: pd.DataFrame, fund_df: pd.DataFrame, flip_dir: bool = False) -> list[dict]:
    """Idea 10: Bull-Regime Dip Buyer (4H + Daily regime + 2019+ funding).
    Entry: Daily C_d > SMA100(C_d) AND SMA20(C_d) > SMA100(C_d).
           On 4H close, LONG when RSI4(C) <= 15 AND C < BB_lower(20, 2.0) AND FR <= 0.0001.
    Stop: Entry - 2.2*ATR14. Exit: C >= SMA20(C) OR RSI4(C) >= 70, max hold 18 bars (72H)."""
    d1 = resample_ohlcv(df_1h, D1)
    dc = d1["close"].to_numpy(dtype=float)
    ds20 = sma(dc, 20)
    ds100 = sma(dc, 100)
    bull_d = np.isfinite(ds100) & (dc > ds100) & (ds20 > ds100)

    d4 = resample_ohlcv(df_1h, H4)
    c4 = d4["close"].to_numpy(dtype=float)
    h4 = d4["high"].to_numpy(dtype=float)
    l4 = d4["low"].to_numpy(dtype=float)
    r4 = rsi(c4, 4)
    _, bb_m, bb_l, _ = bb_width(c4, 20, 2.0)
    a14 = atr(h4, l4, c4, 14)
    fr4 = align_funding_to_bars(d4["time"].to_numpy(dtype="int64"), H4, fund_df)

    d_close_ms = d1["time"].to_numpy(dtype="int64") + D1
    b4_close_ms = d4["time"].to_numpy(dtype="int64") + H4
    d_idx = np.searchsorted(d_close_ms, b4_close_ms, side="right") - 1
    bull_4h = np.zeros(len(d4), dtype=bool)
    ok = d_idx >= 0
    bull_4h[ok] = bull_d[d_idx[ok]]

    cond = bull_4h & np.isfinite(r4) & np.isfinite(bb_l) & np.isfinite(a14) & np.isfinite(fr4) &            (r4 <= 15.0) & (c4 < bb_l) & (fr4 <= 0.0001)
    sig4 = np.where(cond, (-1 if flip_dir else 1), 0).astype(int)
    stp4 = np.where(sig4 > 0, c4 - 2.2 * a14, np.where(sig4 < 0, c4 + 2.2 * a14, np.nan))
    ex4 = (np.isfinite(bb_m) & (c4 >= bb_m)) | (np.isfinite(r4) & (r4 >= 70.0))

    sig1, stp1, _, ex1 = map_4h_to_1h(df_1h, d4, sig4, stp4, exit_cond_4h=ex4)
    return simulate_with_soft_exit(df_1h, sig1, stp1, time_stop=72, soft_exit_L=ex1, soft_exit_S=ex1, src="I10_BullDip")


def build_idea_11(df_1h: pd.DataFrame, fund_df: pd.DataFrame, flip_dir: bool = False) -> list[dict]:
    """Idea 11: Funding Settlement Window Front-Run (1H, 2019+ funding).
    Entry: Enter at 07:00, 15:00, or 23:00 UTC (signal at 06:00, 14:00, 22:00 close -> next_open).
           If FR >= +0.0008 -> SHORT; if FR <= -0.0008 -> LONG.
    Stop: Entry +/- 1.2*ATR14. Exit: 08:00/16:00/00:00 UTC close (1 bar hold after fill)."""
    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)
    fr1 = align_funding_to_bars(t, H1, fund_df)
    hr = pd.to_datetime(t, unit="ms", utc=True).hour.to_numpy()

    win_mask = np.isin(hr, [6, 14, 22]) & np.isfinite(fr1) & np.isfinite(a14)
    sig = np.zeros(len(df_1h), dtype=int)
    sig[win_mask & (fr1 >= 0.0008)] = -1
    sig[win_mask & (fr1 <= -0.0008)] = 1
    if flip_dir:
        sig = -sig
    stp_px = np.where(sig != 0, c - sig * 1.2 * a14, np.nan)
    return simulate(df_1h, sig, stop=stp_px, target=None, time_stop=1, entry="next_open", check=False)


def build_idea_12(df_btc_1h: pd.DataFrame, df_eth_1h: pd.DataFrame, flip_dir: bool = False) -> list[dict]:
    """Idea 12: ETH-Led Volatility Shock Contagion Fade (1H).
    Entry: ETH 1H return <= -3.5% AND BTC 1H return <= -1.8% AND ETH lower wick >= 40% -> LONG BTC.
    Stop: L_BTC - 0.5*ATR14. Exit: 4 bars (4H) OR Entry + 1.5*ATR14."""
    m = pd.merge(df_btc_1h, df_eth_1h[["time", "open", "high", "low", "close"]],
                 on="time", how="inner", suffixes=("", "_eth"))
    ob, hb, lb, cb = (m[k].to_numpy(dtype=float) for k in ("open", "high", "low", "close"))
    oe, he, le, ce = (m[k].to_numpy(dtype=float) for k in ("open_eth", "high_eth", "low_eth", "close_eth"))
    a14 = atr(hb, lb, cb, 14)

    ret_e = (ce - oe) / np.maximum(oe, 1e-12)
    ret_b = (cb - ob) / np.maximum(ob, 1e-12)
    rng_e = np.maximum(he - le, 1e-12)
    wick_e = (ce - le) / rng_e

    cond = np.isfinite(a14) & (ret_e <= -0.035) & (ret_b <= -0.018) & (wick_e >= 0.40)
    s = -1 if flip_dir else 1
    sig = np.where(cond, s, 0).astype(int)
    stp_px = np.where(sig > 0, lb - 0.5 * a14, np.where(sig < 0, hb + 0.5 * a14, np.nan))
    tgt_px = np.where(sig != 0, cb + sig * 1.5 * a14, np.nan)
    return simulate(m[["time", "open", "high", "low", "close", "volume"]],
                    sig, stop=stp_px, target=tgt_px, time_stop=4, entry="next_open", check=False)


def build_idea_13(df_1h: pd.DataFrame, flip_dir: bool = False) -> list[dict]:
    """Idea 13: Volatility Spike Range-Midpoint Magnet (4H).
    Entry: (H - L) >= 2.8*ATR20 AND |C - O|/(H - L) <= 0.25.
           LONG if C < (H + L)/2; SHORT if C > (H + L)/2.
    Stop: L - 0.3*ATR20 (long) or H + 0.3*ATR20 (short).
    Exit: C crosses (H_sig + L_sig)/2 OR 6 bars (24H)."""
    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)
    a20 = atr(h4, l4, c4, 20)

    rng = h4 - l4
    mid = 0.5 * (h4 + l4)
    body_ratio = np.abs(c4 - o4) / np.maximum(rng, 1e-12)
    spike = np.isfinite(a20) & (rng >= 2.8 * a20) & (body_ratio <= 0.25)

    sig4 = np.zeros(len(d4), dtype=int)
    sig4[spike & (c4 < mid)] = 1
    sig4[spike & (c4 > mid)] = -1
    if flip_dir:
        sig4 = -sig4

    stp4 = np.where(sig4 > 0, l4 - 0.3 * a20, np.where(sig4 < 0, h4 + 0.3 * a20, np.nan))
    tgt4 = np.where(sig4 != 0, mid, 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=24, entry="next_open", check=False)


def build_idea_14(df_1h: pd.DataFrame, fund_df: pd.DataFrame, flip_dir: bool = False) -> list[dict]:
    """Idea 14: Friday US-Close Weekend Risk-Off Drift (1H, 2019+ funding).
    Entry: Friday 16:00 UTC close (enters 17:00 UTC next_open).
           If (C_Fri16 - O_Mon00)/O_Mon00 >= +5% AND FR >= 0.0003 -> SHORT.
    Stop: Entry + 2.0*ATR14. Exit: Saturday 02:00 UTC (9 bars hold after 17:00 fill)."""
    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)
    fr1 = align_funding_to_bars(t, H1, fund_df)

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

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

    for i in range(len(df_1h)):
        if dow[i] == 0 and hr[i] == 0:
            mon00_open = o[i]
        elif dow[i] == 4 and hr[i] == 16 and np.isfinite(mon00_open) and mon00_open > 0:
            wk_run = (c[i] - mon00_open) / mon00_open
            if wk_run >= 0.05 and np.isfinite(fr1[i]) and fr1[i] >= 0.0003 and np.isfinite(a14[i]):
                s = 1 if flip_dir else -1
                sig[i] = s
                stp_px[i] = c[i] - s * 2.0 * a14[i]
            mon00_open = np.nan

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


def build_idea_15(df_btc_1h: pd.DataFrame, df_eth_1h: pd.DataFrame, flip_dir: bool = False) -> list[dict]:
    """Idea 15: Cross-Pair Volume-Weighted Z-Score Mean Reversion (1H).
    Entry: S_t = ln(C_BTC) - beta * ln(C_ETH) with rolling 120-bar OLS beta;
           Z_t = (S_t - mu_24(S)) / sd_24(S).
           LONG BTC if Z_t <= -2.6 and Z_t > Z_{t-1}; SHORT BTC if Z_t >= +2.6 and Z_t < Z_{t-1}.
    Stop: Entry +/- 2.0*ATR14 (or |Z| >= 4.0 soft/hard check). Exit: Z_t crosses 0.0, max hold 16 bars."""
    m = pd.merge(df_btc_1h, df_eth_1h[["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)

    lx = pd.Series(np.log(np.maximum(ce, 1e-12)))
    ly = pd.Series(np.log(np.maximum(cb, 1e-12)))
    cov = ly.rolling(120, min_periods=120).cov(lx)
    var = lx.rolling(120, min_periods=120).var()
    beta = (cov / var.replace(0.0, np.nan)).to_numpy()

    spread = ly.to_numpy() - beta * lx.to_numpy()
    s_ser = pd.Series(spread)
    mu24 = s_ser.rolling(24, min_periods=24).mean().to_numpy()
    sd24 = s_ser.rolling(24, min_periods=24).std().to_numpy()
    z = (spread - mu24) / np.where(sd24 > 1e-12, sd24, np.nan)
    zp = np.r_[np.nan, z[:-1]]

    sig = np.zeros(len(m), dtype=int)
    valid = np.isfinite(z) & np.isfinite(zp) & np.isfinite(a14)
    sig[valid & (z <= -2.6) & (z > zp)] = 1
    sig[valid & (z >= 2.6) & (z < zp)] = -1
    if flip_dir:
        sig = -sig

    stp_px = np.where(sig != 0, cb - sig * 2.0 * a14, np.nan)
    ex_L = np.isfinite(z) & ((z >= 0.0) | (np.abs(z) >= 4.0))
    ex_S = np.isfinite(z) & ((z <= 0.0) | (np.abs(z) >= 4.0))

    df_aligned = m[["time", "open", "high", "low", "close", "volume"]].copy()
    return simulate_with_soft_exit(df_aligned, sig, stp_px, time_stop=16, soft_exit_L=ex_L, soft_exit_S=ex_S, src="I15_PairZ")


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

def placebo_pf_percentile(trades: list[dict], real_pf: float, n_runs: int = 100, seed: int = 20261122) -> float:
    """100 shuffled-side placebo runs on the exact trade R stream (preserving entry/exit/friction
    magnitude while randomizing directional sign)."""
    if not trades or not np.isfinite(real_pf):
        return np.nan
    rng = np.random.default_rng(seed)
    r_vals = np.array([float(t["R"]) for t in trades if np.isfinite(t.get("R", np.nan))], dtype=float)
    if len(r_vals) == 0:
        return np.nan
    # Recover gross signed R before round-trip fee drag so sign flips properly pay fees
    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 trades if np.isfinite(t.get("R", np.nan))
    ], 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:
    """Risk-weighted daily R stream of the full live oslib basket."""
    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:
    """Percentage of trades in A whose [entry_time, exit_time] interval overlaps any trade in B."""
    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 14: Orthogonal Mean-Reversion / Session / Funding / Multi-Asset Suite ===", 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)

    # Check Idea 8 taker-buy column availability
    has_taker_vol = build_idea_08_check_only(btc_1h)

    specs = [
        ("I01_NegFundSnap",   "2019-01-01", lambda d, f, fl: build_idea_01(d, f, fl), "single_fund"),
        ("I03_WkndMonFade",   "2017-01-01", lambda d, f, fl: build_idea_03(d, fl),    "single"),
        ("I06_EthBtcLag",     "2017-01-01", None,                                      "pair"),
        ("I07_UsOpenFade",    "2017-01-01", lambda d, f, fl: build_idea_07(d, fl),    "single"),
        ("I08_TakerAbsorb",   "2017-01-01", None,                                      "skip_taker"),
        ("I09_BearRallyFade", "2017-01-01", lambda d, f, fl: build_idea_09(d, fl),    "single"),
        ("I10_BullDipBuy",    "2019-01-01", lambda d, f, fl: build_idea_10(d, f, fl), "single_fund"),
        ("I11_FundFrontRun",  "2019-01-01", lambda d, f, fl: build_idea_11(d, f, fl), "single_fund"),
        ("I12_EthShockFade",  "2017-01-01", None,                                      "pair"),
        ("I13_VolMidMagnet",  "2017-01-01", lambda d, f, fl: build_idea_13(d, fl),    "single"),
        ("I14_FriRiskOff",    "2019-01-01", lambda d, f, fl: build_idea_14(d, f, fl), "single_fund"),
        ("I15_CrossPairZ",    "2017-01-01", None,                                      "pair"),
    ]

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

    for name, start_dt, fn, mode in specs:
        if mode == "skip_taker" and not has_taker_vol:
            print(f"\n[{name}] SKIPPED — TakerBuyQuoteAssetVolume not present in oslib OHLCV data.")
            summary_rows.append({
                "idea": name, "status": "SKIPPED", "n": 0, "win%": "-", "PF": "-",
                "avgR": "-", "ret%": "-", "maxDD%": "-", "avgGross%": "-",
                "PF_17_20": "-", "PF_21_26": "-", "plc_pct": "-", "flip_PF": "-",
                "ETH_PF": "-", "corrK8": "-", "corrBsk": "-"
            })
            verdicts_lines.append(f"SKIP  {name}: TakerBuyQuoteAssetVolume unavailable in oslib data.")
            continue

        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 == "I06_EthBtcLag":
                tr_btc = build_idea_06(btc_1h, eth_1h, False)
                tr_flip = build_idea_06(btc_1h, eth_1h, True)
                tr_eth = build_idea_06(eth_1h, btc_1h, False)
            elif name == "I12_EthShockFade":
                tr_btc = build_idea_12(btc_1h, eth_1h, False)
                tr_flip = build_idea_12(btc_1h, eth_1h, True)
                tr_eth = build_idea_12(eth_1h, btc_1h, False)
            elif name == "I15_CrossPairZ":
                tr_btc = build_idea_15(btc_1h, eth_1h, False)
                tr_flip = build_idea_15(btc_1h, eth_1h, True)
                tr_eth = build_idea_15(eth_1h, btc_1h, False)

        # Restrict evaluation to start_dt (2017+ or 2019+ for funding ideas)
        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)

        # Strict KEEP criteria:
        # BTC PF > 1.3 in BOTH halves, n >= 30, placebo percentile >= 90,
        # flipped PF < 1, ETH PF > 1.0, corr with basket < 0.3
        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 14 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()
