"""In-Space scheduler — the Space triggers its own monthly rebalance (no GitHub or outside cron needed). A background thread wakes every 15 minutes. Each tick it rebuilds the ranking if it is older than 20 hours, and on weekdays between 10:00 and 15:30 New York time it calls the same guarded rebalance as POST /api/rebalance: that trades only while the market is open, on one of the first 5 trading days of a month (or the very first run), once a month, on data at most 5 days old — every other tick is a cheap no-op. A lock makes the scheduler and the API never run a rebalance at the same time; Alpaca's order history (orders tagged "qt3-") is the only state, so a restart cannot cause a second trade. The thread needs the Space to be awake (see README: keep-awake). """ from __future__ import annotations import os import threading import time from datetime import datetime from datetime import time as dtime from . import config, ranking, rebalance from .broker import Alpaca FROM, TO = dtime(10, 0), dtime(15, 30) # New York time; trades after the opening auction settles STATE = {"enabled": config.AUTO_REBALANCE, "running": False, "interval_min": None, "last_tick": None, "last_attempt": None, "last_result": None, "last_error": None} _lock = threading.Lock() def due(now: datetime) -> bool: now = now.astimezone(rebalance.NY) return now.weekday() < 5 and FROM <= now.time() <= TO def run_once(force: bool = False, alpaca: Alpaca | None = None) -> dict: """One guarded rebalance attempt (shared by the scheduler and the API).""" if not _lock.acquire(blocking=False): return {"executed": False, "reasons": ["a rebalance is already running"]} try: r = ranking.refresh() a = alpaca or Alpaca() chk = rebalance.check(a, r, None, force) if not chk["ok"]: return {"executed": False, "reasons": chk["reasons"]} p = rebalance.build_plan(a, r) res = rebalance.execute(a, p) return {"executed": True, "plan": p, "results": res} finally: _lock.release() def _tick() -> None: now = datetime.now(rebalance.NY) STATE["last_tick"] = now.isoformat(timespec="seconds") if config.NDL_KEY: ranking.refresh() # no-op unless older than RANKING_MAX_AGE_H if config.AUTO_REBALANCE and due(now): out = run_once() STATE["last_attempt"] = now.isoformat(timespec="seconds") STATE["last_result"] = ({"executed": True, "orders": [f"{x['side']} {x['symbol']} {x.get('status')}" for x in out.get("results", [])]} if out.get("executed") else {"executed": False, "reasons": out.get("reasons")}) def _loop(interval_s: float) -> None: while True: try: _tick() STATE["last_error"] = None except Exception as e: # noqa: BLE001 — keep the thread alive; the next tick retries STATE["last_error"] = f"{type(e).__name__}: {e}"[:300] time.sleep(interval_s) def start(interval_s: float = 900) -> bool: configured = config.NDL_KEY and config.ALPACA_KEY and config.ALPACA_SECRET if STATE["running"] or not configured or os.getenv("QT3_DISABLE_SCHEDULER"): return False threading.Thread(target=_loop, args=(interval_s,), daemon=True, name="updraft-scheduler").start() STATE.update(running=True, interval_min=interval_s / 60) return True