# ===== OSOM LOCKED PLAN — Monte Carlo + synthetic-future stress test =====
# Locked plan: R=10% risk, M=4 max open, signals NO_Z2 = K8, V7, R0, C1, C2, one shared $1,000 account.
# Engine = osom6_book_v2 (same signal functions, set_native, run_book, clip_window, C2 conf_trades).
# Needs /content/BTCUSDT_perp_1h_2021-2026.csv (funding CSV NOT needed).
#
# Part A — trade bootstrap: run the locked plan as ONE continuous $1k account 2021-2026, take each
#   closed trade's return as a fraction of equity at entry (pnl / E0), then draw 100 trades with
#   replacement N_SIMS times and compound from $1,000. NOTE: this treats trades as sequential and
#   independent — it ignores the overlap of up to 4 concurrent trades (correlated losses at the same
#   time), so real drawdowns can be deeper than Part A suggests.
# Part B — synthetic future: N_PATHS one-year (8,760 x 1h) BTC paths made by block bootstrap of real
#   1h bars (30-day blocks), chained from the last real close, with ~1.5y of real history prepended
#   as indicator warm-up. All signals are rebuilt per path; the book only trades the synthetic year.
# Runtime: Part A ~ same as one backtest (~1-2 min). Part B ~3-10 s per path in Colab
#   -> 200 paths ~10-30 min. Set fewer paths with:  %env OSOM_MC_PATHS=50   (0 = skip Part B)
import os, math, time
import numpy as np, pandas as pd

H1 = 3_600_000
DAY = 86_400_000
COST, LAG, START, SL = 0.0004, 0.0008, 1_000.0, 1.5
IO_SCALE = 29313.49
V7_DEFAULTS = dict(pick="top", phaseRule=True, trailAct=20, trailPct=15)
K8_DEFAULTS = dict(q=1e-4, gate=3, sl=6, hard=7, dx=True, dxLen=14, dxTh=25, nw=True, N=8)
R0_DEFAULTS = dict(len=600, holdDays=10, stop=10, dipMA=4800, dipSlope=720, x=0.5, h=12)
C1_DEFAULTS = dict(don=20, chop=34, chopLen=14, adx=18, adxLen=14, stLen=10, stF=3,
                   htf=12, atrLen=14, sl=1.5, tp1=2.0, tp2=3.5, tp1Frac=0.3)

# ---- locked plan + MC settings ----
R_LOCK, M_LOCK = 0.10, 4
NAMES = ["K8", "V7", "R0", "C1", "C2"]          # NO_Z2
SEED = int(os.environ.get("OSOM_MC_SEED", 20261116))
N_SIMS, N_TRADES = 10_000, 100
N_PATHS = int(os.environ.get("OSOM_MC_PATHS", 200))
HORIZON = 8_760          # 1 year of 1h bars per synthetic path
BLOCK = 720              # 30-day blocks
STATIONARY = False       # False = circular block bootstrap (fixed 720); True = stationary (geometric, mean 720)
WARM_BARS = 13_140       # ~1.5 years of real history prepended (R0 dipMA 4800+720, V7 200d SMA+20)

def _first_csv(paths):
    for p in paths:
        if os.path.exists(p):
            print(f"Loading {p} ...")
            return pd.read_csv(p), p
    return None, None

df1, src = _first_csv(["/content/BTCUSDT_perp_1h_2021-2026.csv", "BTCUSDT_perp_1h_2021-2026.csv",
                       "/workspace/data/BTCUSDT_perp_1h_2021-2026.csv"])
if df1 is None:
    raise FileNotFoundError("Need BTCUSDT_perp_1h_2021-2026.csv in /content")
if "volume" not in df1.columns:
    for c in ("volume_btc", "vol", "volume_base"):
        if c in df1.columns:
            df1 = df1.rename(columns={c: "volume"}); break
if "timestamp_ms" not in df1.columns:
    tcol = next(c for c in ("open_time_utc", "open_time", "timestamp", "time", "date") if c in df1.columns)
    df1["timestamp_ms"] = pd.to_datetime(df1[tcol], utc=True).astype("int64") // 1_000_000
