diff --git a/momentum_cli.py b/momentum_cli.py index ed19b34..c02615e 100644 --- a/momentum_cli.py +++ b/momentum_cli.py @@ -387,9 +387,69 @@ def _latest_eval_board(con) -> dict: return seen +def _market_clock(): + """(phase, detail, color) for the US equities regular session, in ET.""" + from datetime import datetime as _dt + try: + from zoneinfo import ZoneInfo + now = _dt.now(ZoneInfo("America/New_York")) + except Exception: # noqa: BLE001 + now = _dt.now() + open_t = now.replace(hour=9, minute=30, second=0, microsecond=0) + close_t = now.replace(hour=16, minute=0, second=0, microsecond=0) + if now.weekday() >= 5: + return ("CLOSED", "weekend", "dim") + if now < open_t: + s = int((open_t - now).total_seconds()) + return ("PRE-OPEN", f"opens in {s // 3600}h {s % 3600 // 60}m", "yellow") + if now > close_t: + return ("CLOSED", "after hours", "dim") + s = int((close_t - now).total_seconds()) + return ("OPEN", f"{s // 3600}h {s % 3600 // 60}m to close", "green") + + +def _triggers_snapshot(con): + """Latest armed-trigger snapshot emitted by the live loop's `trigger` step. + + Returns (rows, snapshot_timestamp, armed_count). rows is the per-symbol + board data (state/price/gap/rvol/trigger/distance/stop). + """ + rows = con.execute( + "SELECT timestamp, payload_json FROM events WHERE event_type='module_tick' " + "ORDER BY timestamp DESC LIMIT 120").fetchall() + for ts, pj in rows: + p = json.loads(pj) + if p.get("module") == "triggers": + metrics = p.get("metrics") or {} + return (metrics.get("triggers") or [], ts, metrics.get("armed", 0)) + return ([], None, 0) + + +def _heartbeat(ts) -> tuple[str, str]: + """(text, color) describing how long ago the loop last published.""" + if ts is None: + return ("no loop signal yet", "red") + from datetime import datetime as _dt + try: + when = ts if isinstance(ts, _dt) else _dt.fromisoformat(str(ts)) + secs = (_dt.now() - when.replace(tzinfo=None)).total_seconds() + except Exception: # noqa: BLE001 + return ("loop signal seen", "green") + color = "green" if secs < 15 else ("yellow" if secs < 45 else "red") + return (f"loop {int(secs)}s ago", color) + + +_STATE_STYLE = { + "armed": ("bold cyan", "● ARMED"), + "fired": ("bold magenta", "▶ FIRED"), + "filled": ("bold green", "◆ LONG"), + "waiting": ("dim", "· waiting"), + "weak": ("dim yellow", " weak"), +} + + def _render_board(con): """Build the live monitoring board renderable.""" - from datetime import datetime from rich.console import Group from rich.panel import Panel @@ -400,22 +460,38 @@ def _render_board(con): if acct: eq = json.loads(acct[0][0]).get("total_equity", "—") - seen = _latest_eval_board(con) - ready = [s for s, v in seen.items() if v[1] == "ready"] - et = Table(box=box.SIMPLE_HEAVY, expand=True) - for c, j in (("symbol", "left"), ("status", "center"), ("score", "right"), - ("gap", "right"), ("rvol", "right"), ("why", "left")): - et.add_column(c, justify=j, no_wrap=(c != "why")) - for sym, (score, status, gap, rvol, reason) in sorted(seen.items(), key=lambda x: -(x[1][0] or 0))[:28]: - color = {"ready": "bold green", "late": "yellow", "blocked": "red"}.get(status, "white") - et.add_row( - sym, f"[{color}]{(status or '?').upper()}[/{color}]", f"{score:.0f}%", - f"{gap:+.1%}" if isinstance(gap, (int, float)) else "-", - f"{rvol:.1f}x" if isinstance(rvol, (int, float)) else "-", - (reason or "")[:46]) + phase, detail, pcolor = _market_clock() + trig_rows, snap_ts, armed_n = _triggers_snapshot(con) + hb_text, hb_color = _heartbeat(snap_ts) + + # --- the 6 armed triggers: the focused, live watchlist ------------------ + tt = Table(box=box.SIMPLE_HEAVY, expand=True, + title="armed triggers — the 6 most-promising gappers, ready to fire") + for c, j in (("symbol", "left"), ("state", "left"), ("price", "right"), + ("gap", "right"), ("rvol", "right"), ("trigger", "right"), + ("→trigger", "right"), ("stop", "right")): + tt.add_column(c, justify=j, no_wrap=True) + for r in trig_rows: + style, label = _STATE_STYLE.get(r.get("state"), ("white", r.get("state", "?"))) + price = r.get("price"); trig = r.get("trigger"); dist = r.get("dist") + stop = r.get("stop"); gap = r.get("gap"); rvol = r.get("rvol") + tt.add_row( + f"[{style}]{r.get('symbol')}[/{style}]", + f"[{style}]{label}[/{style}]", + f"{price:.2f}" if isinstance(price, (int, float)) else "—", + f"{gap:+.1f}%" if isinstance(gap, (int, float)) else "—", + f"{rvol:.1f}x" if isinstance(rvol, (int, float)) else "—", + f"{trig:.2f}" if isinstance(trig, (int, float)) else "—", + (f"[green]▲{dist * 100:+.2f}%[/green]" if isinstance(dist, (int, float)) and dist >= 0 + else (f"{dist * 100:+.2f}%" if isinstance(dist, (int, float)) else "—")), + f"{stop:.2f}" if isinstance(stop, (int, float)) else "—", + ) + if not trig_rows: + tt.add_row("[dim]—[/dim]", "[dim]waiting for the open / first bars[/dim]", + "—", "—", "—", "—", "—", "—") sig = con.execute("SELECT timestamp, message FROM events WHERE event_type='signal_ready' " - "ORDER BY timestamp DESC LIMIT 6").fetchall() + "ORDER BY timestamp DESC LIMIT 5").fetchall() st = Table(title="ready signals", box=box.SIMPLE) st.add_column("time", style="cyan"); st.add_column("signal", overflow="fold") for ts, m in sig: @@ -433,18 +509,22 @@ def _render_board(con): risk = con.execute("SELECT timestamp, message FROM events WHERE event_type='risk_rule_triggered' " "ORDER BY timestamp DESC LIMIT 4").fetchall() - rt = Table(title="risk events", box=box.SIMPLE) - rt.add_column("time", style="cyan"); rt.add_column("rule", overflow="fold") + rk = Table(title="risk / circuit breaker", box=box.SIMPLE) + rk.add_column("time", style="cyan"); rk.add_column("rule", overflow="fold") for ts, m in risk: - rt.add_row(str(ts)[11:19], m or "") + rk.add_row(str(ts)[11:19], m or "") + n_eval = len(_latest_eval_board(con)) header = Panel( - f"[bold]momentum live[/bold] equity [green]{eq}[/green] " - f"{datetime.now().strftime('%H:%M:%S')} " - f"{len(seen)} evaluated · [bold green]{len(ready)} ready[/bold green] " - f"[dim](window 9:30–10:35 ET · Ctrl-C to exit)[/dim]", + f"[bold]momentum live[/bold] " + f"[{pcolor}]{phase}[/{pcolor}] [dim]{detail}[/dim] " + f"equity [green]{eq}[/green] " + f"[{hb_color}]♥ {hb_text}[/{hb_color}] " + f"[bold cyan]{armed_n} armed[/bold cyan] · {n_eval} scanning\n" + f"[dim]hunting $1–20 gappers (≥ gap% on ≥ 2× volume); buy the break of the " + f"opening-range high, stop at its low · Ctrl-C to exit[/dim]", style="cyan") - return Group(header, et, st, pt, rt) + return Group(header, tt, st, pt, rk) @app.command() diff --git a/run_live_paper.py b/run_live_paper.py index 40319f5..bf66f8f 100644 --- a/run_live_paper.py +++ b/run_live_paper.py @@ -49,6 +49,7 @@ from research.ingestion.scheduler import Scheduler from research.ingestion.watcher_task import ResearchWatchlistProvider from research.ingestion.discovery import run_discovery, screen_universe from research.multi_schema import open_research_db +from runtime.triggers import ArmedTriggerBook from runtime.watcher import Watcher, WatcherConfig from storage.event_schema import EventMode, ModuleTickEvent from storage.event_store import EventStore @@ -253,6 +254,16 @@ def build_runtime(args: argparse.Namespace) -> dict: ) sync = AlpacaPaperSync(store, client=client, session_id=session_id) if client else None + # Fast armed-trigger book: keep the N most-promising gappers ready with a + # pre-computed opening-range trigger/stop so step_trigger can fire the + # instant live price crosses (instead of waiting for a bar close + cadence). + book = ArmedTriggerBook( + max_armed=int(os.environ.get("TRIGGER_MAX_ARMED", "6")), + gap_min=float(os.environ.get("TRIGGER_GAP_MIN", "3.0")), + rvol_min=float(os.environ.get("TRIGGER_RVOL_MIN", "2.0")), + min_range_pct=float(os.environ.get("TRIGGER_MIN_RANGE_PCT", "0.004")), + ) + return { "symbols": symbols, "symbols_source": symbols_source, @@ -263,6 +274,8 @@ def build_runtime(args: argparse.Namespace) -> dict: "watcher": watcher, "execution": execution, "sync": sync, + "book": book, + "latest_price": latest_price, "session_id": session_id, "event_db": event_db, } @@ -410,6 +423,93 @@ def main(argv: list[str] | None = None) -> int: return (f"universe={len(res.universe)} gappers={len(res.gappers)}" + (f" +{len(added)} new" if added else "")) + # --- fast armed-trigger path ------------------------------------------- + book = rt["book"] + latest_price = rt["latest_price"] + price_min_v = float(os.environ.get("WATCHER_PRICE_MIN", "1")) + price_max_v = float(os.environ.get("WATCHER_PRICE_MAX", "20")) + orb_bars_v = int(os.environ.get("ORB_BARS", "5")) + stop_cushion_v = float(os.environ.get("TRIGGER_STOP_CUSHION", "0.005")) + + def step_arm(): + """Rank the most-promising gappers and pre-compute each one's opening- + range breakout trigger/stop, so step_trigger can fire on a live cross.""" + from research import query as rq + from research.ingestion.signals import scan_gappers + from strategy.evaluation.structure import opening_range + + session_date = _now_session_date() + candidates: list[dict] = [] + # rank ALL session symbols by gap*rvol (thresholds applied later, per + # trigger, so the board still shows the field pre-gap) + gappers = scan_gappers( + rt["research_con"], session_date, + min_gap_pct=0.0, min_relative_volume=0.0, + price_min=price_min_v, price_max=price_max_v, limit=12, + ) + for g in gappers: + bars = rq.query_minute_bars(rt["research_con"], g.symbol, session_date) + hi, lo, complete = opening_range(bars, orb_bars=orb_bars_v) + stop = lo * (1.0 - stop_cushion_v) if lo else None + candidates.append({ + "symbol": g.symbol, + "gap_pct": g.gap_pct, + "rvol": g.relative_volume, + "trigger": hi, + "stop": stop, + "range_pct": ((hi - lo) / hi) if (hi and lo and hi > 0) else 0.0, + "complete": complete, + }) + # pre-open / before any gappers form: surface the queued watchlist so the + # board shows what we're about to watch instead of looking blank + if not candidates: + for s in symbols[: book.max_armed]: + candidates.append({"symbol": s, "gap_pct": 0.0, "rvol": 0.0, + "trigger": None, "stop": None, + "range_pct": 0.0, "complete": False}) + book.arm(candidates) + armed = sum(1 for t in book.triggers.values() if t.state == "armed") + return f"tracking={len(book.triggers)} armed={armed}" + + def step_trigger(): + """Fast tick: refresh live prices for the armed names, fire any that have + crossed their trigger, and publish the snapshot the live board renders.""" + if not book.triggers: + return None + for sym in list(book.triggers): + book.update_price(sym, latest_price(sym) if client else None) + if rt["execution"] is not None: + try: + book.mark_filled(rt["execution"]._held_symbols()) + except Exception: # noqa: BLE001 + pass + fired: list[str] = [] + if rt["execution"] is not None: + for t in book.fires(): + res = rt["execution"].submit_breakout_now( + t.symbol, t.trigger, t.stop, last_price=t.price + ) + if res.get("ok"): + book.mark_fired(t.symbol) + fired.append(t.symbol) + armed_n = sum(1 for t in book.triggers.values() if t.state == "armed") + rt["store"].emit( + ModuleTickEvent( + timestamp=datetime.now(), + mode=EventMode.PAPER, + correlation_id=rt["session_id"], + message=f"triggers armed={armed_n} fired={len(fired)}", + module="triggers", + stage="snapshot", + duration_ms=0.0, + input_count=len(book.triggers), + output_count=len(fired), + metrics={"triggers": book.snapshot(), "armed": armed_n}, + errors=[], + ) + ) + return ("FIRED " + ", ".join(fired)) if fired else None + scheduler = Scheduler() scheduler.add("discover", step_discover, float(os.environ.get("DISCOVER_INTERVAL_SECONDS", "300")), @@ -418,6 +518,10 @@ def main(argv: list[str] | None = None) -> int: enabled=_flag("LIVE_BARS_ENABLED", "1")) scheduler.add("watch", step_watch, float(os.environ.get("WATCHER_INTERVAL_SECONDS", "30")), enabled=_flag("WATCHER_ENABLED", "1")) + scheduler.add("arm", step_arm, float(os.environ.get("TRIGGER_ARM_INTERVAL_SECONDS", "20")), + enabled=_flag("TRIGGER_ENABLED", "1")) + scheduler.add("trigger", step_trigger, float(os.environ.get("TRIGGER_INTERVAL_SECONDS", "4")), + enabled=_flag("TRIGGER_ENABLED", "1")) scheduler.add("sync", step_sync, float(os.environ.get("ALPACA_PAPER_SYNC_INTERVAL_SECONDS", "60")), enabled=_flag("ALPACA_PAPER_SYNC_ENABLED", "1")) scheduler.add("execute", step_execute, float(os.environ.get("TRADING_EXECUTION_INTERVAL_SECONDS", "30")), @@ -430,7 +534,7 @@ def main(argv: list[str] | None = None) -> int: for task in scheduler.tasks: task.last_run = -10**9 results = {} - for name in ("discover", "ingest", "watch", "sync", "execute"): + for name in ("discover", "ingest", "watch", "arm", "trigger", "sync", "execute"): for task in scheduler.tasks: if task.name == name and task.enabled: results.update(scheduler_run_one(task)) diff --git a/runtime/triggers.py b/runtime/triggers.py new file mode 100644 index 0000000..f710519 --- /dev/null +++ b/runtime/triggers.py @@ -0,0 +1,171 @@ +"""Armed opening-range-breakout triggers — the fast, top-N watchlist. + +The watcher path reacts only after a 1-minute candle *closes* above the +breakout level and then walks the ingest->watch->execute cadence (up to a +couple of minutes), and it rests a limit *at* the trigger that a fast runner +never comes back to fill. Both make us late and make us miss the move. + +This book is the fix. It keeps the handful of most-promising gappers "armed": +the trigger (opening-range high) and stop (opening-range low) are pre-computed +the moment the opening range finishes forming, so the live loop can fire the +instant the *live* price crosses the trigger — the systematic version of Ross +Cameron's "enter when the candle is breaking, on faith that the volume is +there." Pure state + decision logic; the loop owns I/O (prices, orders). + +State machine per symbol: + + waiting - opening range not complete yet (before ~09:35 ET) + armed - range complete and gap/rvol/range qualify -> may fire on a cross + weak - range complete but the setup is too soft to fire (shown, greyed) + fired - a breakout order has been submitted + filled - the position is open at the broker +""" + +from __future__ import annotations + +from dataclasses import dataclass, field + +WAITING = "waiting" +ARMED = "armed" +WEAK = "weak" +FIRED = "fired" +FILLED = "filled" + +# states that represent a committed trade — pinned across re-ranking so a name +# that fired doesn't get bumped off the board when the gapper ranking rotates +_COMMITTED = (FIRED, FILLED) + + +@dataclass +class ArmedTrigger: + symbol: str + gap_pct: float = 0.0 + rvol: float = 0.0 + trigger: float | None = None # opening-range high (entry breakout level) + stop: float | None = None # opening-range low, cushioned (protective stop) + range_pct: float = 0.0 # (high-low)/high — how wide the opening range is + price: float | None = None # latest live trade price + state: str = WAITING + rank: int = 0 + + def distance_pct(self) -> float | None: + """How far live price is from the trigger, as a fraction. + + Negative = still below the trigger (waiting for the break); >= 0 = at or + through it. None until we have both a price and a trigger. + """ + if self.price and self.trigger: + return (self.price - self.trigger) / self.trigger + return None + + def as_dict(self) -> dict: + d = self.distance_pct() + return { + "symbol": self.symbol, + "state": self.state, + "rank": self.rank, + "gap": round(self.gap_pct, 2), + "rvol": round(self.rvol, 2), + "trigger": round(self.trigger, 4) if self.trigger else None, + "stop": round(self.stop, 4) if self.stop else None, + "price": round(self.price, 4) if self.price else None, + "dist": round(d, 5) if d is not None else None, + "range_pct": round(self.range_pct, 4), + } + + +@dataclass +class ArmedTriggerBook: + """Tracks the top ``max_armed`` gappers and decides when each may fire.""" + + max_armed: int = 6 + gap_min: float = 3.0 # min overnight gap % to be eligible to fire + rvol_min: float = 2.0 # min relative volume to be eligible to fire + min_range_pct: float = 0.004 # opening range must be at least this wide + triggers: dict[str, ArmedTrigger] = field(default_factory=dict) + + def _eligible(self, t: ArmedTrigger) -> bool: + return ( + t.trigger is not None + and t.stop is not None + and t.stop < t.trigger + and t.gap_pct >= self.gap_min + and t.rvol >= self.rvol_min + and t.range_pct >= self.min_range_pct + ) + + def arm(self, candidates: list[dict]) -> None: + """Refresh the book from a ranked candidate list. + + ``candidates`` are dicts (best first): + {symbol, gap_pct, rvol, trigger, stop, range_pct, complete} + + Symbols already ``fired``/``filled`` are pinned (kept regardless of the + new ranking); the remaining ``max_armed`` slots are filled from the top + of ``candidates`` and (re)classified waiting/armed/weak. + """ + pinned = {s: t for s, t in self.triggers.items() if t.state in _COMMITTED} + new: dict[str, ArmedTrigger] = dict(pinned) + rank = 0 + for c in candidates: + sym = c["symbol"] + if sym in new: # already pinned/committed + continue + active = sum(1 for t in new.values() if t.state not in _COMMITTED) + if active >= self.max_armed: + break + rank += 1 + t = self.triggers.get(sym) or ArmedTrigger(symbol=sym) + t.gap_pct = float(c.get("gap_pct") or 0.0) + t.rvol = float(c.get("rvol") or 0.0) + t.trigger = c.get("trigger") + t.stop = c.get("stop") + t.range_pct = float(c.get("range_pct") or 0.0) + t.rank = rank + if not c.get("complete") or t.trigger is None: + t.state = WAITING + elif self._eligible(t): + t.state = ARMED + else: + t.state = WEAK + new[sym] = t + self.triggers = new + + def update_price(self, symbol: str, price: float | None) -> None: + t = self.triggers.get(symbol) + if t is not None and price is not None: + t.price = float(price) + + def fires(self) -> list[ArmedTrigger]: + """Armed triggers whose live price has reached or crossed the trigger.""" + return [ + t + for t in self.triggers.values() + if t.state == ARMED + and t.price is not None + and t.trigger is not None + and t.price >= t.trigger + ] + + def mark_fired(self, symbol: str) -> None: + t = self.triggers.get(symbol) + if t is not None: + t.state = FIRED + + def mark_filled(self, held_symbols) -> None: + """Promote tracked symbols that are now open broker positions to filled.""" + held = set(held_symbols or ()) + for sym, t in self.triggers.items(): + if sym in held: + t.state = FILLED + + def snapshot(self) -> list[dict]: + """Board-ready rows, ordered armed -> fired -> filled -> waiting -> weak.""" + order = {ARMED: 0, FIRED: 1, FILLED: 2, WAITING: 3, WEAK: 4} + return [ + t.as_dict() + for t in sorted( + self.triggers.values(), + key=lambda t: (order.get(t.state, 9), t.rank), + ) + ] diff --git a/strategy/evaluation/structure.py b/strategy/evaluation/structure.py index c2e41b2..68c8307 100644 --- a/strategy/evaluation/structure.py +++ b/strategy/evaluation/structure.py @@ -531,6 +531,28 @@ def detect_continuation_fallback( ) +def opening_range(bars: pd.DataFrame, orb_bars: int = 5): + """High/low of the first ``orb_bars`` regular-hours bars. + + Returns ``(high, low, complete)``. ``complete`` is False — and high/low are + None — until ``orb_bars`` regular-hours bars exist, so a caller can arm a + breakout trigger the moment the opening range finishes forming (≈09:35 ET) + without waiting for a later bar to actually break it. Shares one definition + of "the opening range" with ``detect_opening_range_breakout`` below. + """ + if bars is None or len(bars) == 0: + return (None, None, False) + if "is_regular_hours" in bars.columns: + rth = bars[bars["is_regular_hours"] == True] # noqa: E712 + rth = rth.reset_index(drop=True) + else: + rth = bars.reset_index(drop=True) + if len(rth) < orb_bars: + return (None, None, False) + orb = rth.iloc[:orb_bars] + return (float(orb["high"].max()), float(orb["low"].min()), True) + + def detect_opening_range_breakout( bars: pd.DataFrame, orb_bars: int = 5, diff --git a/tests/unit/test_triggers.py b/tests/unit/test_triggers.py new file mode 100644 index 0000000..56b8619 --- /dev/null +++ b/tests/unit/test_triggers.py @@ -0,0 +1,172 @@ +"""Armed-trigger fast path: opening range, the trigger book, and live-fire. + +Locks in the "don't miss the move" mechanics: the opening range is computed +once it's complete; a qualified trigger arms and fires only when live price +crosses it; fired names are pinned across re-ranking; and submit_breakout_now +honours the same risk gates as the slow path while placing a marketable order. +""" + +import pandas as pd + +from alpaca_paper.execution import AlpacaPaperExecutor +from runtime.triggers import ( + ARMED, + FILLED, + FIRED, + WAITING, + WEAK, + ArmedTriggerBook, +) +from storage.event_store import EventStore +from strategy.evaluation.structure import opening_range +from trading_execution import ExecutionSettings, TradingExecutionService + + +def _bars(highs_lows): + rows = [] + base = pd.Timestamp("2026-06-17 13:30:00") # 09:30 ET in UTC-naive + for i, (h, l) in enumerate(highs_lows): + rows.append({ + "timestamp": base + pd.Timedelta(minutes=i), + "open": l, "high": h, "low": l, "close": h, "volume": 1000, + "is_regular_hours": True, + }) + return pd.DataFrame(rows) + + +# -- opening range -------------------------------------------------------- + +def test_opening_range_incomplete_until_n_bars(): + hi, lo, complete = opening_range(_bars([(10, 9.5), (10.2, 9.8)]), orb_bars=5) + assert complete is False and hi is None and lo is None + + +def test_opening_range_high_low(): + bars = _bars([(10, 9.5), (10.5, 9.8), (10.3, 9.9), (10.1, 9.7), (10.6, 9.6), + (11.0, 10.0)]) + hi, lo, complete = opening_range(bars, orb_bars=5) + assert complete is True + assert hi == 10.6 # max high of first 5 + assert lo == 9.5 # min low of first 5 + + +# -- trigger book --------------------------------------------------------- + +def _cand(sym, gap=5.0, rvol=3.0, trig=10.0, stop=9.5, rng=0.05, complete=True): + return {"symbol": sym, "gap_pct": gap, "rvol": rvol, "trigger": trig, + "stop": stop, "range_pct": rng, "complete": complete} + + +def test_book_arms_when_complete_and_qualified(): + b = ArmedTriggerBook(gap_min=3, rvol_min=2) + b.arm([_cand("AAA")]) + assert b.triggers["AAA"].state == ARMED + + +def test_book_waiting_until_range_complete(): + b = ArmedTriggerBook() + b.arm([_cand("AAA", complete=False, trig=None, stop=None)]) + assert b.triggers["AAA"].state == WAITING + + +def test_book_weak_below_thresholds(): + b = ArmedTriggerBook(gap_min=5, rvol_min=3) + b.arm([_cand("AAA", gap=2, rvol=1)]) + assert b.triggers["AAA"].state == WEAK + + +def test_book_caps_at_max_armed(): + b = ArmedTriggerBook(max_armed=2) + b.arm([_cand(f"S{i}") for i in range(5)]) + assert len([t for t in b.triggers.values() if t.state != FIRED]) == 2 + + +def test_fires_only_when_price_crosses(): + b = ArmedTriggerBook(gap_min=3, rvol_min=2) + b.arm([_cand("AAA", trig=10.0)]) + b.update_price("AAA", 9.9) + assert b.fires() == [] + b.update_price("AAA", 10.01) + assert [t.symbol for t in b.fires()] == ["AAA"] + + +def test_fired_state_pinned_across_rearm(): + b = ArmedTriggerBook(max_armed=2, gap_min=3, rvol_min=2) + b.arm([_cand("AAA"), _cand("BBB")]) + b.mark_fired("AAA") + b.arm([_cand("CCC"), _cand("DDD")]) # new ranking without AAA + assert "AAA" in b.triggers and b.triggers["AAA"].state == FIRED + + +def test_mark_filled_promotes_held(): + b = ArmedTriggerBook(gap_min=3, rvol_min=2) + b.arm([_cand("AAA")]) + b.mark_filled({"AAA"}) + assert b.triggers["AAA"].state == FILLED + + +# -- live fire (submit_breakout_now) -------------------------------------- + +class _FakeClient: + def __init__(self, resp=None, account=None): + self.resp = resp or {"id": "o1", "status": "new", "filled_qty": "0"} + self.account = account or {"equity": "100000", "last_equity": "100000"} + self.last = None + self.closed = [] + + def submit_order(self, **kw): + self.last = kw + return self.resp + + def cancel_order(self, order_id): + pass + + def get_account(self): + return self.account + + def close_position(self, symbol): + self.closed.append(symbol) + return {"id": "c"} + + +def _svc(client): + store = EventStore(":memory:") + svc = TradingExecutionService( + store, + executor=AlpacaPaperExecutor(store, client=client), + settings=ExecutionSettings(auto_approve=True, max_daily_loss_pct=0.5), + session_id="t", + ) + return store, svc + + +def test_breakout_now_submits_marketable_limit(): + client = _FakeClient() + store, svc = _svc(client) + res = svc.submit_breakout_now("AAA", trigger=10.0, stop=9.5, last_price=10.0) + assert res["ok"] is True + assert client.last["order_type"] == "limit" + assert client.last["limit_price"] >= 10.0 # capped ABOVE the trigger + assert store.query_events(event_type="order_approved", limit=None) + + +def test_breakout_now_blocks_when_halted(): + # equity -60% vs prior close, breaker at 50% -> halt + client = _FakeClient(account={"equity": "40000", "last_equity": "100000"}) + store, svc = _svc(client) + res = svc.submit_breakout_now("AAA", 10.0, 9.5, last_price=10.0) + assert res["ok"] is False and res["skipped"] == "halted" + + +def test_breakout_now_dedups_second_attempt(): + client = _FakeClient() + store, svc = _svc(client) + svc.submit_breakout_now("AAA", 10.0, 9.5, last_price=10.0) + res2 = svc.submit_breakout_now("AAA", 10.0, 9.5, last_price=10.0) + assert res2["ok"] is False and res2["skipped"] == "already_active" + + +def test_breakout_now_rejects_bad_geometry(): + store, svc = _svc(_FakeClient()) + res = svc.submit_breakout_now("AAA", 10.0, 10.5, last_price=10.0) # stop > entry + assert res["ok"] is False and res["skipped"] == "bad_geometry" diff --git a/trading_execution.py b/trading_execution.py index 58fd11b..1682b47 100644 --- a/trading_execution.py +++ b/trading_execution.py @@ -71,6 +71,10 @@ class ExecutionSettings: # this fraction (e.g. 0.0 = any break below entry; 0.005 = 0.5% below). # Set to a negative number to disable price-break invalidation. entry_invalidate_pct: float = 0.0 + # live-trigger fast path (submit_breakout_now): how far above the trigger to + # cap the marketable limit so a breakout FILLS on a runner instead of + # resting forever at the trigger, while still bounding slippage. + trigger_slippage_pct: float = 0.004 @classmethod def from_env(cls, env: dict[str, str] | None = None) -> "ExecutionSettings": @@ -102,6 +106,9 @@ class ExecutionSettings: entry_invalidate_pct=float( values.get("TRADING_ENTRY_INVALIDATE_PCT", "0.0") ), + trigger_slippage_pct=float( + values.get("TRADING_TRIGGER_SLIP_PCT", "0.004") + ), ) @@ -432,6 +439,133 @@ class TradingExecutionService: "error": result.error, } + def submit_breakout_now( + self, + symbol: str, + trigger: float, + stop: float, + last_price: float | None = None, + reason: str = "orb_live_break", + ) -> dict: + """Fire a breakout entry immediately on a LIVE price cross. + + The disciplined-but-fast counterpart to the watcher->approval cadence: + used by the armed-trigger loop when price crosses a pre-computed + opening-range high. Runs the SAME risk gates as the slow path (daily-loss + breaker, max-concurrent, per-symbol dedup, 1%-risk sizing), but submits a + *marketable* limit (capped a hair above the trigger) so it fills on a + runner instead of resting at the level. Returns a result dict; ``skipped`` + explains a no-op (the symbol can simply try again next tick). + """ + if not self.settings.enabled: + return {"ok": False, "skipped": "disabled"} + if self._daily_loss_breach(): + return {"ok": False, "skipped": "halted"} + if self._open_position_count() >= self.settings.max_concurrent_positions: + return {"ok": False, "skipped": "max_positions"} + + # per-symbol dedup shared with the slow path: never double-enter a name + # that's already held, pending approval, or requested this session. + held = self._held_symbols() + pending = {row["symbol"] for row in query_approval_queue(self.store)} + if symbol in held or symbol in pending or symbol in self._requested_symbols: + return {"ok": False, "skipped": "already_active"} + + entry_ref = float(last_price or trigger) + stop_f = float(stop) + trigger_f = float(trigger) + if stop_f >= entry_ref or trigger_f <= 0: + return {"ok": False, "skipped": "bad_geometry"} + + sizing = calculate_position_size( + entry_ref, + stop_f, + equity=self.equity, + config=PositionSizingConfig( + risk_per_trade_pct=self.settings.risk_per_trade_pct, + default_equity=self.settings.default_equity, + ), + ) + if sizing.position_size <= 0: + return {"ok": False, "skipped": "zero_size"} + + # marketable limit: fill now (price is already at/above the trigger), but + # cap how far above we'll chase so a gap-through doesn't pay any price. + limit_price = round( + max(entry_ref, trigger_f) * (1.0 + self.settings.trigger_slippage_pct), 2 + ) + risk_per_share = entry_ref - stop_f + request = ExecutionRequest( + symbol=symbol, + side="buy", + quantity=sizing.position_size, + entry_price=limit_price, + stop_loss_price=stop_f, + take_profit_price=round( + entry_ref + self.settings.reward_multiple * risk_per_share, 2 + ), + order_type="limit", + ) + # audit trail mirrors the slow path: requested(auto) -> approved -> submit + self.store.emit( + OrderApprovalRequestedEvent( + timestamp=datetime.now(), + mode=self.mode, + correlation_id=self.session_id, + message=( + f"Live ORB break ({reason}): buy {request.quantity} {symbol} " + f"@ ~{entry_ref:.2f} (trigger {trigger_f:.2f}, stop {stop_f:.2f})" + ), + order_id=request.order_id, + symbol=symbol, + requested_by="orb_trigger", + approval_mode="auto", + execution_mode=self.trading_mode.execution_mode, + execution_request=request.to_payload(), + ) + ) + self.store.emit( + OrderApprovedEvent( + timestamp=datetime.now(), + mode=self.mode, + correlation_id=self.session_id, + message=f"Order {request.order_id} auto-approved (live ORB break)", + order_id=request.order_id, + symbol=symbol, + approved_by="orb_trigger", + approval_notes=reason, + ) + ) + self._requested_symbols.add(symbol) + result = self.executor.execute(request) + if ( + result.ok + and result.status + in {"new", "accepted", "pending_new", "held", "accepted_for_bidding"} + and request.entry_price + ): + self._armed[request.order_id] = { + "symbol": symbol, + "entry_price": float(request.entry_price), + "broker_order_id": result.broker_order_id, + "armed_at": self._now(), + "checks": 0, + } + logger.info( + "live ORB break %s qty=%s -> ok=%s status=%s", + symbol, request.quantity, result.ok, result.status, + ) + return { + "ok": result.ok, + "order_id": request.order_id, + "broker_order_id": result.broker_order_id, + "status": result.status, + "error": result.error, + "quantity": sizing.position_size, + "entry": limit_price, + "stop": stop_f, + } + def reject_order( self, order_id: str, rejected_by: str = "dashboard", reason: str = "manual" ) -> dict: