"""up3x.py fmc|11d|2y -- [2026-10-27] the user's simple rule v3: dip >= 0.5% then 3 GREEN 1-min bars each closing higher + volume
(3 bars >= 0.9x the 5 before), NO 'above yesterday's close', + CROSS (3-min buy share crossed above the 15-min in the last 3 minutes and
is still above) + BOTH INCREASING (UP1: 3m and 15m share both higher than 1 minute ago; UP3: than 3 minutes ago). Variants with / without
buy share >= 55%; old rule for comparison. Buy next open, stop under the dip bar + 3 bars x0.998 (0.5-4%), C3 exit, re-entry after exit."""
import gzip, json, sys
from pathlib import Path
import numpy as np
HERE = Path(__file__).resolve().parent; TR = Path("/var/www/screener/trade")
for p in (str(HERE), str(TR / "reports/playbook"), str(TR)): sys.path.insert(0, p)
from queue_test import Day
from sim_2y import sim
def share(fb, fs, t, n):
    t = max(t, 0); B = sum(fb[max(0, t - n + 1):t + 1]); S_ = sum(fs[max(0, t - n + 1):t + 1]); return B / (B + S_) if B + S_ else 0.5
def cross3(fb, fs, t):
    for k in range(t, t - 3, -1):
        if share(fb, fs, k, 3) <= share(fb, fs, k, 15): return False
        if share(fb, fs, k - 1, 3) <= share(fb, fs, k - 1, 15): return True
    return False
V = {"OLD rule (prev close + volume + buyers)": ["PC", "VOL", "BUY"], "no prev close: volume + buyers": ["VOL", "BUY"],
     "NEW: volume + cross + both up (1 min)": ["VOL", "X", "UP1"], "NEW + buyers >= 55%": ["VOL", "BUY", "X", "UP1"],
     "NEW, both up over 3 min": ["VOL", "X", "UP3"], "NEW, both up over 3 min + buyers": ["VOL", "BUY", "X", "UP3"]}
if "above" in sys.argv:   # [2026-10-27, user] no cross needed: 3-min ABOVE the 15-min + both increasing
    V = {"ABOVE: volume + 3m above 15m + both up (1 min)": ["VOL", "ABOVE", "UP1"], "ABOVE + buyers >= 55%": ["VOL", "BUY", "ABOVE", "UP1"],
         "ABOVE, both up over 3 min": ["VOL", "ABOVE", "UP3"], "ABOVE, both up over 3 min + buyers": ["VOL", "BUY", "ABOVE", "UP3"]}
def scan(D, need, bk=None, tmax=375):
    b, M, pc = D.b, D.m, D.ref["prev_close"]; fb, fs = D.fl["buy"], D.fl["sell"]; out = []; free = 0
    for i in range(9, len(b) - 1):
        t = M[i]
        if t > tmax or i < free or M[i] - M[i - 4] != 4 or (bk is not None and t not in bk): 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])
        if (1 - b[i - 3]["c"] / hi) * 100 < 0.5: continue
        s3, s15 = share(fb, fs, t, 3), share(fb, fs, t, 15)
        chk = {"PC": b[i]["c"] >= pc, "VOL": 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]]),
               "BUY": s3 >= 0.55, "X": cross3(fb, fs, t),
               "ABOVE": s3 > s15, "UP1": s3 > share(fb, fs, t - 1, 3) and s15 > share(fb, fs, t - 1, 15), "UP3": s3 > share(fb, fs, t - 3, 3) and s15 > share(fb, fs, t - 3, 15)}
        if bk is not None:
            q = [bk[k]["imbalance"] for k in (t - 2, t - 1, t) if k in bk]; chk["Q"] = bool(q) and np.mean(q) > 0
        if not all(chk[k] for k in need): 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"); first = 0
        for x in b[bi:bi + 120]:
            if x["l"] <= P * 0.99: first = -1; break
            if x["h"] >= P * 1.01: first = 1; break
        out.append(dict(t=t, pl=round(pl, 3), why=why, first=first, sell_m=M[j], P=P)); free = j + 1
    return out
def f(Z):
    if not Z: return "n     0"
    return (f"n {len(Z):5} | +1% first {np.mean([z['first'] == 1 for z in Z]):3.0%} -1% first {np.mean([z['first'] == -1 for z in Z]):3.0%} "
            f"| C3 {np.mean([z['pl'] for z in Z]):+.3f}%/trade win {np.mean([z['pl'] > 0 for z in Z]):3.0%} total {sum(z['pl'] for z in Z):+7.1f}%")
