"""
exit_x1.py -- [2026-10-23] The user's exit X1 "SELL THE STALL AT THE TOP" (from QUBT 5/20/2025: the run topped 12.10 at
10:22-10:23, then 6 bars flat 12.00-12.10 with the volume shrinking and the 5-min buy share sliding 69% -> 61%; the user's sell
= 10:25; 10:26 closed 11.99 under every close of the flat stretch, then 11.72 by 10:30). Pairs with R1C; replaces the 1/4
give-back, which sells normal retests (QUBT 9:53, JOBY, DERM).
  STOP     under the setup's support (caller) -- until X1 is armed nothing else sells
  ARM      the high since the buy >= arm_pct (2%) above the buy; once armed the stop moves up to break-even (be_pct 0.2% over
           the buy, at a bar close)
  STALL    the last stall_n (5) finished bars before the current one: their high-low span <= stall_k (2.5) x the mean 1-min
           range of the 15 bars before, and their high is within 0.2% of the high since the buy (a stall AT the top, not a
           pullback under an earlier top)
  FADE     the 5-min buy share at the last stall bar < the 5-min buy share stall_n bars earlier, AND the mean volume of the last
           3 stall bars <= vol_fade (0.8) x the biggest bar of the last 10
  BREAK    the current finished bar closes down (under the bar before) AND under the LOWEST CLOSE of the stall bars -> sell
Decided at a bar close only (finished bars), sold at the next price. Untested on 2 years. Pure function, no orders.
"""
DEFAULTS = {"arm_pct": 2.0, "be_pct": 0.2, "stall_n": 5, "stall_k": 2.5, "vol_fade": 0.8}


def _minute(t):
    from datetime import datetime, timezone
    from zoneinfo import ZoneInfo
    if not isinstance(t, datetime):
        t = datetime.fromtimestamp(t, timezone.utc)
    t = t.astimezone(ZoneInfo("America/New_York"))
    return (t.hour - 9) * 60 + t.minute - 30


def check(done, flow, entry, entry_i, c=None):
    """done: finished bars of the day; entry_i: index in done of the buy bar. -> (sell?, why)"""
    c = {**DEFAULTS, **(c or {})}
    since = done[entry_i:]
    if len(since) < 2:
        return False, "too early"
    peak = max(b["h"] for b in since)
    if peak < entry * (1 + c["arm_pct"] / 100):
        return False, "not armed"
    b, p = done[-1], done[-2]
    if b["c"] < entry * (1 + c["be_pct"] / 100):
        return True, f"X1 break-even: armed (peak {peak:.4g}), close {b['c']:.4g} back at the buy {entry:.4g}"
    n = c["stall_n"]
    W = done[-1 - n:-1]
    if len(W) < n or len(done) < n + 16 or entry_i > len(done) - 1 - n:
        return False, "no stall yet"
    span = max(x["h"] for x in W) - min(x["l"] for x in W)
    pre = done[-1 - n - 15:-1 - n]
    rng = sum(x["h"] - x["l"] for x in pre) / len(pre)
    if span > c["stall_k"] * rng:
        return False, f"no stall: span {span:.4g} > {c['stall_k']} x range {rng:.4g}"
    hi_before = max(x["h"] for x in done[entry_i:-1 - n]) if entry_i < len(done) - 1 - n else 0
    if hi_before and max(x["h"] for x in W) < hi_before * 0.998:
        return False, "the stall is under an earlier top (pullback, not the top)"
    fb, fs = flow["buy"], flow["sell"]
    def bs5(m):
        B = sum(fb[max(0, m - 4):m + 1]); S = sum(fs[max(0, m - 4):m + 1]); return B / (B + S) if B + S else 0.5
    m1, m0 = _minute(W[-1]["t"]), _minute(W[0]["t"]) - 1
    if not bs5(m1) < bs5(m0):
        return False, f"buyers not fading: 5-min {bs5(m0):.0%} -> {bs5(m1):.0%}"
    big = max(x["v"] for x in done[-11:-1])
    v3 = sum(x["v"] for x in W[-3:]) / 3
    if v3 > c["vol_fade"] * big:
        return False, f"volume not fading: {v3:.0f} > {c['vol_fade']} x {big:.0f}"
    lowc = min(x["c"] for x in W)
    if b["c"] < p["c"] and b["c"] < lowc:
        return True, (f"X1 stall break: {n} bars flat (span {span:.4g}), 5-min buyers {bs5(m0):.0%} -> {bs5(m1):.0%}, "
                      f"volume fading, close {b['c']:.4g} < stall low close {lowc:.4g} (peak {peak:.4g})")
    return False, "stall, waiting for the break"
