"""tr42_chart.py OUTDIR DAY:SYM:T:PL:HOLD.. -- [2026-10-30] chart a new-#42 trade (uptrend + rise confirmed + volume buy, trade-bot C3 exit):
candles 9:30 -> 30 min after the sell, EMA9 / EMA20 / VWAP, the stop (10-bar low x0.998, 0.5-4%), buy + sell markers, volume vs normal, 3m/15m share."""
import gzip, json, sys
from pathlib import Path
import matplotlib; matplotlib.use("Agg"); import matplotlib.pyplot as plt
TR = Path("/var/www/screener/trade"); sys.path.insert(0, str(TR / "reports/playbook")); sys.path.insert(0, str(TR))
import os
import v2_bar_replay as R
TTL = os.environ.get('TITLE', 'new #42 buy (uptrend + rise + volume)')
import stock_board as SB
out = Path(sys.argv[1]); out.mkdir(parents=True, exist_ok=True)
hm = lambda m: f"{(m + 30) // 60 + 9}:{(m + 30) % 60:02d}"
for ds in sys.argv[2:]:
    day, s, t, pl, hold = ds.split(":"); t, pl, hold = int(t), float(pl), int(hold)
    d = json.load(gzip.open(R.OW / f"bars/bars_{day}.json.gz", "rt")); ref = R.REF.load(day, s)
    bars = [x for x in R.bars_of(d["symbols"][s]["bars"]) if 0 <= R.minute(x["t"]) < 390]; M = [R.minute(x["t"]) for x in bars]
    fl = json.loads((R.OW / "flow" / day / f"{s}.json").read_text()); fb, fs = fl["buy"], fl["sell"]; vpm = ref["vol_per_min"]
    i = M.index(t); bi = i + 1; P = bars[bi]["o"]; sw = min(x["l"] for x in bars[max(0, bi - 10):bi]); stop = min(max(sw * 0.998, P * 0.96), P * 0.995) if not os.environ.get("STOPPCT") else P * (1 - float(os.environ["STOPPCT"]) / 100)
    tx = M[bi] + hold; px = P * (1 + (pl + 0.2) / 100)
    n = next((k for k in range(len(bars)) if M[k] > min(tx + 30, 389)), len(bars)); n = max(n, bi + 20); B = bars[:n]; MM = M[:n]
    e9 = e20 = bars[0]["c"]; E9, E20, VW = [], [], []; cv = pv = 0
    for x in B:
        e9 += (x["c"] - e9) * 0.2; e20 += (x["c"] - e20) * 2 / 21; E9.append(e9); E20.append(e20); cv += x["v"]; pv += (x["h"] + x["l"] + x["c"]) / 3 * x["v"]; VW.append(pv / cv)
    sh = lambda m, k: sum(fb[max(0, m - k + 1):m + 1]) / max(sum(fb[max(0, m - k + 1):m + 1]) + sum(fs[max(0, m - k + 1):m + 1]), 1)
    pp = R.OW / f"pm_history/{day}.json.gz"
    pmh = {r["s"]: r.get("pm_high") for r in json.load(gzip.open(pp, "rt"))["rows"]}.get(s) if pp.exists() else None
    BD = SB.Board(ref["prev_close"], ref["atr14"], bars[0]["o"], pm_high=pmh, vpm=vpm, rule="v2"); RES, SUP = [], []
    for x, m in zip(B, MM):
        row = BD.update(x, m, fb[m], fs[m]); RES.append(row["res"]); SUP.append(row["sup"])
    fig, ax = plt.subplots(3, 1, figsize=(13, 9), sharex=True, gridspec_kw=dict(height_ratios=[4, 1.2, 1.2]))
    for x, m in zip(B, MM):
        c = "#2a9d4b" if x["c"] >= x["o"] else "#d64545"
        ax[0].plot([m, m], [x["l"], x["h"]], color=c, lw=0.8); ax[0].add_patch(plt.Rectangle((m - 0.35, min(x["o"], x["c"])), 0.7, max(abs(x["c"] - x["o"]), 1e-4), color=c))
        ax[1].bar(m, x["v"], color=c, width=0.7)
    ax[1].plot(MM, [vpm[m] for m in MM], color="#555", lw=1, label="normal volume for the minute"); ax[1].legend(loc="upper right", fontsize=8)
    ax[0].plot(MM, E9, color="#1f6feb", lw=1.1, label="EMA9"); ax[0].plot(MM, E20, color="#e07b00", lw=1.1, label="EMA20"); ax[0].plot(MM, VW, color="#7b3fbf", lw=1.4, label="VWAP")
    ax[0].step(MM, RES, where="post", color="#c0392b", lw=1.6, alpha=0.75, label="board RESISTANCE (avg swing highs)")
    ax[0].step(MM, SUP, where="post", color="#16a085", lw=1.6, alpha=0.75, label="board SUPPORT (avg swing lows)")
    ax[0].annotate(f"R {RES[i]:.2f}", (M[bi], RES[i]), (6, 4), textcoords="offset points", fontsize=8, color="#c0392b", weight="bold")
    ax[0].annotate(f"S {SUP[i]:.2f}", (M[bi], SUP[i]), (6, -12), textcoords="offset points", fontsize=8, color="#16a085", weight="bold")
    ax[0].axhline(bars[0]["o"], color="#999", ls=":", lw=1); ax[0].text(MM[-1], bars[0]["o"], " open", va="center", fontsize=8, color="#666", clip_on=True)
    ax[0].axhline(ref["prev_close"], color="#e0a020", ls="-.", lw=1); ax[0].text(MM[-1], ref["prev_close"], " prev close", va="center", fontsize=8, color="#b07a00", clip_on=True)
    ax[0].hlines(stop, M[bi], tx, color="#d64545", ls="--", lw=1); ax[0].text(M[bi], stop, "stop ", ha="right", va="center", fontsize=8, color="#d64545")
    ax[0].scatter([M[bi]], [P], marker="^", s=150, color="#1f6feb", zorder=6); ax[0].annotate(f"BUY {hm(M[bi])} ${P:.2f}", (M[bi], P), (-10, 12), textcoords="offset points", ha="right", fontsize=9, color="#1f6feb", weight="bold")
    ax[0].scatter([tx], [px], marker="v", s=150, color="#d64545", zorder=6); ax[0].annotate(f"SELL {hm(tx)} ${px:.2f} ({pl:+.2f}%)", (tx, px), (8, -16), textcoords="offset points", fontsize=9, color="#d64545", weight="bold")
    lo = min(min(x["l"] for x in B), stop, px, min(SUP)); hi = max(max(x["h"] for x in B), px, max(RES))
    pos = (P - SUP[i]) / max(RES[i] - SUP[i], 1e-9)
    ax[0].set_ylim(lo - (hi - lo) * 0.04, hi + (hi - lo) * 0.06)
    ax[0].set_title(f"{s} {day} — {TTL} | trade-bot C3 exit | {pl:+.2f}% after cost, held {hold} min | gap {(bars[0]['o'] / ref['prev_close'] - 1) * 100:+.1f}%\nat the buy: resistance {RES[i]:.2f} ({(RES[i] / P - 1) * 100:+.2f}%), support {SUP[i]:.2f} ({(SUP[i] / P - 1) * 100:+.2f}%), position in range {pos:.2f}", fontsize=10)
    ax[0].legend(loc="upper left", fontsize=8); ax[1].set_ylabel("volume")
    ax[2].plot(MM, [sh(m, 3) for m in MM], color="#1f6feb", lw=1.1, label="buy share 3m"); ax[2].plot(MM, [sh(m, 15) for m in MM], color="#e07b00", lw=1.1, label="buy share 15m")
    ax[2].axhline(0.5, color="#999", lw=0.6); ax[2].axhline(0.55, color="#2a9d4b", lw=0.6, ls=":"); ax[2].set_ylim(0, 1); ax[2].legend(loc="upper left", fontsize=8)
    for a in ax: a.axvline(M[bi], color="#1f6feb", lw=0.7, ls=":"); a.axvline(tx, color="#d64545", lw=0.7, ls=":"); a.grid(alpha=0.25)
    tk = list(range(0, MM[-1] + 1, 10 if MM[-1] <= 120 else 20)); ax[2].set_xticks(tk); ax[2].set_xticklabels([hm(m) for m in tk])
    plt.tight_layout(); f = out / f"{os.environ.get('PFX', 'tr42')}_{s}_{day}.png"; plt.savefig(f, dpi=95); plt.close(); print(f)
    del d; R.REF._CACHE.clear()
