"""
limit_entry_test.py -- [2026-10-07] The user: test BUYING WITH LIMIT ORDERS (real fills showed market orders cost ~0.2% a
round trip). For every real buy of both bots (trade files, reconciled to real fills), replay the seconds after the buy
decision with Alpaca's historical quotes + trades:
  limit price  BID / MID / MID + 25% of the spread, from the quote at the decision time
  wait         10 / 30 / 60 / 120 s
  filled if    a trade prints below the limit (at the bid: strictly below = conservative about queue position) or at/below it
               (mid levels) within the wait
  not filled   SKIP the trade, or MARKET after the wait (= the ask then)
Each trade keeps its REAL exit (the broker's fill). Compared with the real market-order entry. $ at each trade's real qty.
    python3 limit_entry_test.py
"""
import glob
import json
import sys
from datetime import datetime, timedelta
from pathlib import Path

sys.path.insert(0, "/var/www/screener/trade")
from alpaca_client import get_client

c = get_client()
T = []
for b in ("/var/www/screener/trade", "/var/www/screener/premarket"):
    for f in sorted(glob.glob(f"{b}/data/trades/2026-*_trades.jsonl")):
        for l in open(f):
            t = json.loads(l)
            if t.get("status") == "closed" and t.get("exit_price") and t.get("entry_time"):
                t["bot"] = "star" if "premarket" in b else "trade"; T.append(t)
print(f"{len(T)} real trades", flush=True)
WAITS = (10, 30, 60, 120)
LEVELS = ("bid", "mid", "mid+")
res = {(lv, w, mode): {"pl": 0.0, "filled": 0, "saved": 0.0, "missed_pl": 0.0, "n": 0} for lv in LEVELS for w in WAITS for mode in ("skip", "market")}
base = 0.0
for i, t in enumerate(T):
    t0 = datetime.fromisoformat(t["entry_time"])
    try:
        Q = c.get_historical_quotes(t["symbol"], t0 - timedelta(seconds=5), t0 + timedelta(seconds=125))
        X = c.get_historical_trades(t["symbol"], t0, t0 + timedelta(seconds=125))
    except Exception as e:
        print("skip", t["symbol"], e); continue
    q0 = [q for q in Q if q["t"] <= t0 and q["b"] > 0 and q["a"] >= q["b"]]
    if not q0:
        continue
    bid, ask = q0[-1]["b"], q0[-1]["a"]
    mid = (bid + ask) / 2
    fill_real, exit_real, qty = t["entry_price"], t["exit_price"], t["qty"]
    pl_real = (exit_real - fill_real) * qty
    base += pl_real
    for lv in LEVELS:
        L = bid if lv == "bid" else mid if lv == "mid" else mid + 0.25 * (ask - bid)
        for w in WAITS:
            end = t0 + timedelta(seconds=w)
            got = any((x["p"] < L if lv == "bid" else x["p"] <= L) for x in X if t0 <= x["t"] <= end)
            later_q = [q for q in Q if q["t"] <= end and q["b"] > 0]
            ask_end = later_q[-1]["a"] if later_q else ask
            for mode in ("skip", "market"):
                r = res[(lv, w, mode)]; r["n"] += 1
                if got:
                    r["filled"] += 1; r["pl"] += (exit_real - L) * qty; r["saved"] += (fill_real - L) * qty
                elif mode == "market":
                    px = max(ask_end, fill_real) if ask_end else fill_real
                    r["pl"] += (exit_real - px) * qty; r["saved"] += (fill_real - px) * qty
                else:
                    r["missed_pl"] += pl_real                      # what the skipped trade really made
    if i % 25 == 0:
        print(i, flush=True)
print(f"\nREAL (market orders): {len(T)} trades, ${base:+.2f}\n")
print(f"{'limit':6} {'wait':>5} {'if not filled':14} | {'filled':>7} | {'total $':>9} | {'vs real':>8} | entry price saved on fills | P/L of the skipped trades")
for (lv, w, mode), r in res.items():
    print(f"{lv:6} {w:4}s {mode:14} | {r['filled'] / max(r['n'], 1):6.0%} | {r['pl']:+9.2f} | {r['pl'] - base:+8.2f} | ${r['saved']:+8.2f}"
          + (f" | skipped trades made ${r['missed_pl']:+.2f}" if mode == "skip" else ""))
