"""day_chart.py DAY SYM [SYM..] -- [2026-10-26] the user: whole-day chart per stock: price + VWAP + prev close / prev low, listed time,
EV3 log signals; volume split buyers/sellers (Massive tick rule); 5/15-min buy share; book queue (bid size vs ask size imbalance,
data/book recorder) -> day_<SYM>_<DAY>.png"""
import json, os, re, sys
from datetime import datetime
from zoneinfo import ZoneInfo
from pathlib import Path
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")
for p in (str(TR), str(TR / "reports/open_window")):
    sys.path.insert(0, p)
from alpaca.data.requests import StockBarsRequest
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
ET = ZoneInfo("America/New_York"); day = sys.argv[1]
hm = lambda m: f"{9 + (30 + m) // 60}:{(30 + m) % 60:02d}"
env = get_env(); hc = StockHistoricalDataClient(env.api_key, env.secret_key)
log = (TR / f"logs/trade_bot_{day}.log").read_text(errors="ignore").splitlines()
for arg in sys.argv[2:]:
    sym, *marks = arg.split('@')  # SYM@10:15 -> marks the queue-pattern signal minute (buy = next minute)
    toM = lambda x: (int(x.split(':')[0]) - 9) * 60 + int(x.split(':')[1]) - 30
    exits = [toM(x.split('x')[1]) for x in marks if 'x' in x]  # SYM@9:44x10:17 -> signal 9:44, sold 10:17
    label = sys.argv[1] if False else None
    marks = [toM(x.split('x')[0]) for x in marks]
    raw = hc.get_stock_bars(StockBarsRequest(symbol_or_symbols=sym, timeframe=TimeFrame.Minute,
                                             start=datetime.fromisoformat(day).replace(hour=9, minute=30, tzinfo=ET),
                                             end=datetime.fromisoformat(day).replace(hour=16, tzinfo=ET))).data[sym]
    B = {}
    for x in raw:
        t = x.timestamp.astimezone(ET); m = (t.hour - 9) * 60 + t.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((TR / f"data/reference/{day}/{sym}.json").read_text())
    fb, fs = tick_flow(m_trades(sym, day)); fb, fs = fb[M], fs[M]
    def share(n):
        b = np.convolve(fb, np.ones(n))[:len(fb)]; s = np.convolve(fs, np.ones(n))[:len(fs)]
        return np.where(b + s > 0, b / np.maximum(b + s, 1), np.nan)
    bk = {}
    for line in open(TR / f"data/book/{day}.jsonl"):
        if f'"{sym}"' in line:
            r = json.loads(line); hh, mm = map(int, r["minute"].split(":")); bk[(hh - 9) * 60 + mm - 30] = r
    bm = np.array(sorted(k for k in bk if 0 <= k < 390))
    imb = np.array([bk[k]["imbalance"] for k in bm]); bsz = np.array([bk[k]["bid_size"] for k in bm]); asz = np.array([bk[k]["ask_size"] for k in bm])
    listed = None; ev = []
    for s in log:
        if listed is None and ("[SCAN]" in s or "[RESCAN]" in s) and f"'{sym}'" in s.split("/ -")[0]:
            listed = int(s[11:13]) * 60 + int(s[14:16]) - 570
        if "[EV3]" in s and f" {sym}:" in s:
            mm = re.search(r"at the (\d+):(\d+) bar", s); ev.append(((int(mm[1]) - 9) * 60 + int(mm[2]) - 30 if mm else int(s[11:13]) * 60 + int(s[14:16]) - 570, s.split("[EV3] ")[1][:90]))
    fig, ax = plt.subplots(4, 1, figsize=(16, 13), sharex=True, gridspec_kw={"height_ratios": [4, 1.4, 1.2, 1.6]})
    a = ax[0]; up = c >= o
    a.vlines(M, l, h, color=np.where(up, "#1a9850", "#d73027"), lw=0.8)
    a.bar(M, np.maximum(np.abs(c - o), (h.max() - l.min()) * 0.002), bottom=np.minimum(o, c), color=np.where(up, "#1a9850", "#d73027"), width=0.8)
    a.plot(M, vw, color="#7b3294", lw=1.3, label="VWAP")
    a.axhline(ref["prev_close"], color="gray", ls="--", lw=1, label=f"prev close {ref['prev_close']:.2f}")
    if ref.get("prev_low"): a.axhline(ref["prev_low"], color="#fdae61", ls=":", lw=1.2, label=f"prev low {ref['prev_low']:.2f}")
    CLEAN = os.environ.get("TRADES")  # [2026-10-27] clean mode: TRADES='buyHH:MM,price,sellHH:MM,price;...' -> only entry/exit markers
    if CLEAN: marks, exits, ev, listed = [], [], [], None
    if listed is not None: a.axvline(listed, color="#2166ac", ls="--", lw=1); a.text(listed + 1, h.max(), f"listed {hm(listed)}", color="#2166ac", va="top")
    for m, txt in ev:
        a.annotate(txt[:60], (m, l[np.searchsorted(M, m)] if m in B else c[-1]), xytext=(m + 5, l.min()), color="#b2182b", fontsize=8,
                   arrowprops=dict(arrowstyle="->", color="#b2182b"))
    for n_mk, mk in enumerate(marks):
        for axx in ax: axx.axvline(mk + 1, color="#e08214", lw=1.5, alpha=0.8)
        P = B[mk + 1].open if mk + 1 in B else c[-1]
        a.annotate(f"{os.environ.get('SIGLABEL', 'queue pattern')} fired {hm(mk)} -> buy {hm(mk + 1)} @ {P:.2f}", (mk + 1, P), xytext=(mk + 8, h.max() - n_mk * (h.max() - l.min()) * 0.07), color="#b35806",
                   fontsize=9, fontweight="bold", arrowprops=dict(arrowstyle="->", color="#b35806"))
    for n_ex, ex in enumerate(exits):
        for axx in ax: axx.axvline(ex, color="#542788", lw=1.5, ls="--", alpha=0.8)
        Px = B[ex].open if ex in B else c[-1]
        a.annotate(f"SELL {hm(ex)} ~{Px:.2f}", (ex, Px), xytext=(ex + 8, l.min() + (h.max() - l.min()) * (0.15 - n_ex * 0.07)), color="#542788",
                   fontsize=9, fontweight="bold", arrowprops=dict(arrowstyle="->", color="#542788"))
    for k_tr, tr in enumerate((CLEAN or "").split(";") if CLEAN else []):
        bt, bp, st, sp = tr.split(","); bm_, sm_ = toM(bt), toM(st); bp, sp = float(bp), float(sp); pl_ = (sp / bp - 1) * 100
        a.scatter([bm_], [bp], marker="^", s=160, color="#1a9850", edgecolor="k", zorder=5)
        a.scatter([sm_ + 0.4], [sp], marker="v", s=160, color="#d73027", edgecolor="k", zorder=5)
        a.annotate(f"BUY {bt}  {bp:.2f}", (bm_, bp), xytext=(-110, 18), textcoords="offset points", color="#1a9850", fontsize=10, fontweight="bold", bbox=dict(boxstyle="round", fc="white", ec="#1a9850", alpha=0.9))
        a.annotate(f"SELL {st}  {sp:.2f}  ({pl_:+.1f}%)", (sm_, sp), xytext=(30, -30), textcoords="offset points", color="#d73027", fontsize=10, fontweight="bold", bbox=dict(boxstyle="round", fc="white", ec="#d73027", alpha=0.9))
        for axx in ax[1:]: axx.axvspan(bm_ - 0.5, sm_ + 0.5, color="#fee08b", alpha=0.6)
    ih, il = int(np.argmax(h)), int(np.argmin(l))
    a.set_title(f"{sym} {day} | open {o[0]:.2f}  gap {(o[0] / ref['prev_close'] - 1) * 100:+.1f}%  low {l[il]:.2f} @{hm(M[il])}  high {h[ih]:.2f} @{hm(M[ih])}  "
                f"close {c[-1]:.2f} ({(c[-1] / o[0] - 1) * 100:+.1f}% from open)  daily ATR {ref['atr14'] / ref['prev_close'] * 100:.1f}%", fontsize=11)
    a.legend(loc="upper left", fontsize=8); a.grid(alpha=0.25)
    ax[1].bar(M, fb, color="#1a9850", width=0.9, label="buyers (tick rule)"); ax[1].bar(M, -fs, color="#d73027", width=0.9, label="sellers")
    ax[1].legend(loc="upper left", fontsize=8); ax[1].set_ylabel("shares"); ax[1].grid(alpha=0.25)
    n_s = 3 if os.environ.get("SHARE3") else 5; ax[2].plot(M, share(n_s) * 100, color="#2166ac", lw=1, label=f"buy share {n_s} min"); ax[2].plot(M, share(15) * 100, color="#000", lw=1.3, label="buy share 15 min")
    ax[2].axhline(50, color="gray", lw=0.8); ax[2].axhline(45, color="#d73027", ls=":", lw=0.8); ax[2].set_ylim(0, 100); ax[2].set_ylabel("%")
    ax[2].legend(loc="upper left", fontsize=8); ax[2].grid(alpha=0.25)
    if len(bm):
        sm = np.convolve(imb, np.ones(5) / 5, mode="same")
        ax[3].bar(bm, imb, color=np.where(imb >= 0, "#91cf60", "#fc8d59"), width=0.9, label="queue imbalance (bid size - ask size)/(sum), per minute")
        ax[3].plot(bm, sm, color="#000", lw=1.2, label="5-min average")
        t3 = ax[3].twinx(); t3.plot(bm, bsz, color="#1a9850", lw=0.6, alpha=0.6); t3.plot(bm, asz, color="#d73027", lw=0.6, alpha=0.6); t3.set_ylabel("avg bid / ask size (shares)", fontsize=8)
    else:
        ax[3].text(0.5, 0.5, "no book data (not on the list)", transform=ax[3].transAxes, ha="center")
    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)
    ax[3].set_xticks(range(0, 391, 30)); ax[3].set_xticklabels([hm(x) for x in range(0, 391, 30)])
    plt.tight_layout(); out = HERE / f"day_{sym}_{day}{os.environ.get('SUFFIX', '')}{'_clean' if CLEAN else '_signal' if marks else ''}.png"; plt.savefig(out, dpi=110); plt.close()
    print(out, "book minutes", len(bm), "listed", hm(listed) if listed is not None else None, "events", len(ev))
