"""star_loser_chart.py DAY SYM BUY_HH:MM [..] -- [2026-10-27] the user: chart of a real Star-bot trade (premarket logs): entry / exit,
every entry reading from the bot's own [V2] BUY line + the 8 kept checks, 3-min vs 15-min buy share (Massive tick rule), and the QUEUE
(bid size vs ask size per minute from Alpaca SIP historical quotes -- the Star bot does not record a book). -> star_<SYM>_<DAY>_<HHMM>.png"""
import json, re, sys
from datetime import datetime, timedelta
from pathlib import Path
from zoneinfo import ZoneInfo
import numpy as np
import matplotlib; matplotlib.use("Agg")
import matplotlib.pyplot as plt
HERE = Path(__file__).resolve().parent; TR = Path("/var/www/screener/trade"); PM = Path("/var/www/screener/premarket")
for p in (str(TR), str(TR / "reports/open_window"), str(PM)):
    sys.path.insert(0, p) if p != str(PM) else sys.path.append(p)
from alpaca.data.requests import StockBarsRequest, StockQuotesRequest
from alpaca.data.timeframe import TimeFrame
from alpaca.data.historical import StockHistoricalDataClient
from config_loader import get_env
from massive_trial import m_trades, tick_flow
import volatility
ET = ZoneInfo("America/New_York"); env = get_env(); hc = StockHistoricalDataClient(env.api_key, env.secret_key)
hm = lambda m: f"{9 + (30 + m) // 60}:{(30 + m) % 60:02d}"
toM = lambda s: (int(s[:2]) - 9) * 60 + int(s[3:5]) - 30
def trade_from_log(day, sym, buy_hm):
    L = (PM / f"logs/star_bot_{day}.log").read_text(errors="ignore").splitlines()
    v2 = next(l for l in L if f"[V2] {sym} @" in l and ": BUY |" in l and l[11:16] == buy_hm)
    k = L.index(v2); ent = next(l for l in L[k:] if f"[ENTRY] {sym} BUY" in l and "filled" in l)
    ex = next(l for l in L[k:] if f"[EXIT] {sym} SELL" in l and "P/L" in l)
    star = next((l for l in L[k:] if f"[STAR] SELL {sym}" in l), "")
    num = lambda pat, s: float(re.search(pat, s).group(1))
    t = dict(buy_t=ent[11:16], buy=num(r"BUY \d+ @ \$([\d.]+)", ent), stop=num(r"stop \$([\d.]+)", ent),
             sell_t=ex[11:16], sell=num(r"SELL (?:\d+ )?@ ~?\$([\d.]+)", ex), pl=num(r"P/L ([+-][\d.]+)%", ex),
             why=(re.search(r"\((.*?)\) -- P/L", ex) or re.search(r"-- (.*?) -- P/L", ex)).group(1).replace("limit filled (", ""))
    rd = dict(re.findall(r"(RVOL|vol15x|buy|R2|eff|VWAP|spread) ([\d.\-]+)%?", v2.split("|")[1]))
    t["read"] = {k: float(v) for k, v in rd.items()}; t["room"] = re.search(r"room ([^,]+),", v2).group(1); t["v2line"] = v2.split("BUY | ")[1]
    return t