t = (pd.to_numeric(df1["timestamp_ms"]).astype("int64").to_numpy() // H1) * H1
D_REAL = dict(time=t,
         open=pd.to_numeric(df1["open"]).to_numpy(),
         high=pd.to_numeric(df1["high"]).to_numpy(),
         low=pd.to_numeric(df1["low"]).to_numpy(),
         close=pd.to_numeric(df1["close"]).to_numpy(),
         volume=pd.to_numeric(df1["volume"]).to_numpy())
ord_ = np.argsort(D_REAL["time"])
for k in D_REAL:
    D_REAL[k] = D_REAL[k][ord_]
keep = np.r_[True, D_REAL["time"][1:] != D_REAL["time"][:-1]]
for k in D_REAL:
    D_REAL[k] = D_REAL[k][keep]

# ===================== engine (copied verbatim from osom6_book_v2) =====================
def _agg(t, o, h, l, c, v, period_ms, complete_only=False, drop_partial_last=False):
    key = t // period_ms
    idx = np.flatnonzero(np.r_[True, key[1:] != key[:-1]])
    end = np.r_[idx[1:], len(t)]
    B = dict(time=key[idx] * period_ms,
             open=o[idx], high=np.maximum.reduceat(h, idx), low=np.minimum.reduceat(l, idx),
             close=c[end - 1], volume=np.add.reduceat(v, idx), lastT=t[end - 1], n=end - idx,
             first=idx, last=end - 1)
    keep = np.ones(len(idx), bool)
    if complete_only:
        keep = B["n"] == period_ms // H1
    elif drop_partial_last and len(idx) and B["lastT"][-1] + H1 < B["time"][-1] + period_ms:
        keep[-1] = False
    return {k: val[keep] for k, val in B.items()}

def _map_completed(bar_time, period_ms, t1h, fill=0.0, values=None):
    s = np.searchsorted(bar_time + period_ms, t1h, side="right") - 1
    out = np.full(len(t1h), fill, dtype=float)
    ok = s >= 0
    vv = values[s[ok]]
    vv = np.where(np.isnan(vv), fill, vv)
    out[ok] = vv
    return out

def _roll_sum(x, n):
    return pd.Series(x).rolling(n, min_periods=n).sum().to_numpy()

def _sma(x, n):
    return pd.Series(x).rolling(n, min_periods=n).mean().to_numpy()

def _ema_arr(x, span):
    a = 2.0 / (span + 1); out = np.empty(len(x)); u = x[0]
    for i in range(len(x)):
        u = a * x[i] + (1 - a) * u; out[i] = u
    return out

def _pct_rank(x, t=500):
    n = len(x); out = np.full(n, np.nan)
    if n < t: return out
    from numpy.lib.stride_tricks import sliding_window_view as swv
    W = swv(x, t)
    step = 4000
    for j0 in range(0, len(W), step):
        w = W[j0:j0 + step]; cur = w[:, -1:]
        less = (w < cur).sum(1); eq = (w == cur).sum(1)
        val = (less + (eq + 1) / 2) / t * 100
        val[~np.isfinite(w).all(1)] = np.nan
        out[j0 + t - 1: j0 + t - 1 + len(w)] = val
    return out

def _cross_up(x, th):
    p = np.r_[np.nan, x[:-1]]
    return (p < th) & (x >= th)

def _cross_dn(x, th):
    p = np.r_[np.nan, x[:-1]]
    return (p > th) & (x <= th)

def _within(ev, k):
    out = np.zeros(len(ev), bool); last = -10**9
    for i in range(len(ev)):
        if ev[i]: last = i
        out[i] = i - last <= k
    return out

def _open_trade(side, ei, entry, stop, n, close, why="open"):
    return dict(side=side, ei=ei, xi=n - 1, entry=entry, exit=close[n - 1], stop=stop,
                fills=[(1.0, close[n - 1])], ret=side * (close[n - 1] / entry - 1) - 0.0014, why=why)

def _wilder_ema(tr, alpha):
    out = np.empty(len(tr)); out[0] = tr[0]
    for i in range(1, len(tr)): out[i] = alpha * tr[i] + (1 - alpha) * out[i - 1]
    return out

def _true_range(h, l, c):
    tr = h - l
    pc = np.r_[np.nan, c[:-1]]
    tr2 = np.fmax(tr, np.fmax(np.abs(h - pc), np.abs(l - pc)))
    tr2[0] = h[0] - l[0]
    return tr2

def _rma_seeded(x, n):
    out = np.full(len(x), np.nan); acc = 0.0; cnt = 0; r = np.nan
    for i, val in enumerate(x):
        if not np.isfinite(val): continue
        if np.isnan(r):
            acc += val; cnt += 1
            if cnt == n: r = acc / n; out[i] = r
        else:
            r = (r * (n - 1) + val) / n; out[i] = r
    return out

def _dx_guard(D, n=14, th=25.0):
    t = D["time"]
    BD = _agg(t, D["open"], D["high"], D["low"], D["close"], D["volume"], DAY)
    k = BD["time"] // DAY; H, L, C = BD["high"], BD["low"], BD["close"]
    a = np.zeros(len(H), np.int8); sl = sp = sm = 0.0; dxs = []
    for m in range(1, len(H)):
        up = H[m] - H[m - 1]; dn = L[m - 1] - L[m]
        tr = max(H[m] - L[m], abs(H[m] - C[m - 1]), abs(L[m] - C[m - 1]))
        sl = sl - sl / n + tr
        sp = sp - sp / n + (up if (up > dn and up > 0) else 0.0)
        sm = sm - sm / n + (dn if (dn > up and dn > 0) else 0.0)
        y = 100 * sp / sl if sl else 0.0; S = 100 * sm / sl if sl else 0.0
        dxs.append(100 * abs(y - S) / (y + S) if (y + S) else 0.0)
        if len(dxs) >= n:
            a[m] = int(np.sign(y - S)) if np.mean(dxs[-n:]) > th else 0
    b = (t + H1) // DAY - 1 - k[0]
    out = np.zeros(len(t), np.int8); ok = (b >= 0) & (b < len(a))
    out[ok] = a[b[ok]]
    return out

def _neurow(c):
    n = len(c)
    def ema(span):
        a = 2 / (span + 1); out = np.empty(n); u = c[0]
        for i in range(n):
            u = c[i] * a + u * (1 - a); out[i] = u
        return out
    e8, e21 = ema(8), ema(21)
    s40 = _sma(c, 40)
    rsi = np.empty(n); rsi[0] = 50; g = ls = 0.0
    for i in range(1, n):
        d = c[i] - c[i - 1]
        g = (g * 13 + max(d, 0)) / 14; ls = (ls * 13 + max(-d, 0)) / 14
        rsi[i] = 100 - 100 / (1 + g / ls) if ls else 100
    hh = np.r_[0, (e8[1:] - e8[:-1]) / e8[:-1]]
    uu = (e8 - e21) / e21
    pp = 50 + 50 * np.tanh(uu * 50 + hh * 200)
    mm = np.where(np.isnan(s40), 0.0, (c - s40) / np.where(np.isnan(s40), 1, s40))
    gg = 50 - 50 * np.tanh(mm * 30)
    out = np.zeros(n); out[1:] = ((pp + rsi + gg) / 3)[1:]
    return out

def _sl(ent, side, ei):
    a = ATR4[ei]
    if not np.isfinite(a): return np.nan
    return ent - side * SL * a

def _stop_for(ent, side, ei, p=None):
    """1.5x ATR stop, or a fraction-of-price hard stop when p['px_stop'] is set (e.g. 0.10)."""
    px = (p or {}).get("px_stop")
    if px:
        return ent * (1.0 - side * float(px))
    return _sl(ent, side, ei)

def _ok1(i, side, p):
    # Explicit flags only. Do NOT treat Z2's trend=200 lookback as a 4h trend gate.
    if i < 0 or i >= len(CHOP4): return False
    if p.get("chop"):
        th = float(p.get("chop_th", 30))
        if not (np.isfinite(CHOP4[i]) and CHOP4[i] < th): return False
    if p.get("adx"):
        th = float(p.get("adx_th", 18))
        if not (np.isfinite(ADX4[i]) and ADX4[i] >= th): return False
    if p.get("trend_gate") and TREND4[i] != side: return False
    sc = p.get("sc") or 0
    if sc:
        rng = D["high"][i] - D["low"][i]
        if rng <= 0: return False
        frac = ((D["close"][i] - D["low"][i]) / rng) if side > 0 else ((D["high"][i] - D["close"][i]) / rng)
        if frac < sc: return False
    return True

def _tp_px(side, ent, tp, ei, o_bar, h_bar, l_bar):
    if not tp: return None
    a = ATR4[ei]
    if not np.isfinite(a): return None
    tgt = ent + side * tp * a
    if side > 0 and h_bar >= tgt:
        return o_bar if o_bar >= tgt else tgt
    if side < 0 and l_bar <= tgt:
        return o_bar if o_bar <= tgt else tgt
    return None

def osom_v7(D, p=None):
    p = {**V7_DEFAULTS, **(p or {})}
    t, o, h, l, c, v = D["time"], D["open"], D["high"], D["low"], D["close"], D["volume"]
    n = len(c)
    tp = (h + l + c) / 3; pv = tp * v
    def dev_rank(win):
        P = _roll_sum(pv, win); G = _roll_sum(v, win)
        return _pct_rank((c - P / G) / c, 500)
    b = dev_rank(24); vv = dev_rank(168)
    Le = _cross_up(b, 10) & _within(_cross_up(vv, 20), 6)
    Se = _cross_dn(b, 90) & _within(_cross_dn(vv, 80), 6)
    B4_ = _agg(t, o, h, l, c, v, 4 * H1)
    hh = pd.Series(B4_["high"]).rolling(50).max().to_numpy(); ll = pd.Series(B4_["low"]).rolling(50).min().to_numpy()
    with np.errstate(invalid="ignore", divide="ignore"):
        pos = (B4_["close"] - ll) / (hh - ll)
    reg4 = np.where(np.isnan(hh), np.nan, np.where((pos > .35) & (pos < .65), 0.0, 2.0))
    w4 = _map_completed(B4_["time"], 4 * H1, t, 0.0, reg4)
    BD = _agg(t, o, h, l, c, v, 24 * H1)
    sma = _sma(BD["close"], 200); slope = sma - np.r_[np.full(20, np.nan), sma[:-20]]
    ph = np.where((BD["close"] < sma) & (slope < 0), -1.0, np.where((BD["close"] > sma) & (slope > 0), 1.0, 0.0))
    ph[np.isnan(sma)] = 0.0
    phase = _map_completed(BD["time"], DAY, t, 0.0, ph)
    G = np.where(p["phaseRule"] & (phase == -1), -1, 2)
    reg = np.where(w4 == 0, 0, np.where(w4 == 2, G, 0)).astype(int)
    act, pct, cst = p["trailAct"] / 100, p["trailPct"] / 100, 7e-4
    trail = (not p.get("tp")) and act > 0 and pct > 0
    trades = []; side = 0; ent = 0.0; ei = 0; best = 0.0; block = 0; stp = 0.0
    for M in range(500, n - 1):
        T = M + 1
        if side != 0:
            hit = l[M] <= stp if side > 0 else h[M] >= stp
            if hit:
                px = stp
                if side > 0 and o[M] < stp: px = o[M]
                if side < 0 and o[M] > stp: px = o[M]
                trades.append(dict(side=side, ei=ei, xi=M, entry=ent, exit=px, stop=stp,
                                   fills=[(1.0, px)], ret=(px / ent - 1) * side - 2 * cst, why="stop")); side = 0
            else:
                px = _tp_px(side, ent, p.get("tp"), ei, o[M], h[M], l[M])
                if px is not None:
                    trades.append(dict(side=side, ei=ei, xi=M, entry=ent, exit=px, stop=stp,
                                       fills=[(1.0, px)], ret=(px / ent - 1) * side - 2 * cst, why="tp")); side = 0
                elif trail and M > ei:
                    P = side * (c[M] / ent - 1); best = max(best, P)
                    if best >= act and (1 + best) / (1 + P) - 1 >= pct:
                        block = side
                        trades.append(dict(side=side, ei=ei, xi=M, entry=ent, exit=c[M], stop=stp,
                                           fills=[(1.0, c[M])], ret=(c[M] / ent - 1) * side - 2 * cst, why="trail")); side = 0
        E = 1 if Le[M] else (-1 if Se[M] else 0)
        if block and E == -block: block = 0
        if E != 0 and E != side and E != block:
            if side != 0:
                px = o[T]
                trades.append(dict(side=side, ei=ei, xi=T, entry=ent, exit=px, stop=stp,
                                   fills=[(1.0, px)], ret=(px / ent - 1) * side - 2 * cst, why="opposite")); side = 0
            if (reg[M] == 2 or reg[M] == E) and _ok1(M, E, p):
                ns = _stop_for(o[T], E, T, p)
                if np.isfinite(ns):
                    side, ent, ei, best, stp = E, o[T], T, 0.0, ns
    if side != 0:
        trades.append(_open_trade(side, ei, ent, stp, n, c))
    return trades

def osom_k8(D, p=None):
    p = {**K8_DEFAULTS, **(p or {})}
    q, gate, N = float(p["q"]), float(p["gate"]), int(p["N"])
    t, o, h, l, c = D["time"], D["open"], D["high"], D["low"], D["close"]
    n = len(c)
    B = _agg(t, o, h, l, c, D["volume"], 12 * H1, drop_partial_last=True)
    cb, tb = B["close"], B["time"]
    m = len(cb)
    inn = np.zeros(m); lvl = np.zeros(m); slp = np.zeros(m); P00 = np.zeros(m); P01 = np.zeros(m); P11 = np.zeros(m)
    Hh, be, Ae, ee, F = cb[0] / IO_SCALE, 0.0, 1.0, 0.0, 1.0
    csum = np.zeros(m + 1)
    for k in range(m):
        X = cb[k] / IO_SCALE
        de = Hh + be; ie = be; z = Ae + 2 * ee + F + q; Y = ee + F; Dd = F + q * 0.01; W = X - de
        inn[k] = W
        lo = max(0, k - 100)
        Oe = (csum[k] - csum[lo]) / (k - lo) if k - lo > 5 else W * W + 1e-9
        Li = Oe if abs(W) <= gate * math.sqrt(Oe) else Oe * W * W / (gate * gate * Oe + 1e-12)
        me = z + Li; kt = z / me; Gt = Y / me
        Hh = de + kt * W; be = ie + Gt * W; Ae = (1 - kt) * z; ee = (1 - kt) * Y; F = Dd - Gt * Y
        lvl[k], slp[k], P00[k], P01[k], P11[k] = Hh, be, Ae, ee, F
        csum[k + 1] = csum[k] + W * W
    WARM = 150
    A = np.searchsorted(tb + 12 * H1, t + H1, side="right") - 1
    I = np.full(n, np.nan)
    for i in range(n):
        O = A[i]
        if O < 6: continue
        if tb[O] + 12 * H1 == t[i] + H1:
            I[i] = slp[O]
        else:
            Ae2 = O + 1; ee2 = lvl[O] + slp[O]; F2 = slp[O]
            qq = P00[O] + 2 * P01[O] + P11[O] + q; XX = P01[O] + P11[O]
            de = c[i] / IO_SCALE - ee2; lo = max(0, Ae2 - 100)
            Y = (csum[Ae2] - csum[lo]) / (Ae2 - lo)
            Dd = Y if abs(de) <= gate * math.sqrt(Y) else Y * de * de / (gate * gate * Y + 1e-12)
            I[i] = F2 + XX / (qq + Dd) * de
    sgn = np.where((A >= WARM) & np.isfinite(I), np.sign(np.nan_to_num(I)), 0).astype(int)
    state = np.zeros(n, int); Gs_ = 0; Q = 0; st = 0
    for i in range(n):
        bb = sgn[i]
        if bb != 0 and bb == Gs_: Q += 1
        else: Gs_ = bb; Q = 1 if bb != 0 else 0
        if Gs_ != 0 and Q >= N: st = Gs_
        state[i] = st
    flip = np.where((state != 0) & (state != np.r_[0, state[:-1]]), state, 0)
    guard = _dx_guard(D, int(p["dxLen"]), float(p["dxTh"])) if p["dx"] else None
    nw = _neurow(c) if p["nw"] else None
    ok_ev = np.zeros(n, int)
    for i in range(n):
        H_ = flip[i]
        if not H_ or A[i] < 0: continue
        if guard is not None and guard[i] == -H_: continue
        if nw is not None and not (nw[i] > 50 if H_ > 0 else nw[i] < 50): continue
        if not _ok1(i, H_, p): continue
        ok_ev[i] = H_
    scale = float(p.get("scale") or 0)
    scale_tp = float(p["scale_tp"]) if p.get("scale_tp") is not None else 1.0
    trades = []; i = 0
    while i < n - 1:
        H_ = ok_ev[i]
        if not H_: i += 1; continue
        e_i = i + 1; ent = o[e_i]
        stop0 = _stop_for(ent, H_, e_i, p)
        if not np.isfinite(stop0): i += 1; continue
        stop = stop0
        fills = []; rem = 1.0; did_scale = False; defer_be = False
        ex = None; Y = e_i; why = "open"; nxt = n; xi = n - 1
        while Y < n:
            check_stop = not defer_be
            defer_be = False
            if check_stop and ((l[Y] <= stop) if H_ > 0 else (h[Y] >= stop)):
                ex = min(stop, o[Y]) if H_ > 0 else max(stop, o[Y])
                fills.append((rem, ex, Y)); rem = 0.0
                why = "be_stop" if did_scale else "stop"
                nxt = Y + 1; xi = Y; break
            if rem > 0.999 and scale:
                px = _tp_px(H_, ent, scale_tp, e_i, o[Y], h[Y], l[Y])
                if px is not None:
                    fills.append((scale, px, Y)); rem -= scale
                    stop = ent; did_scale = True; why = "partial"
                    if px == o[Y]:
                        if (l[Y] <= stop) if H_ > 0 else (h[Y] >= stop):
                            ex = min(stop, o[Y]) if H_ > 0 else max(stop, o[Y])
                            fills.append((rem, ex, Y)); rem = 0.0
                            why = "be_stop"; nxt = Y + 1; xi = Y; break
                    else:
                        defer_be = True
                    Y += 1
                    continue
            elif rem > 0.999:
                px = _tp_px(H_, ent, p.get("tp"), e_i, o[Y], h[Y], l[Y])
                if px is not None:
                    fills.append((rem, px, Y)); rem = 0.0
                    ex = px; why = "tp"; nxt = Y + 1; xi = Y; break
            if flip[Y] == -H_ and Y + 1 < n:
                ex = o[Y + 1]
                fills.append((rem, ex, Y + 1)); rem = 0.0
                why = "flip"; nxt = Y; xi = Y + 1; break
            Y += 1
        if rem > 1e-12:
            fills.append((rem, c[n - 1], n - 1))
            xi = n - 1; ex = c[n - 1]; why = "open"
            ret = sum(wt * H_ * (px / ent - 1) for wt, px, *_ in fills) - 2 * 7e-4
            trades.append(dict(side=H_, ei=e_i, xi=xi, entry=ent, exit=ex, stop=stop0,
                               fills=fills, ret=ret, why=why))
            break
        ret = sum(wt * H_ * (px / ent - 1) for wt, px, *_ in fills) - 2 * 7e-4
        trades.append(dict(side=H_, ei=e_i, xi=xi, entry=ent, exit=ex, stop=stop0,
                           fills=fills, ret=ret, why=why))
        i = nxt
    return trades

def osom_r0(D, p=None):
    p = {**R0_DEFAULTS, **(p or {})}
    o, h, l, c = D["open"], D["high"], D["low"], D["close"]
    n = len(c); W, hold = int(p["len"]), int(p["holdDays"] * 24)
    ph = pd.Series(h).rolling(W).max().shift(1).to_numpy(); pl = pd.Series(l).rolling(W).min().shift(1).to_numpy()
    s = np.zeros(n, int); a = 0; left = 0
    for w in range(n):
        M = 0
        if w >= W:
            if h[w] > ph[w] and c[w] < ph[w]: M = -1
            elif l[w] < pl[w] and c[w] > pl[w]: M = 1
        if M and M != a: a = M; left = hold
        elif M: left = hold
        elif left > 0:
            left -= 1
            if left == 0: a = 0
        s[w] = a
    ma = _sma(c, int(p["dipMA"])) if p["dipMA"] else np.full(n, np.nan)
    sl_ = int(p["dipSlope"])
    def dip(w):
        return p["dipMA"] > 0 and c[w] < ma[w] and w >= sl_ and ma[w] < ma[w - sl_]
    v = p["stop"] / 100
    base = []; y = 0; ent = 0.0; ei = 0; k = 0
    for w in range(n - 1):
        if y:
            M = ent * (1 - y * v)
            if (l[w] <= M) if y > 0 else (h[w] >= M):
                base.append((y, ei, w, min(M, o[w]) if y > 0 else max(M, o[w]), "stop")); y = 0
        if s[w] != k:
            M = s[w]; k = M
            if M == 0:
                if y: base.append((y, ei, w + 1, o[w + 1], "time")); y = 0
            elif M != y:
                if y: base.append((y, ei, w + 1, o[w + 1], "flip")); y = 0
                if M > 0 and dip(w):
                    pass
                else:
                    y = M; ent = o[w + 1]; ei = w + 1
    if y: base.append((y, ei, None, None, "open"))
    tr = _true_range(h, l, c); atr = _wilder_ema(tr, 0.08)
    trades = []
    for (S, vI, xI, xP, why0) in base:
        closed = xI is not None; yI = xI if closed else n
        lvl = o[vI] - S * p["x"] * atr[vI - 1]
        wI = -1
        for P in range(vI, min(vI + int(p["h"]), yI)):
            if S * (c[P] - lvl) <= 0:
                if P + 1 < yI and P + 1 < n: wI = P + 1
                break
        if wI < 0: continue
        if not _ok1(wI, S, {**p, "sc": 0}): continue
        if p.get("sc") and not _ok1(vI - 1 if vI > 0 else 0, S, {"sc": p["sc"]}): continue
        C = o[wI]; T = _stop_for(C, S, wI, p); E = -1; A_ = xP; why = why0
        if not np.isfinite(T): continue
        for P in range(wI, yI):
            if (l[P] <= T) if S > 0 else (h[P] >= T):
                E = P; A_ = min(T, o[P]) if S > 0 else max(T, o[P]); why = "stop"; break
            px = _tp_px(S, C, p.get("tp"), wI, o[P], h[P], l[P])
            if px is not None:
                E = P; A_ = px; why = "tp"; break
        if E >= 0 or closed:
            xi = E if E >= 0 else xI
            trades.append(dict(side=S, ei=wI, xi=min(xi, n - 1), entry=C, exit=A_, stop=T, fills=[(1.0, A_)],
                               ret=(A_ / C - 1) * S - 0.0014, why=why))
        else:
            trades.append(_open_trade(S, wI, C, T, n, c))
    return trades

def clip_window(trades, t1, t_lo, t_hi, close):
    last = int(np.searchsorted(t1, t_hi)) - 1
    out = []
    for tr in trades:
        if tr["ei"] >= len(t1) or not (t_lo <= t1[tr["ei"]] < t_hi):
            continue
        d = dict(tr)
        fills = list(tr["fills"])
        crosses = d["xi"] > last or t1[min(d["xi"], len(t1) - 1)] >= t_hi
        if crosses:
            has_xi = all(isinstance(f, (list, tuple)) and len(f) >= 3 for f in fills)
            if has_xi:
                kept, realized = [], 0.0
                for f in fills:
                    wt, px, fxi = f[0], f[1], int(f[2])
                    if fxi <= last and t1[min(fxi, len(t1) - 1)] < t_hi:
                        kept.append((wt, px, fxi)); realized += wt
                rem = 1.0 - realized
                if rem > 1e-12:
                    kept.append((rem, float(close[last]), last))
                d["fills"] = kept
            else:
                d["fills"] = [(1.0, float(close[last]))]
            d["xi"] = last
            d["exit"] = float(close[last])
        else:
            d["fills"] = fills
        d["xi"] = max(d["ei"], min(d["xi"], last))
        out.append(d)
    return out

# ----- C1 native (faithful port; fills keep bar index so year-end clip preserves the scale remainder) -----
def osom_c1_signals(D, p=None):
    p = {**C1_DEFAULTS, **(p or {})}
    t, o, h, l, c = D["time"], D["open"], D["high"], D["low"], D["close"]
    B = _agg(t, o, h, l, c, D["volume"], 4 * H1, complete_only=True)
    bo, bh, bl, bc, bt = B["open"], B["high"], B["low"], B["close"], B["time"]
    nb = len(bc); trb = _true_range(bh, bl, bc)
    atr = _rma_seeded(trb, p["atrLen"])
    L = p["chopLen"]
    trs = pd.Series(trb).rolling(L).sum().to_numpy()
    hh = pd.Series(bh).rolling(L).max().to_numpy()
    ll = pd.Series(bl).rolling(L).min().to_numpy()
    with np.errstate(invalid="ignore", divide="ignore"):
        cc = 100 * np.log10(trs / (hh - ll)) / np.log10(L)
    cc[:L] = np.nan; cc[~(hh > ll)] = np.nan; chop = cc
    up = np.r_[0, bh[1:] - bh[:-1]]; dn = np.r_[0, bl[:-1] - bl[1:]]
    pdm = np.where((up > dn) & (up > 0), up, 0.0)
    mdm = np.where((dn > up) & (dn > 0), dn, 0.0)
    sA, sP, sM = _rma_seeded(trb, p["adxLen"]), _rma_seeded(pdm, p["adxLen"]), _rma_seeded(mdm, p["adxLen"])
    with np.errstate(invalid="ignore", divide="ignore"):
        u = 100 * sP / sA; pm = 100 * sM / sA
        dx = np.where(np.isfinite(u) & np.isfinite(pm),
                      np.where(u + pm != 0, 100 * np.abs(u - pm) / (u + pm), 0.0), np.nan)
    adx = _rma_seeded(dx, p["adxLen"])
    HB = _agg(t, o, h, l, c, D["volume"], p["htf"] * H1, complete_only=True)
    hatr = _rma_seeded(_true_range(HB["high"], HB["low"], HB["close"]), p["stLen"])
    stv = np.zeros(len(hatr), int); r = s_ = np.nan; a = 1
    for i in range(len(hatr)):
        if not np.isfinite(hatr[i]): continue
        mid = (HB["high"][i] + HB["low"][i]) / 2
        lo_b = mid - p["stF"] * hatr[i]; up_b = mid + p["stF"] * hatr[i]
        if np.isnan(r):
            r, s_ = lo_b, up_b; stv[i] = a; continue
        pc = HB["close"][i - 1]; m_, g_ = r, s_
        r = max(lo_b, m_) if pc > m_ else lo_b
        s_ = min(up_b, g_) if pc < g_ else up_b
        if a == -1 and HB["close"][i] > g_: a = 1
        elif a == 1 and HB["close"][i] < m_: a = -1
        stv[i] = a
    hclose = HB["time"] + p["htf"] * H1
    sig = np.zeros(nb, int); uu = -1
    for k in range(p["don"], nb):
        mclose = bt[k] + 4 * H1
        while uu + 1 < len(hclose) and hclose[uu + 1] <= mclose: uu += 1
        if not np.isfinite(atr[k]) or uu < 0 or not stv[uu]: continue
        g = bh[k - p["don"]:k].max(); f = bl[k - p["don"]:k].min()
        y = (chop[k] < p["chop"]) and (adx[k] >= p["adx"])
        if bc[k] > g and bc[k] > bo[k] and y and stv[uu] == 1: sig[k] = 1
        elif bc[k] < f and bc[k] < bo[k] and y and stv[uu] == -1: sig[k] = -1
    return dict(B=B, sig=sig, atr=atr)

def osom_c1(D, p=None):
    p = {**C1_DEFAULTS, **(p or {})}
    R = osom_c1_signals(D, p)
    B, sig, atr = R["B"], R["sig"], R["atr"]
    t, o, h, l, c = D["time"], D["open"], D["high"], D["low"], D["close"]
    n = len(c); bt = B["time"]; nb = len(bt)
    pos_of = {tt: i for i, tt in enumerate(t)}
    trades = []; S = 0
    while S < nb:
        x = sig[S]
        if not x: S += 1; continue
        kt = bt[S + 1] if S + 1 < nb else bt[S] + 4 * H1
        L0 = pos_of.get(kt)
        if L0 is None: S += 1; continue
        w = o[L0]; M = atr[S]
        C = w - x * p["sl"] * M; T = w + x * p["tp1"] * M; E = w + x * p["tp2"] * M
        A = 1.0; fills = []; O = 0; P = L0; done = False
        while P < n:
            hb, lb, ob = h[P], l[P], o[P]
            Fe = lb <= C if x > 0 else hb >= C
            Ye = O == 0 and (hb >= T if x > 0 else lb <= T)
            Me = hb >= E if x > 0 else lb <= E
            if Fe:
                fills.append((A, min(C, ob) if x > 0 else max(C, ob), P)); A = 0; done = True; break
            if O == 0 and Ye:
                fills.append((p["tp1Frac"], max(T, ob) if x > 0 else min(T, ob), P))
                A = 1 - p["tp1Frac"]; O = 1; C = w
                if ((lb <= w) if x > 0 else (hb >= w)) and P > L0:
                    fills.append((A, w, P)); A = 0; done = True; break
                if Me:
                    fills.append((A, max(E, ob) if x > 0 else min(E, ob), P)); A = 0; done = True; break
                P += 1; continue
            if O == 1 and Me:
                fills.append((A, max(E, ob) if x > 0 else min(E, ob), P)); A = 0; done = True; break
            P += 1
        sl0 = w - x * p["sl"] * M
        if not done:
            fl = list(fills) + ([(A, c[n - 1], n - 1)] if A > 1e-12 else [])
            trades.append(dict(side=x, ei=L0, xi=n - 1, entry=w, exit=c[n - 1], stop=sl0, fills=fl))
            break
        Z = fills[-1][2]
        trades.append(dict(side=x, ei=L0, xi=Z, entry=w, exit=fills[-1][1], stop=sl0, fills=fills))
        he = t[Z] + H1; se = S + 1
        while se < nb and bt[se] + 4 * H1 < he: se += 1
        S = se
    return trades

def map_4h_to_1h(trades):
    out = []
    for tr in trades:
        ei = int(np.searchsorted(t1, idx4[tr["ei"]]))
        if ei >= len(t1): continue
        xi = int(np.searchsorted(t1, idx4[tr["xi"]] + 4 * H1, side="left") - 1)
        xi = max(ei, min(xi, len(t1) - 1))
        d = dict(tr); d["ei"], d["xi"] = ei, xi
        out.append(d)
    return out

TP_MULT = 3.0
def conf_trades(k, tp_mult=TP_MULT):
    """Strict new-edge on the vote count: fire when side votes go <k -> >=k and the
    opposite side has <k votes. One position at a time; SL before TP each bar."""
    trades, in_pos = [], False
    prev_l = prev_s = False
    side = ei = 0; raw = sl = tp = 0.0
    for i in range(i0_4, len(df) - 1):
        ls, ss = bool(VOTE_L[i] >= k), bool(VOTE_S[i] >= k)
        if not in_pos:
            el = ls and not prev_l and not ss
            es = ss and not prev_s and not ls
            if el ^ es:
                side = 1 if el else -1
                raw = o4[i + 1]
                ep = raw * (1.0 + side * LAG)
                sl = ep - side * a4[i] * SL
                tp = ep + side * a4[i] * tp_mult
                ei = i + 1; in_pos = True
        prev_l, prev_s = ls, ss
        if in_pos:
            xp = None
            if side == 1:
                if l4[i + 1] <= sl: xp = sl
                elif h4[i + 1] >= tp: xp = tp
            else:
                if h4[i + 1] >= sl: xp = sl
                elif l4[i + 1] <= tp: xp = tp
            if xp is not None:
                trades.append(dict(side=side, ei=ei, xi=i + 1, entry=raw, exit=xp, stop=sl, fills=[(1.0, xp)]))
                in_pos = False
    if in_pos:
        trades.append(dict(side=side, ei=ei, xi=len(df) - 1, entry=raw, exit=c4[-1], stop=sl, fills=[(1.0, c4[-1])]))
    return trades

# Native group: notional f = LEV x (R / 0.30), 10% price stop -> eff_r = f x 0.10 = R.
# run_book reads NATIVE_F / NATIVE_EFF_R as globals, so set_native(R) is called before each run.
NATIVE = {"V7", "R0", "K8"}
NATIVE_LEV, NATIVE_BASE, NATIVE_SF = 3.0, 0.30, 0.10
NATIVE_F = NATIVE_LEV * (0.10 / NATIVE_BASE); NATIVE_EFF_R = NATIVE_F * NATIVE_SF

def set_native(r):
    global NATIVE_F, NATIVE_EFF_R
    NATIVE_F = NATIVE_LEV * (r / NATIVE_BASE)
    NATIVE_EFF_R = NATIVE_F * NATIVE_SF
    return r / NATIVE_BASE

def run_book(books, t_lo, t_hi, r, M, R_tot, names=None, native=None, log=None):
    """One shared account. Open only if under the position cap AND adding effective
    risk keeps total open risk <= R_tot.
    ATR-group names: f = r / sf (1.5x ATR stop), eff_r = r.
    Native names (V7/R0/K8): f = NATIVE_F (= 3 x R/0.30), eff_r = NATIVE_EFF_R (= R), 10% price stop.
    Same-bar flip: close the old trade first so the same name can re-enter.
    Same-bar stop/TP exits realize AFTER new entries (same as the 5-indicator engine).
    Liquidation: realized-plus-open MTM <= 0 at any 1h close; account is wiped."""
    native = set(NATIVE if native is None else native)
    names = names if names is not None else NAMES
    lo_i = int(np.searchsorted(t1, t_lo))
    hi_i = int(np.searchsorted(t1, t_hi))
    nbar = len(c1)
    entries = [[] for _ in range(nbar)]
    exits = [[] for _ in range(nbar)]
    for name in names:
        for tr in books.get(name, ()):
            if 0 <= tr["ei"] < nbar: entries[tr["ei"]].append((name, tr))
            if 0 <= tr["xi"] < nbar: exits[tr["xi"]].append((name, tr))
    E = peak = lowest = START
    mdd = 0.0; open_pos = {}; max_pos = 0
    liquidated = False
    stats = {n: dict(taken=0, skip=0, wins=0, pnl=0.0) for n in names}
    ov = {0: 0, 1: 0, 2: 0}; ov_more = 0; occ_sum = 0
    n_bars = max(0, hi_i - lo_i)

    def _close(name, tr):
        nonlocal E
        pos = open_pos.pop(name, None)
        if pos is None: return
        pnl = sum(item[0] * pos["side"] * (item[1] / pos["ent"] - 1.0) for item in tr["fills"]) - COST
        dollar = pos["E0"] * pos["f"] * pnl
        E += dollar
        st = stats[name]; st["taken"] += 1; st["pnl"] += dollar
        if dollar > 0: st["wins"] += 1
        if log is not None:
            log.append(dict(name=name, side=pos["side"], et=int(t1[tr["ei"]]), xt=int(t1[min(tr["xi"], len(t1) - 1)]),
                            ent=pos["ent"], pnl=dollar, eq=E, E0=pos["E0"], why=tr.get("why", "")))

    def _try_open(name, tr, place=True):
        if name in open_pos: return False, 0.0
        s = tr["side"]
        ent = tr["entry"] * (1.0 + s * LAG)
        sf = abs(ent - tr["stop"]) / ent
        if not np.isfinite(sf) or sf <= 1e-6: return False, 0.0
        if name in native:
            f = NATIVE_F
            eff_r = NATIVE_EFF_R
        else:
            f = r / sf
            eff_r = r
        if place:
            open_pos[name] = dict(side=s, ent=ent, f=f, E0=E, r=eff_r)
        return True, eff_r

    def _mark(m):
        nonlocal peak, mdd, lowest, liquidated
        if m > peak: peak = m
        if peak > 0: mdd = max(mdd, (peak - m) / peak)
        if m < lowest: lowest = m
        if m <= 0: liquidated = True

    for i in range(lo_i, hi_i):
        entering = {name for name, _ in entries[i]}
        for name, tr in exits[i]:
            if name in entering:
                _close(name, tr)
        committed = sum(p["r"] for p in open_pos.values())
        n_open = len(open_pos)
        for name, tr in entries[i]:
            if liquidated or E <= 0:
                continue
            ok, eff_r = _try_open(name, tr, place=False)
            if not ok:
                continue
            if n_open >= M or committed + eff_r > R_tot + 1e-15:
                stats[name]["skip"] += 1
                continue
            ok, eff_r = _try_open(name, tr, place=True)
            if ok:
                committed += eff_r; n_open += 1
        max_pos = max(max_pos, len(open_pos))
        for name, tr in exits[i]:
            if name not in entering:
                _close(name, tr)
        mtm = E
        for p in open_pos.values():
            mtm += p["E0"] * p["f"] * (p["side"] * (c1[i] / p["ent"] - 1.0))
        _mark(mtm)
        k = len(open_pos)
        if k <= 2: ov[k] += 1
        else: ov_more += 1
        occ_sum += k
        if liquidated:
            open_pos.clear(); E = 0.0
            lowest = min(lowest, 0.0)
            rest = hi_i - (i + 1)
            ov[0] += rest
            break

    if not liquidated:
        last = hi_i - 1
        for name in list(open_pos):
            p = open_pos.pop(name)
            pnl = p["side"] * (c1[last] / p["ent"] - 1.0) - COST
            dollar = p["E0"] * p["f"] * pnl
            E += dollar
            st = stats[name]; st["taken"] += 1; st["pnl"] += dollar
            if dollar > 0: st["wins"] += 1
            if log is not None:
                log.append(dict(name=name, side=p["side"], et=-1, xt=int(t1[last]), ent=p["ent"],
                                pnl=dollar, eq=E, E0=p["E0"], why="open@end"))
            if E > peak: peak = E
            if peak > 0: mdd = max(mdd, (peak - E) / peak)
            if E < lowest: lowest = E
            if E <= 0:
                liquidated = True; E = 0.0; lowest = min(lowest, 0.0)
                break
    end_eq = 0.0 if liquidated else E
    return dict(eq=end_eq, taken=sum(s["taken"] for s in stats.values()),
                skipped=sum(s["skip"] for s in stats.values()),
                mdd=mdd, lowest=lowest, max_pos=max_pos, liquidated=liquidated,
                stats=stats, ov=ov, ov_more=ov_more, occ_sum=occ_sum, n_bars=n_bars)


# ===================== per-series context (was module-level in osom6_book_v2) =====================
# Signal functions / run_book read these as GLOBALS: D (_ok1), ATR4 (_sl/_tp_px), CHOP4/ADX4/TREND4 (_ok1),
# t1/c1 (run_book, map_4h_to_1h), and the 4h C2 arrays df/o4/h4/l4/c4/a4/idx4/i0_4/VOTE_L/VOTE_S
# (conf_trades, map_4h_to_1h). build_context(Dx) recomputes ALL of them from Dx, so every synthetic
# path gets its own ATR4 and its own C2 4h signals.
D = t1 = c1 = ATR4 = CHOP4 = ADX4 = TREND4 = None
df = o4 = h4 = l4 = c4 = a4 = idx4 = VOTE_L = VOTE_S = None
i0_4 = 0

def _s(x):
    return x.fillna(False).to_numpy(dtype=bool)

def build_context(Dx):
    global D, t1, c1, ATR4, CHOP4, ADX4, TREND4
    global df, o4, h4, l4, c4, a4, idx4, i0_4, VOTE_L, VOTE_S
    D = Dx
    t1, c1 = Dx["time"], Dx["close"]
    # 4h ATR + Chop + ADX + ema trend, mapped to each 1h open (last COMPLETED 4h bar only)
    B4 = _agg(Dx["time"], Dx["open"], Dx["high"], Dx["low"], Dx["close"], Dx["volume"], 4 * H1)
    trb = _true_range(B4["high"], B4["low"], B4["close"])
    atr4 = _rma_seeded(trb, 14)
    ATR4 = _map_completed(B4["time"], 4 * H1, Dx["time"], np.nan, atr4)
    Lchop = 14
    trs = pd.Series(trb).rolling(Lchop).sum().to_numpy()
    hh4 = pd.Series(B4["high"]).rolling(Lchop).max().to_numpy()
    ll4 = pd.Series(B4["low"]).rolling(Lchop).min().to_numpy()
    with np.errstate(invalid="ignore", divide="ignore"):
        chop4 = 100 * np.log10(trs / (hh4 - ll4)) / np.log10(Lchop)
    chop4[:Lchop] = np.nan; chop4[~(hh4 > ll4)] = np.nan
    up4 = np.r_[0, B4["high"][1:] - B4["high"][:-1]]
    dn4 = np.r_[0, B4["low"][:-1] - B4["low"][1:]]
    pdm = np.where((up4 > dn4) & (up4 > 0), up4, 0.0)
    mdm = np.where((dn4 > up4) & (dn4 > 0), dn4, 0.0)
    sA = _rma_seeded(trb, 14); sP = _rma_seeded(pdm, 14); sM = _rma_seeded(mdm, 14)
    with np.errstate(invalid="ignore", divide="ignore"):
        di_p = 100 * sP / sA; di_m = 100 * sM / sA
        dx4 = np.where(np.isfinite(di_p) & np.isfinite(di_m),
                       np.where(di_p + di_m != 0, 100 * np.abs(di_p - di_m) / (di_p + di_m), 0.0), np.nan)
    adx4 = _rma_seeded(dx4, 14)
    e9_4, e21_4 = _ema_arr(B4["close"], 9), _ema_arr(B4["close"], 21)
    trend4 = np.where(e9_4 > e21_4, 1.0, np.where(e9_4 < e21_4, -1.0, 0.0))
    CHOP4 = _map_completed(B4["time"], 4 * H1, Dx["time"], np.nan, chop4)
    ADX4 = _map_completed(B4["time"], 4 * H1, Dx["time"], np.nan, adx4)
    TREND4 = _map_completed(B4["time"], 4 * H1, Dx["time"], 0.0, trend4).astype(int)

    # ----- C2 4h inputs (locked ports: Chop<30 AND'd, strict new-edge, SL 1.5) -----
    df4 = pd.DataFrame({"open": Dx["open"], "high": Dx["high"], "low": Dx["low"],
                        "close": Dx["close"], "volume": Dx["volume"]},
                       index=pd.to_datetime(Dx["time"], unit="ms"))
    df = df4.resample("4h").agg({"open": "first", "high": "max", "low": "min", "close": "last",
                                 "volume": "sum"}).dropna()
    c, o, h, lo, v = df["close"], df["open"], df["high"], df["low"], df["volume"]
    ema9 = c.ewm(span=9, adjust=False).mean()
    ema21 = c.ewm(span=21, adjust=False).mean()
    atr = pd.Series(_rma_seeded(_true_range(h.to_numpy(), lo.to_numpy(), c.to_numpy()), 14), index=df.index)
    atr_sma = atr.rolling(20).mean()
    vol_sma = v.rolling(20).mean()
    ph10, pl10 = h.rolling(10).max().shift(1), lo.rolling(10).min().shift(1)
    ph20, pl20 = h.rolling(20).max().shift(1), lo.rolling(20).min().shift(1)
    hn, ln = h.rolling(14).max(), lo.rolling(14).min()
    chop = 100 * np.log10(atr.rolling(14).sum() / (hn - ln).replace(0, np.nan)) / np.log10(14)
    rng = (h - lo).replace(0, np.nan)
    body = c - o
    chop_m = chop < 30
    reg_l = _s((c > ph20) & (atr > atr_sma) & chop_m)
    reg_s = _s((c < pl20) & (atr > atr_sma) & chop_m)
    bv_l = _s((c > ph10) & (v > vol_sma * 1.5) & chop_m)
    bv_s = _s((c < pl10) & (v > vol_sma * 1.5) & chop_m)
    od_l = _s((body > atr * 1.0) & (ema9 > ema21) & ((c - lo) / rng >= 0.75) & (v > vol_sma) & chop_m)
    od_s = _s((-body > atr * 1.0) & (ema9 < ema21) & ((h - c) / rng >= 0.75) & (v > vol_sma) & chop_m)
    mom_l = _s((c > ema9) & (ema9 > ema21) & (atr > atr_sma) & ((c - lo) / rng >= 0.50) & chop_m)
    mom_s = _s((c < ema9) & (ema9 < ema21) & (atr > atr_sma) & ((h - c) / rng >= 0.50) & chop_m)
    o4, h4, l4, c4 = df["open"].to_numpy(), h.to_numpy(), lo.to_numpy(), c.to_numpy()
    a4 = atr.to_numpy()
    idx4 = df.index.values.astype("datetime64[ms]").astype(np.int64)
    i0_4 = int(np.where(np.isfinite(a4))[0][0])
    VOTE_L = (reg_l | bv_l).astype(int) + od_l.astype(int) + mom_l.astype(int)
    VOTE_S = (reg_s | bv_s).astype(int) + od_s.astype(int) + mom_s.astype(int)

def build_books(Dx):
    """Rebuild context for Dx, then the 5 locked books (same params as osom6_book_v2)."""
    build_context(Dx)
    b = {}
    b["K8"] = osom_k8(Dx, dict(px_stop=0.10))
    b["V7"] = osom_v7(Dx, dict(px_stop=0.10))
    b["R0"] = osom_r0(Dx, dict(px_stop=0.10))
    b["C1"] = osom_c1(Dx)
    b["C2"] = map_4h_to_1h(conf_trades(2))
    return b


# ===================================== helpers =====================================
def year_ms(y):
    return int(pd.Timestamp(f"{y}-01-01").value // 1_000_000)

def _pct(a, qs=(5, 25, 50, 75, 95)):
    a = np.asarray(a, float)
    return np.percentile(a, qs) if len(a) else np.full(len(qs), np.nan)

def _fmt_pcts(a, money=True):
    p = _pct(a)
    f = (lambda x: f"${x:,.0f}") if money else (lambda x: f"{x:.1f}%")
    return "  ".join(f"p{q}={f(x)}" for q, x in zip((5, 25, 50, 75, 95), p))

rng_master = np.random.SeedSequence(SEED)
rngA_seed, rngB_seed = rng_master.spawn(2)
rngA, rngB = np.random.default_rng(rngA_seed), np.random.default_rng(rngB_seed)
print(f"RNG seed = {SEED}  (numpy SeedSequence; Part A and Part B use separate child streams)")
print(f"Locked plan: R={R_LOCK*100:.0f}%  M={M_LOCK}  signals={','.join(NAMES)}  start ${START:,.0f}")

# ============================ Part A — trade bootstrap ============================
t_ab = time.time()
print("\n==================== PART A — real 2021-2026 trades, bootstrap of 100 ====================")
BOOKS_REAL = build_books(D_REAL)
print("  trades built: " + "  ".join(f"{n}={len(BOOKS_REAL[n])}" for n in NAMES) + "  (expected K8=101 V7=77 R0=52 C1=100 C2=124)")
T_LO_ALL, T_HI_ALL = year_ms(2021), year_ms(2027)
CLIP_ALL = {n: clip_window(BOOKS_REAL[n], t1, T_LO_ALL, T_HI_ALL, c1) for n in NAMES}
set_native(R_LOCK)
LOG = []
resA = run_book(CLIP_ALL, T_LO_ALL, T_HI_ALL, R_LOCK, M_LOCK, M_LOCK * R_LOCK, names=NAMES, log=LOG)
winsA = sum(1 for x in LOG if x["pnl"] > 0)
print(f"  continuous real run: end ${resA['eq']:,.0f}  trades {len(LOG)}  win {winsA/max(1,len(LOG))*100:.1f}%  "
      f"maxDD {resA['mdd']*100:.1f}%  min eq ${resA['lowest']:,.0f}  "
      f"{'LIQUIDATED' if resA['liquidated'] else 'never liquidated'}   (expected ~$265.5M, 439 trades)")
RET = np.array([x["pnl"] / x["E0"] for x in LOG if x["E0"] > 0], float)
RET_NAME = np.array([x["name"] for x in LOG if x["E0"] > 0])
print(f"  per-trade return (% of equity at entry): n={len(RET)}  mean {RET.mean()*100:+.2f}%  "
      f"median {np.median(RET)*100:+.2f}%  worst {RET.min()*100:+.2f}%  best {RET.max()*100:+.2f}%")
print("  by signal: " + "  ".join(
    f"{n}: n={int((RET_NAME == n).sum())} avg {RET[RET_NAME == n].mean()*100:+.2f}%"
    for n in NAMES if (RET_NAME == n).any()))

idx = rngA.integers(0, len(RET), size=(N_SIMS, N_TRADES))
R_DRAW = RET[idx]
growth = np.maximum(1.0 + R_DRAW, 0.0)                  # a single draw <= -100% wipes the account
EQ = START * np.cumprod(growth, axis=1)
LIQ = (EQ <= 0).any(axis=1)
curve = np.hstack([np.full((N_SIMS, 1), START), EQ])
peak = np.maximum.accumulate(curve, axis=1)
DD = np.where(peak > 0, (peak - curve) / peak, 0.0).max(axis=1) * 100
MINEQ = curve.min(axis=1)
END = EQ[:, -1]
print(f"\n  {N_SIMS:,} sims x {N_TRADES} trades drawn with replacement, compounded from ${START:,.0f}")
print(f"  liquidated: {LIQ.mean()*100:.2f}%   ended above $1,000: {(END > START).mean()*100:.1f}%   "
      f"ended below $500: {(END < 500).mean()*100:.1f}%")
print(f"  ending equity: {_fmt_pcts(END)}")
print(f"  maxDD: median {np.median(DD):.1f}%  p95 {np.percentile(DD, 95):.1f}%  worst {DD.max():.1f}%")
print(f"  min equity: worst-case ${MINEQ.min():,.0f}  p5 ${np.percentile(MINEQ, 5):,.0f}  median ${np.median(MINEQ):,.0f}")
ex = 0
w_ex = int((R_DRAW[ex] > 0).sum())
mix = "  ".join(f"{n}={int((RET_NAME[idx[ex]] == n).sum())}" for n in NAMES)
print(f"  example sim #1: {w_ex} wins / {N_TRADES - w_ex} losses   end ${END[ex]:,.0f}   maxDD {DD[ex]:.1f}%   "
      f"min ${MINEQ[ex]:,.0f}   mix: {mix}")
print("  CAVEAT: trades are compounded one after another; the real book runs up to 4 at once, so")
print("          clustered losses (several stops on the same move) are NOT captured here — Part B does that.")
print(f"  Part A time {time.time() - t_ab:.0f}s")

# ===================== Part B — synthetic future BTC paths =====================
# Per-bar relatives from the full real history: bar k is described relative to the previous close.
_c = D_REAL["close"]
REL_LR = np.log(_c[1:] / _c[:-1])
REL_O = D_REAL["open"][1:] / _c[:-1]
REL_H = D_REAL["high"][1:] / _c[:-1]
REL_L = D_REAL["low"][1:] / _c[:-1]
REL_V = D_REAL["volume"][1:].astype(float)
NREL = len(REL_LR)

def make_path(rg):
    """Real warm-up (last WARM_BARS bars) + HORIZON synthetic bars, continuous hourly timestamps."""
    W = {k: np.asarray(D_REAL[k][-WARM_BARS:]) for k in D_REAL}
    P0, T0 = float(W["close"][-1]), int(W["time"][-1])
    parts, got = [], 0
    while got < HORIZON:
        L = int(rg.geometric(1.0 / BLOCK)) if STATIONARY else BLOCK
        s = int(rg.integers(0, NREL))
        parts.append((s + np.arange(L)) % NREL)       # circular wrap
        got += L
    ix = np.concatenate(parts)[:HORIZON]
    cl = P0 * np.exp(np.cumsum(REL_LR[ix]))
    prev = np.r_[P0, cl[:-1]]
    op = prev * REL_O[ix]
    hi = np.maximum(prev * REL_H[ix], np.maximum(op, cl))
    lw = np.minimum(prev * REL_L[ix], np.minimum(op, cl))
    tm = T0 + H1 * np.arange(1, HORIZON + 1, dtype=np.int64)
    Dp = dict(time=np.r_[W["time"].astype(np.int64), tm],
              open=np.r_[W["open"], op], high=np.r_[W["high"], hi], low=np.r_[W["low"], lw],
              close=np.r_[W["close"], cl], volume=np.r_[W["volume"].astype(float), REL_V[ix]])
    return Dp, len(W["time"])

if N_PATHS > 0:
    print(f"\n==================== PART B — {N_PATHS} synthetic 1-year BTC paths ====================")
    wt = D_REAL["time"][-WARM_BARS:]
    gaps = int((np.diff(wt) != H1).sum())
    print(f"  block bootstrap of {NREL:,} real 1h bars, {'stationary (mean' if STATIONARY else 'circular (fixed'} "
          f"{BLOCK}h blocks), {HORIZON:,} bars/path, from last real close ${D_REAL['close'][-1]:,.0f}")
    print(f"  warm-up: last {WARM_BARS:,} real bars ({pd.to_datetime(wt[0], unit='ms'):%Y-%m-%d} -> "
          f"{pd.to_datetime(wt[-1], unit='ms'):%Y-%m-%d}, {gaps} timestamp gaps); trades only in synthetic year")
    rows = []; t_b = time.time()
    for k in range(N_PATHS):
        Dp, n_warm = make_path(rngB)
        books = build_books(Dp)                       # rebuilds ATR4/CHOP4/ADX4/TREND4, C2 4h arrays, t1/c1
        assert t1 is Dp["time"] and c1 is Dp["close"] and len(ATR4) == len(Dp["time"])
        t_lo = int(Dp["time"][n_warm]); t_hi = int(Dp["time"][-1]) + H1
        clip = {n: clip_window(books[n], t1, t_lo, t_hi, c1) for n in NAMES}
        set_native(R_LOCK)
        res = run_book(clip, t_lo, t_hi, R_LOCK, M_LOCK, M_LOCK * R_LOCK, names=NAMES)
        wins = sum(s["wins"] for s in res["stats"].values())
        rows.append(dict(eq=res["eq"], liq=res["liquidated"], mdd=res["mdd"] * 100, low=res["lowest"],
                         n=res["taken"], win=(wins / res["taken"] * 100) if res["taken"] else np.nan,
                         bh=(Dp["close"][-1] / Dp["close"][n_warm - 1] - 1) * 100,
                         sig={n: (res["stats"][n]["taken"], res["stats"][n]["wins"], res["stats"][n]["pnl"])
                              for n in NAMES}))
        if (k + 1) % 25 == 0 or k == 0:
            el = time.time() - t_b
            print(f"    path {k+1}/{N_PATHS}  {el:.0f}s elapsed  (~{el/(k+1)*(N_PATHS-k-1)/60:.1f} min left)")
    EQB = np.array([r["eq"] for r in rows]); LQB = np.array([r["liq"] for r in rows])
    MDB = np.array([r["mdd"] for r in rows]); LOB = np.array([r["low"] for r in rows])
    NB = np.array([r["n"] for r in rows]); WB = np.array([r["win"] for r in rows], float)
    BHB = np.array([r["bh"] for r in rows])
    print(f"\n  RESULTS over {N_PATHS} synthetic years (R=10%, M=4, NO_Z2, fresh $1,000 each path)")
    print(f"  liquidated: {LQB.mean()*100:.1f}%   profitable: {(EQB > START).mean()*100:.1f}%   "
          f"lost >50%: {(EQB < 500).mean()*100:.1f}%")
    print(f"  ending equity: {_fmt_pcts(EQB)}")
    print(f"  maxDD:         {_fmt_pcts(MDB, money=False)}")
    print(f"  lowest equity: worst ${LOB.min():,.0f}   p5 ${np.percentile(LOB, 5):,.0f}   median ${np.median(LOB):,.0f}")
    print(f"  trades/year: median {np.median(NB):.0f} (p5 {np.percentile(NB, 5):.0f}, p95 {np.percentile(NB, 95):.0f})   "
          f"win%: {_fmt_pcts(WB[np.isfinite(WB)], money=False)}")
    print(f"  BTC buy&hold over the same synthetic year: {_fmt_pcts(BHB, money=False)}")
    print(f"  {'signal':<7}{'med trades':>11}{'pooled win%':>12}{'median PnL $':>14}{'p5 PnL $':>11}{'p95 PnL $':>11}")
    for n in NAMES:
        tk = np.array([r["sig"][n][0] for r in rows]); wn = np.array([r["sig"][n][1] for r in rows])
        pn = np.array([r["sig"][n][2] for r in rows])
        print(f"  {n:<7}{np.median(tk):>11.0f}{(wn.sum() / max(1, tk.sum()) * 100):>11.1f}%"
              f"{np.median(pn):>+14,.0f}{np.percentile(pn, 5):>+11,.0f}{np.percentile(pn, 95):>+11,.0f}")
    print(f"  Part B time {(time.time() - t_b)/60:.1f} min")
    print("  NOTE: block bootstrap reshuffles real 2021-2026 BTC months; it keeps realistic volatility and")
    print("        intra-month structure but cannot invent regimes BTC hasn't shown (e.g. a -80% year).")
else:
    print("\nPart B skipped (OSOM_MC_PATHS=0).")
