"""star_stop_test.py -- [2026-10-27] the user: the 3% safety stop gives back the profit (CLRO 10/27 +5.6% -> -3.2%). Replays every REAL
Star-bot trade (premarket/logs, 10/5..) on Alpaca 1-min bars with profit-protecting stops ON TOP of the 3% floor; Star's own sells stay
exactly as they happened -- a new stop only matters if it is hit BEFORE Star's real sell. No look-ahead: the stop for bar j uses the high of
bars before j; hit = bar low <= stop, filled at the stop (or the open if it gapped below). The buy bar and Star's sell bar are not used.
$ = real shares x price change (real fills where logged)."""
import glob, json, re, sys
from datetime import datetime
from pathlib import Path
from zoneinfo import ZoneInfo
HERE = Path(__file__).resolve().parent; TR = Path("/var/www/screener/trade"); sys.path.insert(0, str(TR))
from alpaca.data.requests import StockBarsRequest
from alpaca.data.timeframe import TimeFrame
from alpaca.data.historical import StockHistoricalDataClient
from config_loader import get_env
ET = ZoneInfo("America/New_York"); hc = None
toM = lambda s: (int(s[:2]) - 9) * 60 + int(s[3:5]) - 30
def trades():
    out = []
    for f in sorted(glob.glob("/var/www/screener/premarket/logs/star_bot_2026-*.log")):
        day = f[-14:-4]; open_ = {}
        for l in open(f, errors="ignore"):
            m = re.search(r"\[ENTRY\] (\S+) BUY (\d+) @ ~?\$([\d.]+)(?: -- limit filled)?.*?stop \$([\d.]+)", l)
            if m and "LIMIT BUY" not in l:
                open_[m[1]] = dict(day=day, sym=m[1], n=int(m[2]), buy=float(m[3]), stop=float(m[4]), bt=l[11:16]); continue
            m = re.search(r"\[EXIT\] (\S+) SELL (?:\d+ )?@ ~?\$([\d.]+).*?P/L", l)
            if m and m[1] in open_:
                t = open_.pop(m[1]); rf = re.search(r"REAL FILL: bought ([\d.]+), sold ([\d.]+)", l)
                if rf: t["buy"], sell = float(rf[1]), float(rf[2])
                else: sell = float(m[2])
                why = re.search(r"\((STAR[^)]*|SAFETY STOP[^)]*|END_OF_DAY)\)", l) or re.search(r"\(([^)]*)\)", l)
                t.update(sell=sell, st=l[11:16], why=why[1] if why else "?"); out.append(t)
    return out
def bars(day, sym):
    global hc
    p = HERE / "star_bars" / f"{day}_{sym}.json"
    if p.exists(): return {int(k): v for k, v in json.loads(p.read_text()).items()}
    if hc is None: env = get_env(); hc = StockHistoricalDataClient(env.api_key, env.secret_key)
    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.get(sym, [])
    B = {}
    for x in raw:
        t = x.timestamp.astimezone(ET); m = (t.hour - 9) * 60 + t.minute - 30
        if 0 <= m < 390: B[m] = [x.open, x.high, x.low, x.close]
    p.write_text(json.dumps(B)); return B
def sim(t, B, rule):
    """-> (sell price, minute, why) ; rule(P, high_so_far, S0) -> stop"""
    P, S0 = t["buy"], t["stop"]; bm, em = toM(t["bt"]), toM(t["st"]); hi = P
    for j in range(bm + 1, em):
        if j not in B: continue
        o, h, l, c = B[j]; s = max(S0, rule(P, hi, S0))
        if l <= s: return min(s, o), j, "new stop"
        hi = max(hi, h)
    return t["sell"], em, "star"
RULES = {"ACTUAL (3% floor only)": lambda P, H, S: S}
for x in (1.0, 1.5, 2.0, 3.0): RULES[f"A break-even once +{x}%"] = (lambda x: lambda P, H, S: P * 1.002 if H >= P * (1 + x / 100) else S)(x)
for x in (1.5, 2.0, 3.0): RULES[f"B keep half the best gain once +{x}%"] = (lambda x: lambda P, H, S: P + 0.5 * (H - P) if H >= P * (1 + x / 100) else S)(x)
for a, y in ((1.5, 1.0), (2.0, 1.0), (2.0, 1.5), (2.0, 2.0), (3.0, 1.5), (3.0, 2.0)):
    RULES[f"C trail {y}% under the high once +{a}%"] = (lambda a, y: lambda P, H, S: H * (1 - y / 100) if H >= P * (1 + a / 100) else S)(a, y)
if __name__ == "__main__":
    T = trades(); print(f"{len(T)} real Star trades {T[0]['day']} .. {T[-1]['day']}")
    res = {}
    for k, rule in RULES.items():
        R = []
        for t in T:
            B = bars(t["day"], t["sym"]); px, j, why = sim(t, B, rule)
            R.append(dict(t, new=px, nwhy=why, nm=j, usd=(px - t["buy"]) * t["n"], pct=(px / t["buy"] - 1) * 100))
        res[k] = R
    base = res["ACTUAL (3% floor only)"]; b_usd = sum(r["usd"] for r in base)
    print(f"\n{'rule':42} | total $ | vs actual | win% | changed trades (better / worse)")
    for k, R in res.items():
        usd = sum(r["usd"] for r in R); ch = [(r, b) for r, b in zip(R, base) if abs(r["usd"] - b["usd"]) > 0.005]
        print(f"{k:42} | {usd:+8.2f} | {usd - b_usd:+8.2f} | {sum(r['usd'] > 0 for r in R) / len(R):4.0%} | {len(ch):3} ({sum(r['usd'] > b['usd'] for r, b in ch)} / {sum(r['usd'] < b['usd'] for r, b in ch)})")
    print("\nbiggest give-backs in the ACTUAL trades (best gain while held -> result):")
    for t in T:
        B = bars(t["day"], t["sym"]); bm, em = toM(t["bt"]), toM(t["st"])
        t["mfe"] = (max([B[j][1] for j in range(bm + 1, em) if j in B] or [t["buy"]]) / t["buy"] - 1) * 100; t["res"] = (t["sell"] / t["buy"] - 1) * 100
    for t in sorted(T, key=lambda t: t["res"] - t["mfe"])[:10]:
        print(f"   {t['day']} {t['sym']:5} {t['bt']}->{t['st']} best +{t['mfe']:.2f}% -> {t['res']:+.2f}%  ({t['why'][:45]})")
    json.dump({k: [{kk: vv for kk, vv in r.items()} for r in R] for k, R in res.items()}, open(HERE / "star_stop_test.json", "w"), default=str)
    print("STOPTEST_DONE")