for spec in [sys.argv[i:i + 3] for i in range(1, len(sys.argv), 3)]:
    day, sym, bh = spec; t = trade_from_log(day, sym, bh); d0 = datetime.fromisoformat(day)
    raw = hc.get_stock_bars(StockBarsRequest(symbol_or_symbols=sym, timeframe=TimeFrame.Minute, start=d0.replace(hour=9, minute=30, tzinfo=ET),
                                             end=d0.replace(hour=16, tzinfo=ET))).data[sym]
    B = {}
    for x in raw:
        tt = x.timestamp.astimezone(ET); m = (tt.hour - 9) * 60 + tt.minute - 30
        if 0 <= m < 390: B[m] = x
    M = np.array(sorted(B)); o, h, l, c, v = (np.array([getattr(B[m], k) for m in M]) for k in ("open", "high", "low", "close", "volume"))
    vw = np.cumsum((h + l + c) / 3 * v) / np.cumsum(v)
    ref = json.loads((PM / f"data/reference/{day}/{sym}.json").read_text()); pc = ref["prev_close"]
    fb, fs = tick_flow(m_trades(sym, day))
    bm, sm = toM(t["buy_t"]), toM(t["sell_t"]); lo_m, hi_m = max(0, bm - 60), min(389, sm + 30)
    q = hc.get_stock_quotes(StockQuotesRequest(symbol_or_symbols=sym, start=d0.replace(tzinfo=ET) + timedelta(hours=9, minutes=30 + lo_m),
                                               end=d0.replace(tzinfo=ET) + timedelta(hours=9, minutes=31 + hi_m))).data.get(sym, [])
    qb, qa, qn = np.zeros(390), np.zeros(390), np.zeros(390)
    for z in q:
        tt = z.timestamp.astimezone(ET); m = (tt.hour - 9) * 60 + tt.minute - 30
        if 0 <= m < 390 and z.bid_size and z.ask_size: qb[m] += z.bid_size; qa[m] += z.ask_size; qn[m] += 1
    ok = qn > 0; imb = np.where(ok, (qb - qa) / np.maximum(qb + qa, 1), np.nan)
    def share(n):
        bb = np.convolve(fb, np.ones(n))[:390]; ss = np.convolve(fs, np.ones(n))[:390]; return np.where(bb + ss > 0, bb / np.maximum(bb + ss, 1) * 100, np.nan)
    s3, s15 = share(3), share(15)
    # the 8 kept checks at the signal (bar before the buy)
    k = int(np.searchsorted(M, bm)) - 1; r = t["read"]
    ext = (t["buy"] / o[0] - 1) * 100; spm = v[max(0, k - 14):k + 1].mean()
    sp = volatility.sr_position(ref["sr14"], t["buy"]) if ref.get("sr14") else {}
    res, sup = sp.get("resistance"), sp.get("support")
    chk = [("RVOL so far >= 1.5x", f"{r['RVOL']:.2f}x", r["RVOL"] >= 1.5), ("VWAP 0..+2%", f"{r['VWAP']:+.2f}%", 0 <= r["VWAP"] <= 2),
           ("straightness >= 0.5", f"{r['eff']:.2f}", r["eff"] >= 0.5), ("<= 3% over the open", f"{ext:+.1f}%", ext <= 3),
           ("room >= 1% to resistance", t["room"], True), ("liquidity >= 2,000 sh/min", f"{spm:,.0f}", spm >= 2000),
           ("buy share 15m >= 55%", f"{r['buy'] * 100:.0f}%", r["buy"] >= 0.55), ("timing >= 9:45", t["buy_t"], bm >= 15)]
    info = [("now OFF: vol spike 15m <= 5x", f"{r['vol15x']:.2f}x"), ("now OFF: smoothness >= 0.7", f"{r['R2']:.2f}"), ("spread", f"{r['spread']:.2f}%"),
            ("3m/15m buy share (tick)", f"{s3[bm - 1]:.0f}% / {s15[bm - 1]:.0f}%"),
            ("queue 5 min before buy", f"{np.nanmean(imb[bm - 5:bm]):+.2f}" if ok[bm - 5:bm].any() else "n/a"),
            ("daily ATR", f"{ref['atr14'] / pc * 100:.1f}%")]
    fig = plt.figure(figsize=(18, 13)); gs = fig.add_gridspec(4, 2, width_ratios=[3.3, 1], height_ratios=[3.6, 1.2, 1.3, 1.5], hspace=0.08, wspace=0.16)
    ax = [fig.add_subplot(gs[0, 0])]; ax += [fig.add_subplot(gs[i, 0], sharex=ax[0]) for i in (1, 2, 3)]
    W = (M >= lo_m) & (M <= hi_m); Mw = M[W]; a = ax[0]; up = (c >= o)[W]; col = np.where(up, "#1a9850", "#d73027")
    a.vlines(Mw, l[W], h[W], color=col, lw=0.9); a.bar(Mw, np.maximum(abs(c - o)[W], (h[W].max() - l[W].min()) * 0.003), bottom=np.minimum(o, c)[W], color=col, width=0.8)
    a.plot(Mw, vw[W], color="#7b3294", lw=1.4, label="VWAP"); a.axhline(pc, color="gray", ls="--", lw=1, label=f"prev close {pc:.2f}")
    if res: a.axhspan(res["lo"], res["hi"], color="#d73027", alpha=0.10, label=f"14-day resistance {res['lo']:.2f}-{res['hi']:.2f}")
    if sup: a.axhspan(sup["lo"], sup["hi"], color="#1a9850", alpha=0.10, label=f"14-day support {sup['lo']:.2f}-{sup['hi']:.2f}")
    a.hlines(t["stop"], bm, sm, color="#d73027", ls=":", lw=1.3, label=f"safety stop {t['stop']:.2f}")
    a.scatter([bm], [t["buy"]], marker="^", s=190, color="#1a9850", edgecolor="k", zorder=6); a.scatter([sm + 0.4], [t["sell"]], marker="v", s=190, color="#d73027", edgecolor="k", zorder=6)
    a.annotate(f"BUY {t['buy_t']} {t['buy']:.2f}", (bm, t["buy"]), xytext=(-125, 28), textcoords="offset points", color="#1a9850", fontweight="bold", bbox=dict(boxstyle="round", fc="white", ec="#1a9850"))
    a.annotate(f"SELL {t['sell_t']} {t['sell']:.2f} ({t['pl']:+.2f}%)", (sm, t["sell"]), xytext=(20, -34), textcoords="offset points", color="#d73027", fontweight="bold", bbox=dict(boxstyle="round", fc="white", ec="#d73027"))
    a.set_title(f"STAR BOT {sym} {day} | open {o[0]:.2f}, gap {(o[0] / pc - 1) * 100:+.1f}% | sell: {t['why'][:80]}", fontsize=11, loc="left")
    a.legend(loc="upper left", fontsize=8); a.grid(alpha=0.25); plt.setp(a.get_xticklabels(), visible=False)
    ax[1].bar(range(390), fb, color="#1a9850", width=0.9, label="buyers (tick rule)"); ax[1].bar(range(390), -fs, color="#d73027", width=0.9, label="sellers")
    ax[1].set_ylim(-max(fs[lo_m:hi_m + 1].max(), 1) * 1.1, max(fb[lo_m:hi_m + 1].max(), 1) * 1.1); ax[1].legend(loc="upper left", fontsize=8); ax[1].grid(alpha=0.25)
    ax[2].plot(range(390), s3, color="#2166ac", lw=1.1, label="buy share 3 min"); ax[2].plot(range(390), s15, color="k", lw=1.6, label="buy share 15 min")
    ax[2].axhline(55, color="#1a9850", ls=":", lw=0.9); ax[2].axhline(50, color="gray", lw=0.7); ax[2].set_ylim(0, 100); ax[2].set_ylabel("%"); ax[2].legend(loc="upper left", fontsize=8); ax[2].grid(alpha=0.25)
    xs = np.arange(390)[ok]; ax[3].bar(xs, imb[ok], color=np.where(imb[ok] >= 0, "#91cf60", "#fc8d59"), width=0.9, label="queue: (bid size - ask size) / sum, per minute (Alpaca SIP quotes)")
    ax[3].plot(xs, np.convolve(np.nan_to_num(imb[ok]), np.ones(5) / 5, mode="same"), color="k", lw=1.2, label="5-min average")
    t3 = ax[3].twinx(); t3.plot(xs, (qb / np.maximum(qn, 1))[ok], color="#1a9850", lw=0.8, alpha=0.7); t3.plot(xs, (qa / np.maximum(qn, 1))[ok], color="#d73027", lw=0.8, alpha=0.7)
    t3.set_ylabel("avg bid (green) / ask (red) size", fontsize=8)
    ax[3].axhline(0, color="gray", lw=0.8); ax[3].set_ylim(-1, 1); ax[3].legend(loc="upper left", fontsize=8); ax[3].grid(alpha=0.25)
    for axx in ax[1:]: axx.axvspan(bm - 0.5, sm + 0.5, color="#fee08b", alpha=0.45)
    for axx in ax: axx.axvline(bm, color="#1a9850", lw=1, alpha=0.6); axx.axvline(sm, color="#d73027", lw=1, alpha=0.6)
    ax[3].set_xlim(lo_m - 1, hi_m + 1); tk = [x for x in range(0, 391, 10 if hi_m - lo_m > 100 else 5) if lo_m <= x <= hi_m]
    ax[3].set_xticks(tk[::max(1, len(tk) // 14)]); ax[3].set_xticklabels([hm(x) for x in tk[::max(1, len(tk) // 14)]])
    for axx in ax[1:3]: plt.setp(axx.get_xticklabels(), visible=False)
    tx = fig.add_subplot(gs[:, 1]); tx.axis("off"); y = 0.98
    tx.text(0, y, "ENTRY CHECKS AT THE BUY\n(the 8 kept, from the bot's log)", fontsize=11, fontweight="bold", va="top"); y -= 0.07
    for name, val, passed in chk:
        tx.text(0, y, ("PASS  " if passed else "FAIL  ") + name, fontsize=10, color="#1a9850" if passed else "#d73027", va="top"); tx.text(1, y, val, fontsize=10, ha="right", va="top"); y -= 0.04
    y -= 0.03; tx.text(0, y, "OTHER READINGS", fontsize=11, fontweight="bold", va="top"); y -= 0.05
    for name, val in info:
        tx.text(0, y, name, fontsize=9.5, va="top"); tx.text(1, y, val, fontsize=9.5, ha="right", va="top"); y -= 0.04
    y -= 0.03; tx.text(0, y, "TRADE", fontsize=11, fontweight="bold", va="top"); y -= 0.05
    for line in (f"buy {t['buy_t']} @ {t['buy']:.2f}", f"stop {t['stop']:.2f} ({(t['stop'] / t['buy'] - 1) * 100:+.1f}%)", f"sell {t['sell_t']} @ {t['sell']:.2f}",
                 f"P/L {t['pl']:+.2f}%", f"held {sm - bm} min"):
        tx.text(0, y, line, fontsize=10, va="top"); y -= 0.035
    tx.text(0, y - 0.02, "sell reason:\n" + "\n".join(t["why"][i:i + 38] for i in range(0, len(t["why"]), 38)), fontsize=9, va="top", color="#542788")
    out = HERE / f"star_{sym}_{day}_{t['buy_t'].replace(':', '')}.png"; plt.savefig(out, dpi=100, bbox_inches="tight"); plt.close()
    print(out, f"| quotes {len(q)} | {t['buy_t']} {t['buy']} -> {t['sell_t']} {t['sell']} {t['pl']:+.2f}%")
