"""up3g_chart.py DAY SYM [..] -- [2026-10-27] chart of the green-bar rule trades on a 2-year LIBRARY day (bars + quote flow + ref from the
library): price + VWAP + prev close, the dip bar and the 3 green bars highlighted, BUY / SELL markers; buyers vs sellers; buy share 3/15 min;
volume. -> up3g_<SYM>_<DAY>.png"""
import gzip, json, sys
from pathlib import Path
import numpy as np
import matplotlib; matplotlib.use("Agg")
import matplotlib.pyplot as plt
HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE)); sys.path.insert(0, "/var/www/screener/trade/reports/playbook"); sys.path.insert(0, "/var/www/screener/trade")
import v2_bar_replay as R
from queue_test import Day
from sim_2y import sim
hm = lambda m: f"{9 + (30 + m) // 60}:{(30 + m) % 60:02d}"
day = sys.argv[1]; d = json.load(gzip.open(R.OW / "bars" / f"bars_{day}.json.gz", "rt"))
for sym in sys.argv[2:]:
    ref = R.REF.load(day, sym); fl = json.loads((R.OW / "flow" / day / f"{sym}.json").read_text())
    bars = [x for x in R.bars_of(d["symbols"][sym]["bars"]) if 0 <= R.minute(x["t"]) < 390]
    D = Day(bars, [R.minute(x["t"]) for x in bars], fl, ref); b, M, pc = D.b, D.m, ref["prev_close"]; fb, fs = np.array(fl["buy"]), np.array(fl["sell"])
    trades = []; free = 0; info = []
    for i in range(9, len(b) - 1):
        t = M[i]
        if t > 375 or i < free or M[i] - M[i - 4] != 4: continue
        if not (b[i - 3]["c"] < b[i - 4]["c"] and all(b[k]["c"] > b[k - 1]["c"] and b[k]["c"] > b[k]["o"] for k in (i - 2, i - 1, i))): continue
        hi = max(x["c"] for x in b[max(0, i - 18):i - 2]); pb = (1 - b[i - 3]["c"] / hi) * 100
        if pb < 0.5: continue
        bb = fb[t - 2:t + 1].sum(); ss = fs[t - 2:t + 1].sum()
        v3 = np.mean([x["v"] for x in b[i - 2:i + 1]]); v5 = np.mean([x["v"] for x in b[i - 7:i - 2]])
        if not (b[i]["c"] >= pc and v3 >= 0.9 * v5 and bb + ss > 0 and bb / (bb + ss) >= 0.55): continue
        bi = i + 1; P = b[bi]["o"]; stop = min(max(min(x["l"] for x in b[i - 3:i + 1]) * 0.998, P * 0.96), P * 0.995)
        pl, j, why = sim(D, bi, P, stop, 2.0, "C3"); sp = P * (1 + (pl + 0.2) / 100)
        trades.append((i, bi, P, j, sp, why, pl, stop)); free = j + 1
        info.append(f"signal {hm(t)}: dip {pb:.1f}% | buy share 3m {bb / (bb + ss):.0%} | vol 3 bars {v3 / v5:.1f}x the 5 before | "
                    f"vs VWAP {(b[i]['c'] / D.vw[i] - 1) * 100:+.1f}% | BUY {hm(M[bi])} {P:.2f}, stop {stop:.2f}, SELL {hm(M[j])} {sp:.2f} ({why}) {pl:+.2f}% after cost")
    o = np.array([x["o"] for x in b]); h = np.array([x["h"] for x in b]); l = np.array([x["l"] for x in b]); c = np.array([x["c"] for x in b]); v = np.array([x["v"] for x in b]); Ma = np.array(M)
    fig, ax = plt.subplots(4, 1, figsize=(16, 12), sharex=True, gridspec_kw={"height_ratios": [4, 1.3, 1.2, 1.1]}); a = ax[0]; up = c >= o
    col = np.where(up, "#1a9850", "#d73027"); a.vlines(Ma, l, h, color=col, lw=0.8); a.bar(Ma, np.maximum(abs(c - o), (h.max() - l.min()) * 0.002), bottom=np.minimum(o, c), color=col, width=0.8)
    a.plot(Ma, D.vw, color="#7b3294", lw=1.3, label="VWAP"); a.axhline(pc, color="gray", ls="--", lw=1, label=f"prev close {pc:.2f}")
    for (i, bi, P, j, sp, why, pl, stop) in trades:
        a.axvspan(M[i - 3] - 0.5, M[i - 3] + 0.5, color="#fdae61", alpha=0.5); a.axvspan(M[i - 2] - 0.5, M[i] + 0.5, color="#a6d96a", alpha=0.45)
        a.scatter([M[bi]], [P], marker="^", s=170, color="#1a9850", edgecolor="k", zorder=5); a.scatter([M[j] + 0.4], [sp], marker="v", s=170, color="#d73027", edgecolor="k", zorder=5)
        a.hlines(stop, M[bi], M[j], color="#d73027", ls=":", lw=1.2)
        a.annotate(f"BUY {hm(M[bi])} {P:.2f}", (M[bi], P), xytext=(-120, 25), textcoords="offset points", color="#1a9850", fontsize=10, fontweight="bold", bbox=dict(boxstyle="round", fc="white", ec="#1a9850"))
        a.annotate(f"SELL {hm(M[j])} {sp:.2f} ({pl:+.1f}%)", (M[j], sp), xytext=(25, -30), textcoords="offset points", color="#d73027", fontsize=10, fontweight="bold", bbox=dict(boxstyle="round", fc="white", ec="#d73027"))
        for axx in ax[1:]: axx.axvspan(M[bi] - 0.5, M[j] + 0.5, color="#fee08b", alpha=0.6)
    a.set_title(f"{sym} {day} | open {o[0]:.2f} gap {(o[0] / pc - 1) * 100:+.1f}% | close {c[-1]:.2f} ({(c[-1] / o[0] - 1) * 100:+.1f}% from open) | daily ATR {ref['atr14'] / pc * 100:.1f}%"
                f"\norange = dip bar, green band = the 3 green bars, dotted red = stop", fontsize=11)
    a.legend(loc="upper left", fontsize=8); a.grid(alpha=0.25)
    ax[1].bar(range(390), fb, color="#1a9850", width=0.9, label="buyers (quote flow)"); ax[1].bar(range(390), -fs, color="#d73027", width=0.9, label="sellers"); ax[1].legend(loc="upper left", fontsize=8); ax[1].grid(alpha=0.25)
    sh = lambda n: np.where(np.convolve(fb + fs, np.ones(n))[:390] > 0, np.convolve(fb, np.ones(n))[:390] / np.maximum(np.convolve(fb + fs, np.ones(n))[:390], 1), np.nan) * 100
    ax[2].plot(range(390), sh(3), color="#2166ac", lw=0.9, label="buy share 3 min"); ax[2].plot(range(390), sh(15), color="k", lw=1.3, 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].legend(loc="upper left", fontsize=8); ax[2].grid(alpha=0.25)
    ax[3].bar(Ma, v, color=col, width=0.9); ax[3].set_ylabel("volume"); 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"up3g_{sym}_{day}.png"; plt.savefig(out, dpi=110); plt.close()
    print(out); print("\n".join("   " + s for s in info))
