# ===== sessions.py - BTC/ETH session study: when the day's high/low is made, which way, which session =====
# Colab:  !wget -q -O sessions.py https://osom-boba.pages.dev/colab/sessions.py
#         %run sessions.py
# Box (synthetic smoke only):  python3 sessions.py --smoke
#
# Sessions (UTC): Asia 00-08, London 08-13, NY 13-21, late 21-24. Days are UTC calendar days with all 24 1h bars.
# Headline BTC 2017+, halves 2017-20 / 2021-26, ETH repeat. Costs 0.12%/side (oslib.COST), 1% risk, next-bar fills,
# stop wins when a bar touches stop and target. Minimum stop distance 0.25% of entry for every trade test.
# 1) hour of daily high/low (by session, weekday, halves); P(high/low already set by end of Asia / London)
# 2) conditional direction: Asia sign/quintile -> rest of day, NY vs London, first Asia-range break, London 1st hour
# 3) ranges by session in % and daily-ATR units; does a narrow Asia range predict a big NY range
# 4) trade tests (a) London breakout of Asia range (b) NY continuation of London (c) fade a failed first Asia break
#    (d) = (a) with daily SMA50 trend filter
# 5) the 21:30-22:30 UTC hour (3:00-4:00 AM IST): move size and direction (15m bars)
# 6) one-hour boxes: NY 03-04 ET, NY 09-10 ET, 21:30-22:30 UTC (15m bars): range stats, breakout, fade, narrow-box breakout
# 7) stop hunts in thin hours: 1h wick >= 0.3 ATR14(1h) beyond the prior 24h high/low, close back inside within
#    1-3 bars, fade it (stop beyond wick, target 2R or opposite 24h extreme, 24h time stop); thin vs liquid hours.
# Placebo: 100 random entries per test, same days/session window, same hold, same stop distance, random side.
# KEEP gates: PF > 1.3 in both halves, n >= 30, placebo >= 90, ETH PF > 1.0, |corr| vs live basket < 0.3.
import os, sys, time, subprocess, traceback
from pathlib import Path

T0 = time.time()
BASE_URL = "https://osom-boba.pages.dev/colab/"
try:
    _HERE = Path(__file__).resolve().parent
except Exception:
    _HERE = Path.cwd()

def _download(name):
    here = Path.cwd() / name
    url = BASE_URL + name + "?nc=" + str(int(time.time()))
    tmp = Path(str(here) + ".tmp")
    try:
        try:
            subprocess.run(["wget", "-q", "-O", str(tmp), url], check=True)
        except Exception:
            from urllib.request import urlopen, Request
            tmp.write_bytes(urlopen(Request(url, headers={"User-Agent": "osom-sessions/1.0"}), timeout=120).read())
        if tmp.stat().st_size < 1000:
            raise RuntimeError("download too small")
        os.replace(str(tmp), str(here))
    except Exception as ex:
        if not here.exists():
            raise
        print(f"  could not refresh {name} ({type(ex).__name__}); using the local copy", flush=True)

def _need(name, refresh):
    if not refresh:
        for d in (Path.cwd(), _HERE):
            if (d / name).exists():
                if str(d) not in sys.path:
                    sys.path.insert(0, str(d))
                return
        print(f"{name} missing -> downloading " + BASE_URL + name, flush=True)
    _download(name)
    if str(Path.cwd()) not in sys.path:
        sys.path.insert(0, str(Path.cwd()))

_need("oslib.py", Path("/content").exists())
import numpy as np
import pandas as pd
import oslib
from oslib import load, funding, engines, atr, sma, in_colab, synthetic_1h, synthetic_15m_from_1h, LIVE_RISK, COST, H1, D1, M15

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

NAN = np.nan
START = "2017-01-01"
SPLIT = "2021-01-01"
RISK = 0.01
MINR = 0.0025
N_PLC = 100
SEED = 20261122
SESS = [("Asia", 0, 8), ("London", 8, 13), ("NY", 13, 21), ("late", 21, 24)]
DOW = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
ROWS = []
FIND = []
KEEP = {}

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

T_START, T_SPLIT = ms(START), ms(SPLIT)

def pct(x):
    return "  n/a" if x is None or not np.isfinite(x) else f"{100*x:5.1f}"

def f2(x, nd=2):
    return "n/a" if x is None or not np.isfinite(x) else f"{x:.{nd}f}"

def rec(section, asset, subset, metric, value):
    try:
        v = float(value)
    except Exception:
        v = NAN
    ROWS.append(dict(section=section, asset=asset, subset=subset, metric=metric, value=v))

def prob(mask):
    m = np.asarray(mask, dtype=float)
    m = m[np.isfinite(m)]
    return (m.mean() if len(m) else NAN), len(m)

def zval(p, n):
    return (p - 0.5) / np.sqrt(0.25 / n) if n > 0 and np.isfinite(p) else NAN

def pf_of(R):
    R = np.asarray(R, dtype=float)
    R = R[np.isfinite(R)]
    if not len(R):
        return NAN
    pos, neg = R[R > 0].sum(), -R[R < 0].sum()
    return pos / neg if neg > 0 else (99.0 if pos > 0 else NAN)

