"""
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
FADE INTO RESISTANCE (2026-10-23, from HELP 7/3/25: 10:05-10:09 price 7.795 -> 7.83 while the 5-min buy share fell 63% -> 38%;
  10:10 last push to 7.90 on 99% buyers, 0.6% under the day's open 7.95; 10:11 95% sellers -> the user's sell). Sell when ALL:
    armed (as above); the current finished bar is a SELLER bar (1-min buy share <= seller_bs 25%) with the 5-min buy share
    < 50% and a close under the bar before; DIVERGENCE: over the div_n (5) bars before it the close rose while the 5-min buy
    share fell by >= div_drop (10 points); RESISTANCE: the peak since the buy is within res_pct (1%) under the day's open or
    the day's high before the buy (res_required False = skip this part); the dip from the peak >= dip_k (1.0) x the mean
    1-min range of the 15 bars before.
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, "stall": True,
            "fade": True, "seller_bs": 0.25, "div_n": 5, "div_drop": 0.10, "res_pct": 1.0, "res_required": True, "dip_k": 1.0}


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}"
    if c["fade"]:
        f, why = _fade(done, flow, entry_i, peak, c)
        if f:
            return True, why
    if not c["stall"]:
        return False, "stall part off"
    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"


def _fade(done, flow, entry_i, peak, c):
    """FADE INTO RESISTANCE -> (sell?, why)"""
    n = c["div_n"]; k = len(done) - 1
    if k - 1 - n < 0 or k < 16:
        return False, ""
    fb, fs = flow["buy"], flow["sell"]

    def bs(m, w):
        B = sum(fb[max(0, m - w + 1):m + 1]); S = sum(fs[max(0, m - w + 1):m + 1]); return B / (B + S) if B + S else 0.5
    b, p = done[k], done[k - 1]
    m = _minute(b["t"])
    if not (bs(m, 1) <= c["seller_bs"] and bs(m, 5) < 0.5 and b["c"] < p["c"]):
        return False, ""
    a, z = done[k - 1 - n], done[k - 1]
    d0, d1 = bs(_minute(a["t"]), 5), bs(_minute(z["t"]), 5)
    if not (z["c"] > a["c"] and d0 - d1 >= c["div_drop"]):
        return False, ""
    res = ""
    if c["res_required"]:
        lv = [("the day's open", done[0]["o"])]
        if entry_i > 0:
            lv.append(("the day's high before the buy", max(x["h"] for x in done[:entry_i])))
        near = [(nm, v) for nm, v in lv if v * (1 - c["res_pct"] / 100) <= peak <= v * 1.002]
        if not near:
            return False, ""
        res = f", peak {peak:.4g} at {near[0][0]} {near[0][1]:.4g}"
    rng = sum(x["h"] - x["l"] for x in done[k - 15:k]) / 15
    if peak - b["c"] < c["dip_k"] * rng:
        return False, ""
    return True, (f"X1 fade into resistance: close {a['c']:.4g} -> {z['c']:.4g} while 5-min buyers {d0:.0%} -> {d1:.0%}{res}; "
                  f"seller bar {bs(m, 1):.0%} buyers, 5-min {bs(m, 5):.0%}, dip {peak - b['c']:.4g} >= {c['dip_k']:g} x range {rng:.4g}")
