"""
exit_climax.py -- [2026-10-23] The user's CLIMAX SELL (from PRTA 12/19/2024, sample chart #11: R1B buy 9:55 at 12.74, ran to
17.66 at 11:17 = +38%; the user's sell = 11:15). At 11:15 the price was +12.8% over VWAP (~1.5x the daily ATR above it), the
volume had been 2.8-3.8x normal for 7 bars, and 11:15 was the run's first big SELLER bar (86,525 shares, 41% buyers; the 5-min
buy share 77% -> 53%); the 1-min range had tripled (0.10 -> 0.26). Then 11:16-11:17 blow-off wicks to 17.66 and back to 16.49.
Meant to sit ON TOP of another exit (GB2 / X1) to keep a runner's profit at the climax. Sell at a FINISHED bar's close when ALL:
  PROFIT     the close >= min_gain (3%) over the buy
  STRETCHED  the close >= vwap_pct (8%) over the session VWAP, OR >= atr_k (1.0) x the daily ATR over it (when ref is given)
  HEAVY      a SUSTAINED climax: >= heavy_min (5) of the last heavy_n (6) bars each with >= heavy_x (2.0) x the MEDIAN minute volume
             of the day before them (a long climax would lift a 15-bar baseline) (PRTA 10:39 had only 3 heavy bars after quiet ones and was a pause, not the top)
  WIDER      the mean 1-min range of the last 15 bars >= range_x (1.5) x the same 30 bars earlier (the bars blow out:
             PRTA 11:15 0.26 vs 0.15)
  SELLERS    the current bar: 1-min buy share < seller_bs (45%) on volume >= seller_vol_x (2.0) x that same median
Decided at a bar close only, sold at the next price. Untested on 2 years. Pure function, no orders.
"""
DEFAULTS = {"min_gain": 3.0, "vwap_pct": 8.0, "atr_k": 1.0, "heavy_n": 6, "heavy_min": 5, "heavy_x": 2.0, "range_x": 1.5,
            "seller_bs": 0.45, "seller_vol_x": 2.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, ref=None, c=None):
    """done: the day's finished regular-session bars; flow: {"buy": [390], "sell": [390]} -> (sell?, why)"""
    c = {**DEFAULTS, **(c or {})}
    n = c["heavy_n"]
    if len(done) < max(n + 15, 46):
        return False, ""
    b = done[-1]
    if b["c"] < entry * (1 + c["min_gain"] / 100):
        return False, ""
    pv = sum((x["h"] + x["l"] + x["c"]) / 3 * x["v"] for x in done); cv = sum(x["v"] for x in done)
    vw = pv / cv if cv else b["c"]
    over = (b["c"] / vw - 1) * 100
    atr = (ref or {}).get("atr14")
    stretched = over >= c["vwap_pct"] or (atr and b["c"] - vw >= c["atr_k"] * atr)
    if not stretched:
        return False, ""
    pre = sorted(x["v"] for x in done[:-n])
    base = pre[len(pre) // 2] if pre else 0
    nh = sum(1 for x in done[-n:] if base and x["v"] >= c["heavy_x"] * base)
    if not base or nh < c["heavy_min"]:
        return False, ""
    rng = lambda w: sum(x["h"] - x["l"] for x in w) / len(w)
    r_now, r_then = rng(done[-15:]), rng(done[-45:-30])
    if not r_then or r_now < c["range_x"] * r_then:
        return False, ""
    m = _minute(b["t"]); B, S = flow["buy"][m], flow["sell"][m]
    bs1 = B / (B + S) if B + S else 0.5
    if not (bs1 < c["seller_bs"] and b["v"] >= c["seller_vol_x"] * base):
        return False, ""
    return True, (f"CLIMAX sell: close {b['c']:.4g} +{(b['c'] / entry - 1) * 100:.1f}% over the buy, {over:.1f}% over VWAP {vw:.4g}"
                  + (f" ({(b['c'] - vw) / atr:.1f}x ATR)" if atr else "")
                  + f"; {nh} of the last {n} bars >= {c['heavy_x']:g}x normal volume; 1-min range {r_now:.3g} vs {r_then:.3g} 30 bars before"
                  + f"; seller bar {bs1:.0%} buyers on {b['v'] / base:.1f}x volume")