# ---------------------------------------------------------------------------
# data shapes
# ---------------------------------------------------------------------------
def day_matrix(df):
    t = df["time"].to_numpy(dtype="int64")
    keep = t >= T_START
    t = t[keep]
    cols = {k: df[k].to_numpy(dtype=float)[keep] for k in ("open", "high", "low", "close", "volume") if k in df}
    di = t // D1
    hr = ((t % D1) // H1).astype(int)
    days, inv = np.unique(di, return_inverse=True)
    out = {}
    for k, nm in (("open", "O"), ("high", "H"), ("low", "L"), ("close", "C")):
        m = np.full((len(days), 24), NAN)
        m[inv, hr] = cols[k]
        out[nm] = m
    ok = np.isfinite(out["O"]).all(1) & np.isfinite(out["H"]).all(1) & np.isfinite(out["L"]).all(1) & np.isfinite(out["C"]).all(1)
    for nm in ("O", "H", "L", "C"):
        out[nm] = out[nm][ok]
    day = days[ok] * D1
    out["day"] = day
    dts = pd.to_datetime(day, unit="ms", utc=True)
    out["dow"] = dts.dayofweek.to_numpy()
    out["year"] = dts.year.to_numpy()
    dO, dH, dL, dC = out["O"][:, 0], out["H"].max(1), out["L"].min(1), out["C"][:, 23]
    out.update(dO=dO, dH=dH, dL=dL, dC=dC)
    a = atr(dH, dL, dC, 14)
    out["atr_prev"] = np.r_[NAN, a[:-1]]
    s50 = sma(dC, 50)
    out["trend"] = np.r_[0, np.where(np.isfinite(s50[:-1]), np.sign(dC[:-1] - s50[:-1]), 0)].astype(int)
    out["h1"] = day < T_SPLIT
    return out

def subsets(DM):
    return [("all", np.ones(len(DM["day"]), bool)), ("17-20", DM["h1"]), ("21-26", ~DM["h1"])]

def first_true(mask):
    """index of the first True per row, or -1"""
    anyv = mask.any(1)
    return np.where(anyv, mask.argmax(1), -1)

def box_matrix(d15, starts, K):
    t = d15["time"].to_numpy(dtype="int64")
    starts = np.asarray(starts, dtype="int64")
    pos = np.searchsorted(t, starts)
    okp = pos + K - 1 < len(t)
    pos_c = np.where(okp, pos, 0)
    ok = okp & (t[pos_c] == starts) & (t[np.minimum(pos_c + K - 1, len(t) - 1)] == starts + (K - 1) * M15)
    idx = pos_c[ok][:, None] + np.arange(K)[None, :]
    out = {nm: d15[k].to_numpy(dtype=float)[idx] for k, nm in (("open", "O"), ("high", "H"), ("low", "L"), ("close", "C"))}
    out["start"] = starts[ok]
    out["day"] = (starts[ok] // D1) * D1
    return out

# ---------------------------------------------------------------------------
# vectorised simulators (matrix rows = days, next-bar fill at O[e], stop wins, exit at C[xcol])
# ---------------------------------------------------------------------------
def sim_mat(M, d, e, side, stop, xcol, tgt=None):
    d = np.asarray(d, int); e = np.asarray(e, int); side = np.asarray(side, float); stop = np.asarray(stop, float)
    n = len(d)
    if n == 0:
        return dict(R=np.array([]), risk=np.array([]), ret=np.array([]))
    O, H, L, C = M["O"][d], M["H"][d], M["L"][d], M["C"][d]
    K = O.shape[1]
    cols = np.arange(K)[None, :]
    act = (cols >= e[:, None]) & (cols <= xcol)
    s = side[:, None]
    hit = act & np.where(s > 0, L <= stop[:, None], H >= stop[:, None])
    r = np.arange(n)
    entry = O[r, e]
    fh = first_true(hit)
    ex = C[r, np.full(n, xcol)]
    sx = np.where(side > 0, np.minimum(O[r, np.maximum(fh, 0)], stop), np.maximum(O[r, np.maximum(fh, 0)], stop))
    if tgt is not None:
        tgt = np.asarray(tgt, float)
        th = first_true(act & np.where(s > 0, H >= tgt[:, None], L <= tgt[:, None]))
        tx = np.where(side > 0, np.maximum(O[r, np.maximum(th, 0)], tgt), np.minimum(O[r, np.maximum(th, 0)], tgt))
        use_t = (th >= 0) & ((fh < 0) | (th < fh))
        ex = np.where(use_t, tx, ex)
        ex = np.where((fh >= 0) & ~use_t, sx, ex)
    else:
        ex = np.where(fh >= 0, sx, ex)
    ret = side * (ex / entry - 1.0) - 2 * COST
    risk = np.abs(entry - stop) / entry
    return dict(R=ret / risk, risk=risk, ret=ret)

def adj_stop(entry, side, raw):
    entry, side, raw = np.asarray(entry, float), np.asarray(side, float), np.asarray(raw, float)
    return np.where(side > 0, np.minimum(raw, entry * (1 - MINR)), np.maximum(raw, entry * (1 + MINR)))

def placebo_mat(M, d, risk, w0, w1, xcol, rng, n_plc=N_PLC):
    d = np.asarray(d, int); risk = np.asarray(risk, float)
    if len(d) < 5:
        return np.array([])
    w1 = min(w1, xcol)
    dd = np.tile(d, n_plc)
    rr = np.tile(risk, n_plc)
    e = rng.integers(w0, w1 + 1, len(dd))
    side = rng.choice([-1.0, 1.0], len(dd))
    entry = M["O"][dd, e]
    stop = entry * (1 - side * rr)
    R = sim_mat(M, dd, e, side, stop, xcol)["R"].reshape(n_plc, len(d))
    return np.array([pf_of(x) for x in R])

def plc_pct(pf_act, pfs):
    pfs = np.asarray(pfs, float)
    pfs = pfs[np.isfinite(pfs)]
    if not len(pfs) or not np.isfinite(pf_act):
        return NAN
    return 100.0 * np.mean(pfs < pf_act)

# ---------------------------------------------------------------------------
# live basket daily pnl and correlation
# ---------------------------------------------------------------------------
def basket_daily(df, fund):
    eng = engines(df, fund=fund)
    pn = {}
    for nm, trs in eng.items():
        rk = LIVE_RISK.get(nm, RISK)
        for t in trs:
            r, R, xt = t.get("risk", NAN), t.get("R", NAN), t.get("exit_time", 0)
            if np.isfinite(r) and r > 0 and np.isfinite(R) and xt >= T_START:
                k = (int(xt) // D1) * D1
                pn[k] = pn.get(k, 0.0) + R * min(rk, r)
    print("    live basket: " + " ".join(f"{k} {len(v)}" for k, v in eng.items()), flush=True)
    return pd.Series(pn, dtype=float).sort_index()

def corr_vs(basket, day, R, risk, all_days):
    if basket is None or not len(R):
        return NAN
    idea = pd.Series(np.asarray(R) * np.minimum(RISK, np.asarray(risk)), index=np.asarray(day, "int64")).groupby(level=0).sum()
    idx = pd.Index(np.asarray(all_days, "int64"))
    a = basket.reindex(idx).fillna(0.0).to_numpy()
    b = idea.reindex(idx).fillna(0.0).to_numpy()
    if a.std() == 0 or b.std() == 0:
        return NAN
    return float(np.corrcoef(a, b)[0, 1])

# ---------------------------------------------------------------------------
# test bookkeeping
# ---------------------------------------------------------------------------
TEST_HDR = f"  {'test':<34} {'n':>5} {'win%':>6} {'PF':>5} {'avgR':>6} {'PF17-20':>8} {'PF21-26':>8} {'ETH n':>6} {'ETH PF':>7} {'plc':>5} {'corr':>6}  verdict"

def eval_test(sec, name, res):
    """res: dict asset -> dict(R, day, risk, plc_pfs, corr)"""
    b, e = res.get("btc"), res.get("eth")
    if b is None:
        print(f"  {name:<34} no BTC trades", flush=True)
        return
    R, day = np.asarray(b["R"], float), np.asarray(b["day"], "int64")
    n = len(R)
    win = np.mean(R > 0) if n else NAN
    pf = pf_of(R); avg = np.nanmean(R) if n else NAN
    p1, p2 = pf_of(R[day < T_SPLIT]), pf_of(R[day >= T_SPLIT])
    epf = pf_of(e["R"]) if e is not None else NAN
    en = len(e["R"]) if e is not None else 0
    plc = plc_pct(pf, b.get("plc_pfs", []))
    cr = b.get("corr", NAN)
    fails = []
    if not (np.isfinite(p1) and p1 > 1.3 and np.isfinite(p2) and p2 > 1.3): fails.append("halves")
    if n < 30: fails.append("n")
    if not (np.isfinite(plc) and plc >= 90): fails.append("placebo")
    if not (np.isfinite(epf) and epf > 1.0): fails.append("ETH")
    if not (np.isfinite(cr) and abs(cr) < 0.3): fails.append("corr")
    v = "KEEP" if not fails else "NO (" + ",".join(fails) + ")"
    KEEP[name] = (v, pf, p1, p2, epf, plc, n)
    print(f"  {name:<34} {n:>5} {pct(win):>6} {f2(pf):>5} {f2(avg):>6} {f2(p1):>8} {f2(p2):>8} {en:>6} {f2(epf):>7} {f2(plc,0):>5} {f2(cr):>6}  {v}", flush=True)
    for k, val in (("n", n), ("win", win), ("PF", pf), ("avgR", avg), ("PF_17_20", p1), ("PF_21_26", p2),
                   ("ETH_PF", epf), ("ETH_n", en), ("placebo", plc), ("corr", cr), ("keep", 1.0 if not fails else 0.0)):
        rec(sec, "btc", name, k, val)

# ---------------------------------------------------------------------------
# SECTION 1: when are the high and low made
# ---------------------------------------------------------------------------
def sess_of(h):
    h = np.asarray(h)
    return np.select([h < 8, h < 13, h < 21], [0, 1, 2], 3)

def section1(ctx):
    print("\n=== 1) WHEN IS THE DAILY HIGH / LOW MADE (UTC hour, first touch on 1h bars) ===", flush=True)
    for a in ("btc", "eth"):
        DM = ctx[a]["DM"]
        hh, hl = DM["H"].argmax(1), DM["L"].argmin(1)
        print(f"  {a.upper()} {'subset':<6} {'days':>5} | high in: " + " ".join(f"{s[0]:>6}" for s in SESS) +
              " | low in: " + " ".join(f"{s[0]:>6}" for s in SESS) + " | set by end Asia H/L/either | by end London H/L/both", flush=True)
        for sn, m in subsets(DM):
            if m.sum() < 5:
                continue
            sh, sl = sess_of(hh[m]), sess_of(hl[m])
            ph = [np.mean(sh == k) for k in range(4)]
            pl = [np.mean(sl == k) for k in range(4)]
            ea = (np.mean(hh[m] < 8), np.mean(hl[m] < 8), np.mean((hh[m] < 8) | (hl[m] < 8)))
            el = (np.mean(hh[m] < 13), np.mean(hl[m] < 13), np.mean((hh[m] < 13) & (hl[m] < 13)))
            print(f"  {a.upper()} {sn:<6} {m.sum():>5} |          " + " ".join(f"{pct(x):>6}" for x in ph) +
                  " |         " + " ".join(f"{pct(x):>6}" for x in pl) +
                  f" | {pct(ea[0])}/{pct(ea[1])}/{pct(ea[2])}           | {pct(el[0])}/{pct(el[1])}/{pct(el[2])}", flush=True)
            for k, s in enumerate(SESS):
                rec("1", a, sn, f"high_in_{s[0]}", ph[k]); rec("1", a, sn, f"low_in_{s[0]}", pl[k])
            rec("1", a, sn, "high_set_by_asia", ea[0]); rec("1", a, sn, "low_set_by_asia", ea[1]); rec("1", a, sn, "either_set_by_asia", ea[2])
            rec("1", a, sn, "high_set_by_london", el[0]); rec("1", a, sn, "low_set_by_london", el[1]); rec("1", a, sn, "both_set_by_london", el[2])
            if a == "btc" and sn == "all":
                FIND.append(f"BTC daily low is made in Asia {100*pl[0]:.0f}% of days, London {100*pl[1]:.0f}%, NY {100*pl[2]:.0f}%, late {100*pl[3]:.0f}%.")
                FIND.append(f"BTC daily high is made in Asia {100*ph[0]:.0f}% of days, London {100*ph[1]:.0f}%, NY {100*ph[2]:.0f}%, late {100*ph[3]:.0f}%.")
                FIND.append(f"By the end of Asia (08 UTC) BTC has already made the day's high or low on {100*ea[2]:.0f}% of days; by the end of London (13 UTC) both are in on {100*el[2]:.0f}% of days.")
        m = np.ones(len(hh), bool)
        hist_h = np.bincount(hh, minlength=24) / len(hh)
        hist_l = np.bincount(hl, minlength=24) / len(hl)
        print(f"  {a.upper()} hour of HIGH %: " + " ".join(f"{h:02d}:{100*hist_h[h]:.1f}" for h in range(24)), flush=True)
        print(f"  {a.upper()} hour of LOW  %: " + " ".join(f"{h:02d}:{100*hist_l[h]:.1f}" for h in range(24)), flush=True)
        for h in range(24):
            rec("1", a, "all", f"high_hour_{h:02d}", hist_h[h]); rec("1", a, "all", f"low_hour_{h:02d}", hist_l[h])
        if a == "btc":
            th, tl = int(hist_h.argmax()), int(hist_l.argmax())
            FIND.append(f"Most common hour for the BTC daily high is {th:02d}:00 UTC ({100*hist_h[th]:.1f}% of days); for the low {tl:02d}:00 UTC ({100*hist_l[tl]:.1f}%). Flat would be 4.2%.")
        print(f"  {a.upper()} by weekday (all days): high in Asia/London/NY/late | low in Asia/London/NY/late", flush=True)
        for w in range(7):
            mw = DM["dow"] == w
            if mw.sum() < 3:
                continue
            sh, sl = sess_of(hh[mw]), sess_of(hl[mw])
            ph = [np.mean(sh == k) for k in range(4)]
            pl = [np.mean(sl == k) for k in range(4)]
            print(f"    {DOW[w]} n {mw.sum():>4} | " + " ".join(pct(x) for x in ph) + " | " + " ".join(pct(x) for x in pl), flush=True)
            for k, s in enumerate(SESS):
                rec("1", a, DOW[w], f"high_in_{s[0]}", ph[k]); rec("1", a, DOW[w], f"low_in_{s[0]}", pl[k])

# ---------------------------------------------------------------------------
# SECTION 2: conditional direction
# ---------------------------------------------------------------------------
def asia_range(DM):
    return DM["H"][:, 0:8].max(1), DM["L"][:, 0:8].min(1)

def first_break(DM, h0, h1, AH, AL, use_close=False):
    """first hour in [h0,h1) that trades (or closes) beyond the Asia range: returns (hour, dir) with dir 0 = none/ambiguous"""
    H, L, C = DM["H"][:, h0:h1], DM["L"][:, h0:h1], DM["C"][:, h0:h1]
    up = (C > AH[:, None]) if use_close else (H > AH[:, None])
    dn = (C < AL[:, None]) if use_close else (L < AL[:, None])
    fu, fd = first_true(up), first_true(dn)
    big = 999
    fu2, fd2 = np.where(fu < 0, big, fu), np.where(fd < 0, big, fd)
    dirv = np.where(fu2 < fd2, 1, np.where(fd2 < fu2, -1, 0))
    hr = np.where(dirv != 0, np.minimum(fu2, fd2) + h0, -1)
    return hr, dirv

def cond_stats(DM, m, h2130=None):
    O, H, L, C = DM["O"][m], DM["H"][m], DM["L"][m], DM["C"][m]
    S = {}
    day_ret = C[:, 23] / O[:, 0] - 1
    asia = C[:, 7] / O[:, 0] - 1
    rest = C[:, 23] / C[:, 7] - 1
    S["P(day up)"] = prob(day_ret > 0)
    S["P(day up | Asia up)"] = prob((day_ret > 0)[asia > 0])
    S["P(day up | Asia down)"] = prob((day_ret > 0)[asia < 0])
    S["P(rest 08-24 up | Asia up)"] = prob((rest > 0)[asia > 0])
    S["P(rest 08-24 up | Asia down)"] = prob((rest > 0)[asia < 0])
    try:
        q = pd.qcut(asia, 5, labels=False, duplicates="drop")
        for k in range(5):
            S[f"P(rest up | Asia ret Q{k+1})"] = prob((rest > 0)[q == k])
    except Exception:
        pass
    lon = C[:, 12] / O[:, 8] - 1
    ny = C[:, 20] / O[:, 13] - 1
    nz = (lon != 0) & (ny != 0)
    S["P(NY dir = London dir)"] = prob((np.sign(lon) == np.sign(ny))[nz])
    sub = {k: DM[k][m] for k in ("O", "H", "L", "C")}
    AH, AL = H[:, 0:8].max(1), L[:, 0:8].min(1)
    hr, dv = first_break(sub, 8, 24, AH, AL)
    S["P(first Asia-range break after 08 is UP)"] = prob((dv > 0)[dv != 0])
    cl = C[:, 23]
    beyond = np.where(dv > 0, cl > AH, cl < AL)
    opp = np.where(dv > 0, cl < AL, cl > AH)
    S["P(day closes beyond broken side)"] = prob(beyond[dv != 0])
    S["P(day closes beyond opposite side)"] = prob(opp[dv != 0])
    S["P(day close-open in break dir)"] = prob((np.sign(day_ret) == dv)[dv != 0])
    hr2, dv2 = first_break(sub, 13, 21, AH, AL)
    S["P(NY breaks Asia HIGH first | NY breaks)"] = prob((dv2 > 0)[dv2 != 0])
    S["P(NY breaks Asia range at all)"] = prob(dv2 != 0)
    b8 = C[:, 8] / O[:, 8] - 1
    after = C[:, 20] / C[:, 8] - 1
    nz8 = (b8 != 0) & (after != 0)
    S["P(08-09 bar dir persists to 21:00)"] = prob((np.sign(b8) == np.sign(after))[nz8])
    bo8 = np.where(C[:, 8] > AH, 1, np.where(C[:, 8] < AL, -1, 0))
    S["P(08 bar closes beyond Asia range)"] = prob(bo8 != 0)
    S["P(close beyond side | 08 bar breakout)"] = prob(np.where(bo8 > 0, cl > AH, cl < AL)[bo8 != 0])
    if h2130 is not None:
        mv = h2130.reindex(DM["day"][m]).to_numpy()
        S["P(21:30-22:30 UTC hour up)"] = prob((mv > 0)[np.isfinite(mv) & (mv != 0)])
        S["21:30-22:30 hour median |move| %"] = (np.nanmedian(np.abs(mv)) * 100 if np.isfinite(mv).any() else NAN, int(np.isfinite(mv).sum()))
    return S

def hour2130_series(d15):
    t = d15["time"].to_numpy(dtype="int64")
    tod = t % D1
    o, c = d15["open"].to_numpy(float), d15["close"].to_numpy(float)
    i = np.where(tod == (21 * 60 + 30) * 60000)[0]
    i = i[(i + 3 < len(t))]
    i = i[t[i + 3] == t[i] + 3 * M15]
    mv = c[i + 3] / o[i] - 1
    return pd.Series(mv, index=(t[i] // D1) * D1)

def section2(ctx):
    print("\n=== 2) CONDITIONAL DIRECTION (UTC days; Asia 00-08, London 08-13, NY 13-21) ===", flush=True)
    cols, stats = [], []
    for a in ("btc", "eth"):
        DM = ctx[a]["DM"]
        for sn, m in subsets(DM):
            if m.sum() < 20:
                continue
            cols.append(f"{a.upper()} {sn}")
            stats.append(cond_stats(DM, m, ctx[a].get("h2130")))
    keys = []
    for s in stats:
        for k in s:
            if k not in keys:
                keys.append(k)
    print(f"  {'metric':<44}" + "".join(f"{c:>13}" for c in cols), flush=True)
    for k in keys:
        cells = []
        for c, s in zip(cols, stats):
            v = s.get(k, (NAN, 0))
            if "median" in k:
                cells.append(f"{f2(v[0], 3):>13}")
            else:
                z = zval(v[0], v[1])
                star = "*" if np.isfinite(z) and abs(z) >= 2.5 else " "
                cells.append(f"{pct(v[0])}{star}n{v[1]:<5}".rjust(13))
            a_, sn_ = c.split(" ")
            rec("2", a_.lower(), sn_, k, v[0])
        print(f"  {k:<44}" + "".join(cells), flush=True)
    print("  (* = |z| >= 2.5 vs a coin flip)", flush=True)
    try:
        b = stats[0]
        FIND.append(f"When BTC's Asia session is up, the rest of the day (08-24 UTC) is up {100*b['P(rest 08-24 up | Asia up)'][0]:.0f}% of the time; after a down Asia {100*b['P(rest 08-24 up | Asia down)'][0]:.0f}% (base rate day up {100*b['P(day up)'][0]:.0f}%).")
        FIND.append(f"BTC NY session moves the same way as London {100*b['P(NY dir = London dir)'][0]:.0f}% of days.")
        FIND.append(f"The first break of the Asia range is to the upside {100*b['P(first Asia-range break after 08 is UP)'][0]:.0f}% of the time; the day closes beyond the broken side {100*b['P(day closes beyond broken side)'][0]:.0f}% and all the way beyond the other side {100*b['P(day closes beyond opposite side)'][0]:.0f}%.")
        FIND.append(f"The direction of the first London hour (08-09 UTC) holds to 21:00 UTC {100*b['P(08-09 bar dir persists to 21:00)'][0]:.0f}% of days.")
    except Exception:
        pass

# ---------------------------------------------------------------------------
# SECTION 3: ranges
# ---------------------------------------------------------------------------
def section3(ctx):
    print("\n=== 3) RANGES: median session range in % of open and in prior-day ATR14 units ===", flush=True)
    print(f"  {'asset subset':<14} {'day %':>6} {'day ATR':>7} | " + " ".join(f"{s[0]+' %':>9} {s[0]+' ATR':>10}" for s in SESS), flush=True)
    for a in ("btc", "eth"):
        DM = ctx[a]["DM"]
        A = DM["atr_prev"]
        for sn, m in subsets(DM):
            m = m & np.isfinite(A)
            if m.sum() < 20:
                continue
            dr = (DM["dH"] - DM["dL"])[m]
            cells = []
            for s, h0, h1 in SESS:
                rng_ = DM["H"][m, h0:h1].max(1) - DM["L"][m, h0:h1].min(1)
                p_, a_ = np.median(rng_ / DM["O"][m, h0]) * 100, np.median(rng_ / A[m])
                cells.append(f"{p_:>9.2f} {a_:>10.2f}")
                rec("3", a, sn, f"{s}_range_pct", p_); rec("3", a, sn, f"{s}_range_atr", a_)
            dp, da = np.median(dr / DM["dO"][m]) * 100, np.median(dr / A[m])
            rec("3", a, sn, "day_range_pct", dp); rec("3", a, sn, "day_range_atr", da)
            print(f"  {a.upper()+' '+sn:<14} {dp:>6.2f} {da:>7.2f} | " + " ".join(cells), flush=True)
        yrs = sorted(set(DM["year"]))
        dr = DM["dH"] - DM["dL"]
        line = []
        for y in yrs:
            my = DM["year"] == y
            line.append(f"{y}: ${np.median(dr[my]):,.0f} ({100*np.median(dr[my]/DM['dO'][my]):.1f}%) {100*np.mean(dr[my] >= 2000):.0f}%>=2k")
            rec("3", a, str(y), "day_range_usd_med", np.median(dr[my])); rec("3", a, str(y), "share_range_ge_2000usd", np.mean(dr[my] >= 2000))
        print(f"  {a.upper()} median daily range by year: " + " | ".join(line), flush=True)
        if a == "btc":
            my = DM["year"] >= DM["year"].max() - 1
            FIND.append(f"BTC median daily high-low range over {DM['year'].max()-1}-{DM['year'].max()}: ${np.median(dr[my]):,.0f} ({100*np.median(dr[my]/DM['dO'][my]):.1f}%); it was >= $2,000 on {100*np.mean(dr[my] >= 2000):.0f}% of those days.")
        # narrow Asia -> NY range
        m = np.isfinite(A)
        ar = (DM["H"][:, 0:8].max(1) - DM["L"][:, 0:8].min(1)) / A
        nr = (DM["H"][:, 13:21].max(1) - DM["L"][:, 13:21].min(1)) / A
        ok = m & np.isfinite(ar) & np.isfinite(nr)
        try:
            q = pd.qcut(ar[ok], 5, labels=False, duplicates="drop")
            med_all = np.median(nr[ok])
            parts = []
            for k in range(5):
                v = nr[ok][q == k]
                parts.append(f"Q{k+1} {np.median(v):.2f} ({100*np.mean(v > med_all):.0f}%>med)")
                rec("3", a, f"asiaQ{k+1}", "ny_range_atr_med", np.median(v)); rec("3", a, f"asiaQ{k+1}", "p_ny_range_above_med", np.mean(v > med_all))
            sp = pd.Series(ar[ok]).corr(pd.Series(nr[ok]), method="spearman")
            rec("3", a, "all", "spearman_asia_vs_ny_range", sp)
            # same but Asia range vs its own trailing 20-day median (narrow relative to recent)
            rel = ar / pd.Series(ar).shift(1).rolling(20, min_periods=10).median().to_numpy()
            okr = ok & np.isfinite(rel)
            nar, wid = nr[okr & (rel < 0.7)], nr[okr & (rel > 1.3)]
            print(f"  {a.upper()} NY range (ATR) by Asia-range quintile (Q1 = narrowest): " + " | ".join(parts) + f" | spearman {sp:.2f}", flush=True)
            print(f"  {a.upper()} Asia range < 0.7x its 20d median: NY range med {np.median(nar):.2f} ATR (n {len(nar)}) vs > 1.3x: {np.median(wid):.2f} ATR (n {len(wid)})", flush=True)
            if a == "btc":
                lo, hi = np.median(nr[ok][q == 0]), np.median(nr[ok][q == 4])
                FIND.append(f"A narrow Asia range does {'NOT ' if lo >= hi else ''}lead to a bigger NY range: NY range is {lo:.2f} ATR after the narrowest-fifth Asia vs {hi:.2f} ATR after the widest (spearman {sp:.2f}).")
        except Exception as ex:
            print(f"  {a.upper()} narrow-Asia test error {type(ex).__name__}: {ex}", flush=True)

# ---------------------------------------------------------------------------
# SECTION 4: trade tests on the 1h day matrix
# ---------------------------------------------------------------------------
def build_a(DM, trend=False):
    AH, AL = asia_range(DM)
    hr, dv = first_break(DM, 8, 13, AH, AL, use_close=True)
    d = np.where(dv != 0)[0]
    side = dv[d].astype(float); e = hr[d] + 1
    if trend:
        k = DM["trend"][d] == side
        d, side, e = d[k], side[k], e[k]
    entry = DM["O"][d, e]
    raw = np.where(side > 0, AL[d], AH[d])
    ok = side * (entry - raw) > 0
    d, side, e, entry, raw = d[ok], side[ok], e[ok], entry[ok], raw[ok]
    return d, e, side, adj_stop(entry, side, raw), (9, 13)

def build_b(DM):
    lon = DM["C"][:, 12] / DM["O"][:, 8] - 1
    d = np.where(lon != 0)[0]
    side = np.sign(lon[d]); e = np.full(len(d), 13)
    entry = DM["O"][d, 13]
    raw = np.where(side > 0, DM["L"][d, 8:13].min(1), DM["H"][d, 8:13].max(1))
    ok = side * (entry - raw) > 0
    d, side, e, entry, raw = d[ok], side[ok], e[ok], entry[ok], raw[ok]
    return d, e, side, adj_stop(entry, side, raw), (13, 13)

def build_fade(M, bh, bl, s0, s1, kfail, last_entry):
    """first close beyond [bl,bh] in cols [s0,s1); if a close back inside within kfail bars, fade at next open; stop beyond the extreme"""
    C, H, L = M["C"], M["H"], M["L"]
    dd, ee, ss, rw = [], [], [], []
    up = C[:, s0:s1] > bh[:, None]; dn = C[:, s0:s1] < bl[:, None]
    fu, fd = first_true(up), first_true(dn)
    for i in range(len(C)):
        u, w = fu[i], fd[i]
        if u < 0 and w < 0:
            continue
        if u >= 0 and (w < 0 or u < w):
            j0, dirv = u + s0, 1
        else:
            j0, dirv = w + s0, -1
        for j in range(j0 + 1, min(j0 + kfail, s1 + kfail - 1, C.shape[1] - 1) + 1):
            back = C[i, j] < bh[i] if dirv > 0 else C[i, j] > bl[i]
            if back:
                if j + 1 <= last_entry:
                    dd.append(i); ee.append(j + 1); ss.append(-dirv)
                    rw.append(H[i, j0:j + 1].max() if dirv > 0 else L[i, j0:j + 1].min())
                break
    d, e, side, raw = np.array(dd, int), np.array(ee, int), np.array(ss, float), np.array(rw, float)
    if not len(d):
        return d, e, side, raw
    entry = M["O"][d, e]
    ok = side * (entry - raw) > 0
    d, e, side, entry, raw = d[ok], e[ok], side[ok], entry[ok], raw[ok]
    return d, e, side, adj_stop(entry, side, raw)

def build_c(DM):
    AH, AL = asia_range(DM)
    d, e, side, stop = build_fade(DM, AH, AL, 8, 20, 2, 20)
    return d, e, side, stop, (9, 20)

def run_mat_test(ctx, sec, name, builder, xcol, mat_key="DM", tgt_fn=None):
    res = {}
    for a in ("btc", "eth"):
        M = ctx[a][mat_key] if isinstance(mat_key, str) else mat_key[a]
        if M is None or not len(M["day"]):
            continue
        d, e, side, stop, (w0, w1) = builder(M)
        if not len(d):
            continue
        out = sim_mat(M, d, e, side, stop, xcol)
        day = M["day"][d]
        r = dict(R=out["R"], day=day, risk=out["risk"])
        if a == "btc":
            r["plc_pfs"] = placebo_mat(M, d, out["risk"], w0, w1, xcol, ctx["rng"])
            r["corr"] = corr_vs(ctx[a].get("basket"), day, out["R"], out["risk"], ctx[a]["DM"]["day"])
        res[a] = r
    eval_test(sec, name, res)
    return res

def section4(ctx):
    print("\n=== 4) TRADE TESTS (1h bars, 1% risk, next-bar fill, stop wins, exit 21:00 UTC unless noted, 0.12%/side) ===", flush=True)
    print(TEST_HDR, flush=True)
    run_mat_test(ctx, "4", "a London breakout of Asia range", lambda M: build_a(M), 20)
    run_mat_test(ctx, "4", "b NY continuation of London dir", build_b, 20)
    run_mat_test(ctx, "4", "c fade failed first Asia break", build_c, 20)
    run_mat_test(ctx, "4", "d (a) + daily SMA50 trend", lambda M: build_a(M, trend=True), 20)

# ---------------------------------------------------------------------------
# SECTION 5: the 21:30-22:30 UTC hour (3:00-4:00 AM IST)
# ---------------------------------------------------------------------------
def section5(ctx):
    print("\n=== 5) THE 21:30-22:30 UTC HOUR (3:00-4:00 AM IST), 15m bars ===", flush=True)
    print(f"  {'asset subset':<14} {'n':>5} {'P(up)':>6} {'med|mv|%':>9} {'mean|mv|%':>10} {'med ATR':>8} {'med $':>8} {'vs avg hr':>9} {'P(next6h same)':>15} {'P(opp NY dir)':>14}", flush=True)
    for a in ("btc", "eth"):
        d15 = ctx[a].get("m15")
        DM = ctx[a]["DM"]
        if d15 is None:
            print(f"  {a.upper()} no 15m data", flush=True)
            continue
        t = d15["time"].to_numpy(dtype="int64")
        o, c, h, l = (d15[k].to_numpy(float) for k in ("open", "close", "high", "low"))
        i = np.where((t % D1) == (21 * 60 + 30) * 60000)[0]
        i = i[i + 27 < len(t)]
        i = i[t[i] >= T_START]
        i = i[t[np.minimum(i + 27, len(t) - 1)] == t[i] + 27 * M15]
        mv = c[i + 3] / o[i] - 1
        usd = c[i + 3] - o[i]
        nxt = c[i + 27] / c[i + 3] - 1
        day = (t[i] // D1) * D1
        di = pd.Series(np.arange(len(DM["day"])), index=DM["day"])
        k = di.reindex(day).to_numpy()
        okk = np.isfinite(k)
        A = np.full(len(i), NAN); nyd = np.full(len(i), NAN)
        kk = k[okk].astype(int)
        A[okk] = DM["atr_prev"][kk]
        nyd[okk] = np.sign(DM["C"][kk, 20] / DM["O"][kk, 13] - 1)
        hr_abs = np.abs(DM["C"] / DM["O"] - 1)
        avg_hr = np.median(hr_abs)
        for sn, m in (("all", np.ones(len(i), bool)), ("17-20", day < T_SPLIT), ("21-26", day >= T_SPLIT)):
            if m.sum() < 10:
                continue
            p_up, n_ = prob((mv[m] > 0)[mv[m] != 0])
            same = prob((np.sign(nxt[m]) == np.sign(mv[m]))[(mv[m] != 0) & (nxt[m] != 0)])[0]
            opp = prob((np.sign(mv[m]) == -nyd[m])[np.isfinite(nyd[m]) & (mv[m] != 0) & (nyd[m] != 0)])[0]
            medm, meanm = np.median(np.abs(mv[m])) * 100, np.mean(np.abs(mv[m])) * 100
            matr = np.nanmedian(np.abs(usd[m]) / A[m]) if np.isfinite(A[m]).any() else NAN
            mus = np.median(np.abs(usd[m]))
            ratio = np.median(np.abs(mv[m])) / avg_hr if avg_hr > 0 else NAN
            print(f"  {a.upper()+' '+sn:<14} {m.sum():>5} {pct(p_up):>6} {medm:>9.3f} {meanm:>10.3f} {f2(matr):>8} {mus:>8,.0f} {f2(ratio):>9} {pct(same):>15} {pct(opp):>14}", flush=True)
            for kn, v in (("p_up", p_up), ("med_abs_move_pct", medm), ("mean_abs_move_pct", meanm), ("med_abs_move_atr", matr),
                          ("med_abs_move_usd", mus), ("vs_median_1h_bar", ratio), ("p_next6h_same_dir", same), ("p_opposite_ny_dir", opp)):
                rec("5", a, sn, kn, v)
            if a == "btc" and sn == "all":
                FIND.append(f"The 21:30-22:30 UTC hour (3-4 AM IST) on BTC moves a median ${mus:,.0f} ({medm:.2f}%), {f2(ratio)}x a typical 1h bar; it closes up {100*p_up:.0f}% of days and the next 6h continue its direction {100*same:.0f}%.")
        wd = pd.to_datetime(t[i], unit="ms", utc=True).dayofweek.to_numpy()
        print(f"  {a.upper()} by weekday P(up) / med|mv|%: " + " | ".join(f"{DOW[w]} {pct(prob((mv[wd == w] > 0))[0])}/{np.median(np.abs(mv[wd == w]))*100:.2f}" for w in range(7) if (wd == w).sum() > 2), flush=True)

# ---------------------------------------------------------------------------
# SECTION 6: one-hour boxes on 15m bars
# ---------------------------------------------------------------------------
BOX_PRE, BOX_POST = 4, 24     # 4 x 15m box, then 6h (24 x 15m) after it; breaks looked for in the first 4h (16 bars)
BOX_SCAN, BOX_FAIL = 16, 8    # fade: back inside within 2h (8 bars)

def box_starts(d15, kind):
    t = d15["time"].to_numpy(dtype="int64")
    days = np.unique((t[t >= T_START] // D1) * D1)
    if kind == "UTC2130":
        return days + (21 * 60 + 30) * 60000
    hh = 3 if kind == "NY03" else 9
    naive = pd.to_datetime(days, unit="ms") + pd.Timedelta(hours=hh)
    loc = naive.tz_localize("America/New_York", ambiguous="NaT", nonexistent="NaT").tz_convert("UTC")
    loc = loc[~pd.isna(loc)]
    v = np.asarray((loc - pd.Timestamp("1970-01-01", tz="UTC")) // pd.Timedelta(milliseconds=1), dtype="int64")
    return v

def box_ctx(ctx, a, kind):
    d15 = ctx[a].get("m15")
    if d15 is None:
        return None
    M = box_matrix(d15, box_starts(d15, kind), BOX_PRE + BOX_POST)
    DM = ctx[a]["DM"]
    di = pd.Series(DM["atr_prev"], index=DM["day"])
    M["atr_prev"] = di.reindex(M["day"]).to_numpy()
    M["BH"], M["BL"] = M["H"][:, :BOX_PRE].max(1), M["L"][:, :BOX_PRE].min(1)
    M["rng_atr"] = (M["BH"] - M["BL"]) / M["atr_prev"]
    q = pd.Series(M["rng_atr"]).shift(1).rolling(100, min_periods=40).quantile(0.4).to_numpy()
    M["narrow"] = M["rng_atr"] <= q
    return M

def build_box_bo(M, narrow=False):
    hr, dv = first_break(M, BOX_PRE, BOX_PRE + BOX_SCAN, M["BH"], M["BL"], use_close=True)
    d = np.where(dv != 0)[0]
    if narrow:
        d = d[M["narrow"][d]]
    side = dv[d].astype(float); e = hr[d] + 1
    entry = M["O"][d, e]
    raw = np.where(side > 0, M["BL"][d], M["BH"][d])
    ok = side * (entry - raw) > 0
    d, side, e, entry, raw = d[ok], side[ok], e[ok], entry[ok], raw[ok]
    return d, e, side, adj_stop(entry, side, raw), (BOX_PRE + 1, BOX_PRE + BOX_SCAN)

def build_box_fade(M):
    d, e, side, stop = build_fade(M, M["BH"], M["BL"], BOX_PRE, BOX_PRE + BOX_SCAN, BOX_FAIL, BOX_PRE + BOX_POST - 2)
    return d, e, side, stop, (BOX_PRE + 2, BOX_PRE + BOX_SCAN + BOX_FAIL)

def section6(ctx):
    print("\n=== 6) ONE-HOUR BOXES (15m bars): NY 03-04 ET, NY 09-10 ET (DST-aware), 21:30-22:30 UTC = 3-4 AM IST ===", flush=True)
    print(f"  box = first hour; breaks = first 15m close beyond it in the next 4h; exit 6h after the box; fade = back inside within 2h", flush=True)
    names = [("NY03", "NY 03-04 ET"), ("NY09", "NY 09-10 ET"), ("UTC2130", "21:30-22:30 UTC")]
    boxes = {}
    for kind, label in names:
        boxes[kind] = {a: box_ctx(ctx, a, kind) for a in ("btc", "eth")}
    print(f"  {'box asset':<22} {'n':>5} {'rng %':>6} {'rng ATR':>8} {'P(break 4h)':>12} {'P(up first)':>12} {'P(beyond @exit)':>16} {'P(opp @exit)':>13} {'post6h/box':>11}", flush=True)
    for kind, label in names:
        for a in ("btc", "eth"):
            M = boxes[kind][a]
            if M is None or not len(M["day"]):
                print(f"  {label+' '+a.upper():<22} no data", flush=True)
                continue
            hr, dv = first_break(M, BOX_PRE, BOX_PRE + BOX_SCAN, M["BH"], M["BL"], use_close=True)
            cx = M["C"][:, -1]
            beyond = np.where(dv > 0, cx > M["BH"], cx < M["BL"])
            opp = np.where(dv > 0, cx < M["BL"], cx > M["BH"])
            rp = np.median((M["BH"] - M["BL"]) / M["O"][:, 0]) * 100
            ra = np.nanmedian(M["rng_atr"])
            post = (M["H"][:, BOX_PRE:].max(1) - M["L"][:, BOX_PRE:].min(1)) / np.maximum(M["BH"] - M["BL"], 1e-12)
            pb, pu = prob(dv != 0)[0], prob((dv > 0)[dv != 0])[0]
            pby, pop = prob(beyond[dv != 0])[0], prob(opp[dv != 0])[0]
            print(f"  {label+' '+a.upper():<22} {len(M['day']):>5} {rp:>6.2f} {f2(ra):>8} {pct(pb):>12} {pct(pu):>12} {pct(pby):>16} {pct(pop):>13} {np.median(post):>11.2f}", flush=True)
            for kn, v in (("range_pct", rp), ("range_atr", ra), ("p_break_4h", pb), ("p_up_first", pu), ("p_beyond_at_exit", pby),
                          ("p_opposite_at_exit", pop), ("post6h_over_box_med", np.median(post))):
                rec("6", a, kind, kn, v)
            if a == "btc" and kind == "UTC2130":
                FIND.append(f"The 21:30-22:30 UTC box on BTC is a median {rp:.2f}% wide; price closes beyond it in the next 4h on {100*pb:.0f}% of days and is still beyond the broken side 6h later {100*pby:.0f}% of those times.")
    print(TEST_HDR, flush=True)
    xcol = BOX_PRE + BOX_POST - 1
    for kind, label in names:
        mk = {a: boxes[kind][a] for a in ("btc", "eth")}
        if mk["btc"] is None:
            continue
        run_mat_test(ctx, "6", f"{label} breakout", lambda M: build_box_bo(M), xcol, mat_key=mk)
        run_mat_test(ctx, "6", f"{label} fade fail", build_box_fade, xcol, mat_key=mk)
        run_mat_test(ctx, "6", f"{label} narrow-box breakout", lambda M: build_box_bo(M, narrow=True), xcol, mat_key=mk)

# ---------------------------------------------------------------------------
# SECTION 7: stop hunts in thin hours (continuous 1h bars)
# ---------------------------------------------------------------------------
SW_ATR, SW_HOLD, SW_LOOK = 0.3, 24, 24
THIN_HOURS = {20, 21, 22, 23, 0, 7, 12}   # US close -> Asia open, and 1h before London (08) / NY (13) opens

def sweeps(df):
    t = df["time"].to_numpy(dtype="int64")
    o, h, l, c = (df[k].to_numpy(float) for k in ("open", "high", "low", "close"))
    v = df["volume"].to_numpy(float) if "volume" in df else np.ones(len(t))
    ph = pd.Series(h).shift(1).rolling(SW_LOOK, min_periods=SW_LOOK).max().to_numpy()
    pl = pd.Series(l).shift(1).rolling(SW_LOOK, min_periods=SW_LOOK).min().to_numpy()
    a1 = np.r_[NAN, atr(h, l, c, 14)[:-1]]
    vr = pd.Series(v).rolling(720, min_periods=200).rank(pct=True).to_numpy()
    n = len(t)
    hr = ((t % D1) // H1).astype(int)
    wd = pd.to_datetime(t, unit="ms", utc=True).dayofweek.to_numpy()
    out = []
    busy = -1
    for i in np.where(np.isfinite(ph) & np.isfinite(a1) & (t >= T_START))[0]:
        if i <= busy or i + 3 + SW_HOLD >= n:
            continue
        for dirv, lev, ext in ((1, ph[i], h[i] - ph[i]), (-1, pl[i], pl[i] - l[i])):
            if ext < SW_ATR * a1[i]:
                continue
            j = None
            for k in range(i, i + 3):
                if (c[k] < lev) if dirv > 0 else (c[k] > lev):
                    j = k; break
            if j is None:
                continue
            e = j + 1
            entry = o[e]
            wick = h[i:j + 1].max() if dirv > 0 else l[i:j + 1].min()
            side = -dirv
            stop = float(adj_stop(entry, side, wick))
            if side * (entry - stop) <= 0:
                continue
            opp = pl[i] if dirv > 0 else ph[i]
            out.append(dict(i=i, e=e, side=side, entry=entry, stop=stop, opp=opp, size_atr=ext / a1[i], atr=a1[i],
                            thin=(hr[i] in THIN_HOURS) or (wd[i] >= 5), lowvol=bool(np.isfinite(vr[i]) and vr[i] <= 0.3),
                            day=(t[i] // D1) * D1, hour=hr[i]))
            busy = e + SW_HOLD - 1
            break
    return out, dict(t=t, o=o, h=h, l=l, c=c, hr=hr)

def sim_cont(B, e, side, stop, tgt, hold=SW_HOLD):
    e = np.asarray(e, int)
    n = len(B["o"])
    idx = np.minimum(e[:, None] + np.arange(hold)[None, :], n - 1)
    M = dict(O=B["o"][idx], H=B["h"][idx], L=B["l"][idx], C=B["c"][idx])
    return sim_mat(M, np.arange(len(e)), np.zeros(len(e), int), side, stop, hold - 1, tgt=tgt)

def sw_trades(B, S, mode):
    if not S:
        return None
    e = np.array([s["e"] for s in S]); side = np.array([s["side"] for s in S], float)
    entry = np.array([s["entry"] for s in S]); stop = np.array([s["stop"] for s in S])
    rk = np.abs(entry - stop)
    if mode == "2R":
        tgt = entry + side * 2 * rk
    else:
        opp = np.array([s["opp"] for s in S])
        tgt = np.where(side * (opp - entry) > 0, opp, entry + side * 2 * rk)
    out = sim_cont(B, e, side, stop, tgt)
    out["tR"] = np.abs(tgt - entry) / rk
    out["day"] = np.array([s["day"] for s in S], "int64")
    out["e"] = e
    # reversal size: best favourable move over the hold in ATR(1h) units
    idx = np.minimum(e[:, None] + np.arange(SW_HOLD)[None, :], len(B["o"]) - 1)
    best = np.where(side[:, None] > 0, B["h"][idx] - entry[:, None], entry[:, None] - B["l"][idx]).max(1)
    out["rev_atr"] = best / np.array([s["atr"] for s in S])
    return out

def sw_placebo(B, res, rng):
    e0, risk, tR = res["e"], res["risk"], res["tR"]
    if len(e0) < 5:
        return np.array([])
    hr = B["hr"]
    n = len(B["o"])
    ee = np.tile(e0, N_PLC) + 24 * rng.integers(-30, 31, len(e0) * N_PLC)   # same hour of day, within +-30 days
    ee = np.clip(ee, 0, n - SW_HOLD - 1)
    side = rng.choice([-1.0, 1.0], len(ee))
    rr, tt = np.tile(risk, N_PLC), np.tile(tR, N_PLC)
    entry = B["o"][ee]
    stop = entry * (1 - side * rr)
    tgt = entry * (1 + side * rr * tt)
    R = sim_cont(B, ee, side, stop, tgt)["R"].reshape(N_PLC, len(e0))
    return np.array([pf_of(x) for x in R])

def section7(ctx):
    print(f"\n=== 7) STOP HUNTS IN THIN HOURS: 1h wick >= {SW_ATR} ATR14(1h) beyond prior 24h high/low, close back inside within 1-3 bars, fade ===", flush=True)
    print("  thin = 20:00-01:00 UTC, Sat/Sun, 07:00 and 12:00 UTC (1h before London / NY); lowvol = 1h volume in bottom 30% of last 30d; stop beyond wick, 24h time stop", flush=True)
    data = {}
    for a in ("btc", "eth"):
        S, B = sweeps(ctx[a]["df"])
        data[a] = (S, B)
        nt = sum(1 for s in S if s["thin"])
        print(f"  {a.upper()} sweeps faded: {len(S)} (thin {nt}, liquid {len(S)-nt}, lowvol {sum(1 for s in S if s['lowvol'])})", flush=True)
    print(TEST_HDR, flush=True)
    groups = [("all", lambda s: True), ("thin", lambda s: s["thin"]), ("liquid", lambda s: not s["thin"]),
              ("lowvol", lambda s: s["lowvol"]), ("thin+lowvol", lambda s: s["thin"] and s["lowvol"])]
    keep_res = {}
    for mode in ("2R", "opp24h"):
        for gname, fn in groups:
            res = {}
            for a in ("btc", "eth"):
                S, B = data[a]
                Sg = [s for s in S if fn(s)]
                r = sw_trades(B, Sg, mode)
                if r is None:
                    continue
                if a == "btc":
                    r["plc_pfs"] = sw_placebo(B, r, ctx["rng"])
                    r["corr"] = corr_vs(ctx[a].get("basket"), r["day"], r["R"], r["risk"], ctx[a]["DM"]["day"])
                    keep_res[(mode, gname)] = (r, Sg)
                res[a] = r
            eval_test("7", f"sweep fade {mode} {gname}", res)
    try:
        r, Sg = keep_res[("2R", "all")]
        sz = np.array([s["size_atr"] for s in Sg])
        thin = np.array([s["thin"] for s in Sg])
        q = pd.qcut(sz, 5, labels=False, duplicates="drop")
        print("  BTC sweep size vs reversal (2R, all): quintile of wick size in ATR(1h) -> median reversal (best move over 24h, ATR), PF, n", flush=True)
        for k in range(int(np.nanmax(q)) + 1):
            m = q == k
            print(f"    Q{k+1} wick {np.min(sz[m]):.2f}-{np.max(sz[m]):.2f} ATR | reversal med {np.median(r['rev_atr'][m]):.2f} ATR | PF {f2(pf_of(r['R'][m]))} | n {m.sum()}", flush=True)
            rec("7", "btc", f"sizeQ{k+1}", "rev_atr_med", np.median(r["rev_atr"][m])); rec("7", "btc", f"sizeQ{k+1}", "PF", pf_of(r["R"][m]))
        sp = pd.Series(sz).corr(pd.Series(r["rev_atr"]), method="spearman")
        print(f"    spearman(wick size, reversal) {sp:.2f}; reversal med thin {np.median(r['rev_atr'][thin]):.2f} vs liquid {np.median(r['rev_atr'][~thin]):.2f} ATR", flush=True)
        rec("7", "btc", "all", "spearman_size_reversal", sp)
        pt, pl_ = pf_of(r["R"][thin]), pf_of(r["R"][~thin])
        FIND.append(f"Fading BTC stop hunts (wick past the 24h high/low that closes back inside): PF {f2(pt)} in thin hours vs {f2(pl_)} in liquid hours (2R target, n {thin.sum()} / {(~thin).sum()}).")
    except Exception as ex:
        print(f"  sweep size table error {type(ex).__name__}: {ex}", flush=True)

# ---------------------------------------------------------------------------
def main(smoke=False):
    ctx = {"rng": np.random.default_rng(SEED)}
    if smoke:
        print("SMOKE MODE: synthetic data only (no real backtest).", flush=True)
        n = int(os.environ.get("SESS_SMOKE_N", str(24 * 900)))
        b1 = synthetic_1h(n=n, seed=9, start="2019-07-01")
        e1 = synthetic_1h(n=n, seed=21, start="2019-07-01", px0=300.0)
        ctx["btc"] = dict(df=b1, fund=None, m15=synthetic_15m_from_1h(b1, seed=3))
        ctx["eth"] = dict(df=e1, fund=None, m15=synthetic_15m_from_1h(e1, seed=4))
    else:
        for a in ("btc", "eth"):
            df = load(a, "1h")
            try:
                fd = funding(a, "binance")
            except Exception as ex:
                print(f"  funding {a} failed ({type(ex).__name__}); basket without funding", flush=True)
                fd = None
            try:
                m15 = load(a, "15m")
            except Exception as ex:
                print(f"  15m {a} failed ({type(ex).__name__}: {ex}); sections 5/6 skip {a}", flush=True)
                m15 = None
            ctx[a] = dict(df=df, fund=fd, m15=m15)
    for a in ("btc", "eth"):
        c = ctx[a]
        c["DM"] = day_matrix(c["df"])
        print(f"  {a.upper()}: {len(c['DM']['day'])} complete UTC days from {START}", flush=True)
        try:
            c["h2130"] = hour2130_series(c["m15"]) if c.get("m15") is not None else None
        except Exception as ex:
            c["h2130"] = None
            print(f"  21:30 series {a} error {type(ex).__name__}: {ex}", flush=True)
        try:
            ta = time.time()
            c["basket"] = basket_daily(c["df"], c["fund"])
            print(f"    {a.upper()} basket daily pnl days {len(c['basket'])} ({time.time()-ta:.0f}s)", flush=True)
        except Exception as ex:
            c["basket"] = None
            print(f"  basket {a} error {type(ex).__name__}: {ex} (corr = n/a)", flush=True)
    for fn in (section1, section2, section3, section4, section5, section6, section7):
        try:
            fn(ctx)
        except Exception as ex:
            print(f"SECTION {fn.__name__} ERROR {type(ex).__name__}: {ex}", flush=True)
            traceback.print_exc(limit=3)
        print(f"  ({time.time()-T0:.0f}s)", flush=True)

    print("\n=== FINDINGS ===", flush=True)
    for s in FIND:
        print("  - " + s, flush=True)
    keeps = [k for k, v in KEEP.items() if v[0] == "KEEP"]
    near = sorted([(v[1], k) for k, v in KEEP.items() if v[0] != "KEEP" and np.isfinite(v[1]) and v[1] > 1.2], reverse=True)[:5]
    print(f"  - Trade tests that pass every KEEP gate: {', '.join(keeps) if keeps else 'none'}.", flush=True)
    if near:
        print("  - Best of the rest (PF, failed gates): " + "; ".join(f"{k} PF {v:.2f} {KEEP[k][0]}" for v, k in near) + ".", flush=True)
    print("  KEEP gates: PF > 1.3 both halves, n >= 30, placebo >= 90, ETH PF > 1.0, |corr| < 0.3 vs live basket.", flush=True)

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

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