# RohOnChain session-open, rewritten on oslib.
# In Colab:
#   !wget -q -O oslib.py https://osom-boba.pages.dev/colab/oslib.py
#   !wget -q -O rs_fix.py https://osom-boba.pages.dev/colab/rs_fix.py
#   %run rs_fix.py
# On the box this file only smokes synthetic data (no real backtest).
from oslib import *
import sys
from pathlib import Path
import numpy as np
import pandas as pd

SESSIONS = (("Asia", 0, 0), ("London", 7, 0), ("NY", 13, 30))
# Skip if stop distance would make round-trip costs more than 0.5R.
MIN_RISK = 2 * 2 * COST  # 0.48%

def _colour(o, c):
    return np.where(c > o, 1, np.where(c < o, -1, 0)).astype("int8")

def _htf_bias(df1h, t_ms):
    """Closed prior day vs 4h agreement, else prior week colour. 0 = no trade."""
    ts = df1h["time"].to_numpy(dtype="int64")
    o, h, l, c = (df1h[k].to_numpy(dtype=float) for k in ("open", "high", "low", "close"))
    day = pd.DataFrame({"g": ts // D1, "open": o, "high": h, "low": l, "close": c}).groupby("g").agg(
        open=("open", "first"), high=("high", "max"), low=("low", "min"), close=("close", "last"))
    d_g = day.index.to_numpy()
    d_col = _colour(day.open.to_numpy(), day.close.to_numpy())
    h4 = pd.DataFrame({"g": ts // H4, "open": o, "close": c}).groupby("g").agg(open=("open", "first"), close=("close", "last"))
    h4_g, h4_col = h4.index.to_numpy(), _colour(h4.open.to_numpy(), h4.close.to_numpy())
    week_ms = 7 * D1
    mon = ((ts + 3 * D1) // week_ms) * week_ms - 3 * D1
    wk = pd.DataFrame({"g": mon, "open": o, "close": c}).groupby("g").agg(open=("open", "first"), close=("close", "last"))
    w_g, w_col = wk.index.to_numpy(), _colour(wk.open.to_numpy(), wk.close.to_numpy())

    def closed(groups, vals, key):
        j = int(np.searchsorted(groups, key, side="left"))
        if j < len(groups) and groups[j] == key:
            return int(vals[j])
        j = int(np.searchsorted(groups, key, side="right")) - 1
        return int(vals[j]) if j >= 0 else 0

    day_id = t_ms // D1 - 1
    dcol = closed(d_g, d_col, day_id)
    c4 = closed(h4_g, h4_col, (t_ms // H4 - 1) * H4)
    this_mon = ((t_ms + 3 * D1) // week_ms) * week_ms - 3 * D1
    cw = closed(w_g, w_col, this_mon - week_ms)
    if dcol != 0 and dcol == c4:
        return dcol
    if dcol != c4:
        return cw
    return 0

def rs_signals(df15, df1h, placebo=False, stop_mode="range", min_risk=MIN_RISK):
    """Build 15m signal and stop-price arrays for simulate(..., entry='next_open').

    stop_mode:
      'retest' — batch9 bug: stop at the retest-bar extreme (often a few ticks, so
                 R is dominated by 0.24% round-trip costs).
      'range'  — fix: stop at the opening-range far side, skip if risk < min_risk.
    """
    t = df15["time"].to_numpy(dtype="int64")
    o, h, l, c = (df15[k].to_numpy(dtype=float) for k in ("open", "high", "low", "close"))
    n = len(t)
    sig = np.zeros(n, dtype=int)
    stp = np.full(n, np.nan)
    minute = ((t // 60000) % 1440).astype("int32")
    for sname, shour, smin in SESSIONS:
        start_min = shour * 60 + smin
        for i0 in np.where(minute == start_min)[0]:
            if i0 + 4 >= n:
                continue
            if any(t[i0 + k] - t[i0 + k - 1] != M15 for k in range(1, 4)):
                continue
            t0 = int(t[i0])
            if placebo:
                sides = (1, -1)
            else:
                bias = _htf_bias(df1h, t0) if df1h is not None else 0
                if bias == 0:
                    continue
                sides = (bias,)
            first_hi, first_lo = float(h[i0]), float(l[i0])
            for side in sides:
                lvl = first_hi if side > 0 else first_lo
                broke = False
                dip_i = conf_i = None
                for k in range(i0 + 1, i0 + 4):
                    if not broke:
                        if (h[k] > lvl) if side > 0 else (l[k] < lvl):
                            broke = True
                        continue
                    if (l[k] <= lvl) if side > 0 else (h[k] >= lvl):
                        dip_i = k
                    if dip_i is not None and ((c[k] > lvl) if side > 0 else (c[k] < lvl)):
                        conf_i = k
                        break
                if conf_i is None or dip_i is None:
                    continue
                if stop_mode == "retest":
                    stop = float(l[dip_i]) if side > 0 else float(h[dip_i])
                else:
                    stop = first_lo if side > 0 else first_hi
                # next-open fill is simulate's job; require the confirm close already on the right side
                preview = float(c[conf_i])
                if side * (preview - stop) <= 0:
                    continue
                if min_risk and abs(preview - stop) / preview < min_risk:
                    continue
                if sig[conf_i] != 0:
                    continue
                sig[conf_i] = int(side)
                stp[conf_i] = stop
                break
    return sig, stp

def rs_run(df15, df1h, target_R=1.0, placebo=False, stop_mode="range", min_risk=MIN_RISK, be_at=None):
    sig, stp = rs_signals(df15, df1h, placebo=placebo, stop_mode=stop_mode, min_risk=min_risk)
    be = be_at if be_at is not None else (1.0 if target_R > 1.0 else None)
    return simulate(df15, sig, stop=stp, target=float(target_R), time_stop=96,
                    be_at=be, entry="next_open", check=True)

def _summarize(trades, label):
    tr = standardize(trades)
    n = len(tr)
    if not n:
        print(f"  {label}: 0 trades")
        return
    R = np.array([t["R"] for t in tr], dtype=float)
    risk = np.array([t["risk"] for t in tr], dtype=float)
    why = pd.Series([t["why"] for t in tr])
    cost_R = 2 * COST / np.maximum(risk, 1e-12)
    print(f"  {label}: n={n}  win%={(R>0).mean()*100:.1f}  avgR={np.nanmean(R):.2f}  "
          f"median risk%={np.nanmedian(risk)*100:.3f}  median cost_R={np.nanmedian(cost_R):.2f}  "
          f"why={why.value_counts().to_dict()}")

def _smoke():
    print("rs_fix smoke — synthetic 15m only (no real market data)")
    h1 = synthetic_1h(n=8000, seed=9, start="2023-02-15")
    d15 = synthetic_15m_from_1h(h1, seed=11)
    # Buggy batch9 rule: retest stop, no min-risk filter (same entry otherwise).
    buggy_1 = rs_run(d15, h1, target_R=1.0, stop_mode="retest", min_risk=0.0)
    fixed_1 = rs_run(d15, h1, target_R=1.0, stop_mode="range", min_risk=MIN_RISK)
    buggy_p = rs_run(d15, h1, target_R=1.0, stop_mode="retest", min_risk=0.0, placebo=True)
    fixed_p = rs_run(d15, h1, target_R=1.0, stop_mode="range", min_risk=MIN_RISK, placebo=True)
    _summarize(buggy_1, "BUGGY retest-stop 1R")
    _summarize(fixed_1, "FIXED range-stop + min-risk 1R")
    # Root-cause checks on the buggy book (when it traded).
    if buggy_1:
        raw = []
        for t in buggy_1:
            if t["why"] == "SL" and np.isfinite(t["entry"]) and np.isfinite(t["stop"]) and t["risk"] > 0:
                raw.append(t["side"] * (t["exit"] - t["entry"]) / abs(t["entry"] - t["stop"]))
        if raw:
            print(f"  BUGGY SL raw price-R (no costs): mean={np.mean(raw):.3f}  "
                  f"(~-1.0 means the stop side is correct; the hole is the denominator)")
        risk = np.array([t["risk"] for t in buggy_1], dtype=float)
        print(f"  BUGGY share of stops tighter than round-trip cost 0.24%: {(risk < 2*COST).mean()*100:.0f}%")
    assert len(fixed_1) >= 0
    # evaluate/report path (synthetic frame as asset — no real load)
    rows = [
        evaluate("RS-bug-retest", buggy_1, buggy_p, h1),
        evaluate("RS-fix-range", fixed_1, fixed_p, h1),
    ]
    report(rows, title="RS session-open (synthetic smoke)", out_dir=Path("/tmp/rs_fix_smoke"),
           notes=("Root cause: batch9 stopped at the retest-bar extreme, often 0.04–0.13% from entry. "
                  "Stops were on the correct side (SL raw R = -1). net_R = price_R - 0.24%/risk, so "
                  "avgR printed near -2R and many 1R targets were net losers. Fix: opening-range far-side "
                  "stop plus skip when risk < 2x round-trip cost."),
           write_csv=False)
    print("RS_FIX SMOKE OK")

def _colab():
    print("RS session-open on hosted 15m (oslib)")
    rows, erows = [], []
    for asset, bucket in (("btc", rows), ("eth", erows)):
        h1 = load(asset, "1h")
        d15 = load(asset, "15m")
        for tgt, be in ((1.0, None), (2.0, 1.0)):
            tr = rs_run(d15, h1, target_R=tgt, stop_mode="range", min_risk=MIN_RISK, be_at=be)
            plc = rs_run(d15, h1, target_R=tgt, stop_mode="range", min_risk=MIN_RISK, be_at=be, placebo=True)
            bucket.append(evaluate(f"RS-fix-{int(tgt)}R", tr, plc, h1))
            _summarize(tr, f"{asset} RS-fix-{int(tgt)}R")
    report(rows, erows, title="RS session-open (fixed stop)")

if __name__ == "__main__" or True:
    # `%run` in Colab sets __name__ to the filename; keep this always-on, but
    # refuse a real-data run on the box.
    if "--smoke" in sys.argv or not in_colab():
        _smoke()
        raise SystemExit(0)
    _colab()