hm = lambda m: f"{9 + (30 + m) // 60}:{(30 + m) % 60:02d}"
mode = sys.argv[1]
if mode == "fmc":
    import ev3
    from datetime import datetime
    from zoneinfo import ZoneInfo
    from config_loader import get_env
    from alpaca.data.requests import StockBarsRequest
    from alpaca.data.timeframe import TimeFrame
    from alpaca.data.historical import StockHistoricalDataClient
    ET = ZoneInfo("America/New_York"); env = get_env(); hc = StockHistoricalDataClient(env.api_key, env.secret_key)
    day, sym = sys.argv[2], sys.argv[3]; 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]
    bars = [{"t": x.timestamp, "o": x.open, "h": x.high, "l": x.low, "c": x.close, "v": x.volume} for x in raw if 0 <= ev3.minute_of(x.timestamp) < 390]
    ref = json.load(open(TR / f"data/reference/{day}/{sym}.json")); fl = json.loads((TR / f"reports/open_window/flow/{day}/{sym}.json").read_text())
    D = Day(bars, [ev3.minute_of(x["t"]) for x in bars], fl, ref)
    for lab, need in V.items():
        T = scan(D, need); print(f"{lab:42} -> " + (", ".join(f"buy {hm(x['t'] + 1)} {x['P']:.2f} sold {hm(x['sell_m'])} {x['pl']:+.2f}%" for x in T) or "no trade") + (f"  | day {sum(x['pl'] for x in T):+.2f}%" if T else ""))
elif mode == "11d":
    import io, contextlib
    with contextlib.redirect_stdout(io.StringIO()):
        from up3_test import load, DAYS
    S = load(); half = DAYS[6]; V11 = dict(V); V11.update({"ABOVE + QUEUE": ["VOL", "ABOVE", "UP1", "Q"], "ABOVE + buyers + QUEUE": ["VOL", "BUY", "ABOVE", "UP1", "Q"]} if "above" in sys.argv else {"NEW + QUEUE": ["VOL", "X", "UP1", "Q"], "NEW + buyers + QUEUE": ["VOL", "BUY", "X", "UP1", "Q"]})
    print(f"{len(S)} stock-days, {len(DAYS)} days (live watch list); C3 after 0.2% cost")
    for lab, need in V11.items():
        T = [dict(day=d, **x) for d, s, D, bk in S for x in scan(D, need, bk=bk)]
        print(f"{lab}\n   days 1-6  {f([x for x in T if x['day'] < half])}\n   days 7-{len(DAYS)} {f([x for x in T if x['day'] >= half])}")
else:
    import v2_bar_replay as R
    OUT = {k: [] for k in V}; n = 0
    for p in sorted(R.OW.glob("bars/bars_20*.json.gz")):
        day = p.name[5:15]
        if not ("2024-10-01" <= day <= "2026-10-02"): continue
        d = json.load(gzip.open(p, "rt"))
        for s in d["top30_current"]:
            fp = R.OW / "flow" / day / f"{s}.json"; ref = R.REF.load(day, s)
            if s not in d["symbols"] or not fp.exists() or not ref or not ref.get("atr14") or not ref.get("prev_close"): continue
            b = [x for x in R.bars_of(d["symbols"][s]["bars"]) if 0 <= R.minute(x["t"]) < 390]
            if len(b) < 200: continue
            D = Day(b, [R.minute(x["t"]) for x in b], json.loads(fp.read_text()), ref)
            for k, need in V.items():
                for x in scan(D, need): OUT[k].append(dict(day=day, sym=s, **x))
        del d; R.REF._CACHE.clear(); n += 1
        if n % 50 == 0: print(day, n, flush=True)
    json.dump(OUT, open(HERE / ("up3x_above_2y.json" if "above" in sys.argv else "up3x_2y.json"), "w"))
    print(f"\n{n} days; C3 after 0.2% cost; year 1 = 2024-10..2025-09, year 2 = 2025-10..2026-10")
    for k, T in OUT.items():
        print(f"{k}\n   year 1 {f([x for x in T if x['day'] < '2025-10-01'])}\n   year 2 {f([x for x in T if x['day'] >= '2025-10-01'])}")
    print("UP3X2Y_DONE")
