"""MRV08 — Daily gap-fill (adapted for 24/7 crypto)
HYPOTHESIS: On 1d bars, if the day opens well BELOW the prior close (gap-down),
go LONG expecting reversion toward prior close. SL below the day open.

IMPORTANT: Crypto trades 24/7 — open[i] vs close[i-1] gaps are typically <0.1%
on Deribit 1d resampled bars (max gap found = 0.089%). True overnight gaps don't exist.

ADAPTED INTERPRETATION: "Gap" operationalized as a large down day:
  - Bar i closes gap_thresh% below prior close (big intraday decline)
  - Enter LONG at close[i], TP = close[i-1] (full reversion), SL below
  - This captures the "gap fill" spirit: buy after a large daily drop expecting recovery
"""
import sys
sys.path.insert(0, "/opt/docker/PythagorasGoal/scripts/research/alt")
import altlib as al
import numpy as np

# Grid: (gap_thresh, sl_frac, max_bars, label)
CONFIGS = [
    (0.015, 0.015, 3, "down1.5%_sl1.5%_3d"),  # moderate down day, 3d hold
    (0.020, 0.020, 3, "down2%_sl2%_3d"),       # bigger down day only
    (0.015, 0.020, 5, "down1.5%_sl2%_5d"),     # more time to recover
    (0.020, 0.015, 5, "down2%_sl1.5%_5d"),     # tighter SL, longer hold
]


def make_entries(df, gap_thresh=0.015, sl_frac=0.015, max_bars=3):
    """
    Reversion after a large down day:
      - If close[i] < close[i-1] * (1 - gap_thresh): "gap" trigger
      - Entry: LONG at close[i]
      - TP: close[i-1] (prior close recovery)
      - SL: close[i] * (1 - sl_frac)
      - Hold up to max_bars days
    Causal: uses only close[i] and close[i-1].
    """
    c = df["close"].values.astype(float)
    n = len(df)
    entries = [None] * n

    for i in range(1, n):
        prior_close = c[i - 1]
        cur_close = c[i]

        if prior_close <= 0:
            continue

        ret = (cur_close - prior_close) / prior_close
        if ret >= -gap_thresh:
            continue

        tp = prior_close
        sl = cur_close * (1.0 - sl_frac)

        if tp <= cur_close or sl >= cur_close:
            continue

        entries[i] = {"dir": +1, "tp": tp, "sl": sl, "max_bars": max_bars}

    return entries


# Diagnostic: check trade counts per config
print("=== MRV08 Daily Gap-Fill (Crypto Adapted) ===")
print("NOTE: True overnight gaps don't exist in 24/7 crypto.")
print("Using 'large down day' as gap proxy (close[i] < close[i-1] * (1-thresh))")
print()

for gt, sf, mb, label in CONFIGS:
    df_btc = al.get("BTC", "1d")
    ent_btc = make_entries(df_btc, gt, sf, mb)
    n_btc = sum(1 for e in ent_btc if e is not None)
    df_eth = al.get("ETH", "1d")
    ent_eth = make_entries(df_eth, gt, sf, mb)
    n_eth = sum(1 for e in ent_eth if e is not None)
    print(f"  {label}: BTC trades={n_btc}, ETH trades={n_eth}")

print()

# Run all configs
best_rep = None
best_min_hold = -999.0

for gap_thresh, sl_frac, max_bars, label in CONFIGS:
    name = f"MRV08-{label}"

    def make_fn(gt=gap_thresh, sf=sl_frac, mb=max_bars):
        return lambda df: make_entries(df, gap_thresh=gt, sl_frac=sf, max_bars=mb)

    rep = al.study_signals(name, make_fn(), tfs=("1d",))

    v = rep["verdict"]
    min_hold = v.get("best_holdout_sharpe", -999)
    print(f"\n--- Config: {label} ---")
    print(al.fmt(rep))
    print("JSON:", al.as_json(rep))

    if min_hold > best_min_hold:
        best_min_hold = min_hold
        best_rep = rep

print("\n\n=== BEST CONFIG ===")
print(al.fmt(best_rep))
print("JSON:", al.as_json(best_rep))
