"""up3_afterdrop.py DAY:SYM [..] -- [2026-10-27] the user: the bot starts counting 3 rising 1-min closes only AFTER the price stops falling
(bar before the run closed down); [fix 10/27, user] each of the 3 bars must be GREEN (close > open) AND close above the previous close. Checks as before: >= yesterday's close, volume (3 bars avg >= 90% of the 5 before), buy share 3 min >= 55%,
queue 3-min avg > 0. Every pattern all day is listed with pass/fail; trades (when all pass and not holding) go through the C3 exit.
PULLBACK variant: the low before the run is >= 0.5% under the highest close of the 15 min before."""
import json, sys
import numpy as np
from up3_test import load, sim, hm
S = {(d, s): (D, bk) for d, s, D, bk in load()}
def scan(D, bk, pull=0.0):
    b, M, pc = D.b, D.m, D.ref["prev_close"]; fb, fs = D.fl["buy"], D.fl["sell"]; ev = []; free = 0
    for i in range(9, len(b) - 1):
        t = M[i]
        if t > 375 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]); low = b[i - 3]["c"]; pb = (1 - low / hi) * 100
        if pb < pull: continue
        bb = sum(fb[t - 2:t + 1]); ss = sum(fs[t - 2:t + 1]); q = [bk[k]["imbalance"] for k in (t - 2, t - 1, t) if k in bk]
        chk = {"above prev close": b[i]["c"] >= pc,
               "volume": np.mean([x["v"] for x in b[i - 2:i + 1]]) >= 0.9 * np.mean([x["v"] for x in b[i - 7:i - 2]]),
               "buyers>=55%": bb + ss > 0 and bb / (bb + ss) >= 0.55, "queue>0": bool(q) and np.mean(q) > 0}
        e = dict(t=t, price=b[i]["c"], pullback=pb, bs=bb / (bb + ss) if bb + ss else np.nan, q=np.mean(q) if q else np.nan,
                 fail=[k for k, v in chk.items() if not v], trade=None)
        if not e["fail"] and i >= free:
            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"); e["trade"] = (hm(M[bi]), P, hm(M[j]), why, pl); free = j + 1
        elif not e["fail"]: e["fail"] = ["(already holding)"]
        ev.append(e)
    return ev
for arg in sys.argv[1:]:
    day, sym = arg.split(":"); D, bk = S[(day, sym)]
    for pull in (0.5,):
        ev = scan(D, bk, pull)
        print(f"\n== {sym} {day} | prev close {D.ref['prev_close']:.2f} | {'any drop' if not pull else 'pullback >= 0.5%'} : {len(ev)} patterns ==")
        for e in ev:
            tr = f"  ==> BUY {e['trade'][0]} @ {e['trade'][1]:.2f}, sold {e['trade'][2]} ({e['trade'][3]}) {e['trade'][4]:+.2f}% after cost" if e["trade"] else ""
            print(f"   {hm(e['t'])} close {e['price']:.2f} pullback {e['pullback']:.1f}% buy share {e['bs']:.0%} queue {e['q']:+.2f} | "
                  f"{'ALL PASS' if not e['fail'] else 'fail: ' + ', '.join(e['fail'])}{tr}")
        tot = [e["trade"][4] for e in ev if e["trade"]]
        print(f"   trades {len(tot)}, total {sum(tot):+.2f}%")
