""" CRE v1.0 — entrypoint (spec §8, §12). Boot sequence: 1. restore the DB snapshot from the HF bucket (if configured) [sync.restore] 2. open + migrate the SQLite DB, snapshot the config version 3. start the background engine (data workers + signal engine + monitor + sync) on a dedicated asyncio loop in a worker thread 4. launch the Gradio dashboard on the main thread (HF reads `app_file: app.py`) The workers run in their own thread/loop so Gradio's blocking launch() doesn't starve them. A stop Event + atexit hook flush a final DB snapshot on shutdown. Step 4 swaps the placeholder UI for ui/dashboard.py (imported lazily so the app still boots if the dashboard module isn't present yet). """ from __future__ import annotations import asyncio import atexit import threading import time import gradio as gr import config import sync from store import db from exchange.base import get_client import workers import signals_worker _stop = asyncio.Event() _loop: asyncio.AbstractEventLoop | None = None _client = None _state: workers.UniverseState | None = None def _boot_db() -> None: sync.restore_on_boot() # pull last snapshot before opening the DB db.init() db.save_config_version(config.CONFIG_VERSION, config.snapshot()) print(f"[boot] DB ready @ {config.DB_PATH} · config v{config.CONFIG_VERSION} · " f"exchange={config.EXCHANGE} · universe={config.UNIVERSE_MODE}", flush=True) async def _run_engine() -> None: global _client, _state _client = get_client(config.EXCHANGE, config.WATCHLIST, config.HTTP_TIMEOUT_SEC) _state, data_tasks = await workers.start(_client, _stop) sig_tasks = signals_worker.start(_client, _state, _stop) sync_task = [asyncio.create_task(sync.sync_worker(_stop), name="sync_worker")] tasks = data_tasks + sig_tasks + sync_task print(f"[boot] {len(tasks)} background tasks started", flush=True) await _stop.wait() for t in tasks: t.cancel() await asyncio.gather(*tasks, return_exceptions=True) if _client: await _client.aclose() def _engine_thread() -> None: global _loop _loop = asyncio.new_event_loop() asyncio.set_event_loop(_loop) _loop.run_until_complete(_run_engine()) def _shutdown() -> None: if _loop and not _stop.is_set(): _loop.call_soon_threadsafe(_stop.set) time.sleep(2) # give the final sync push a moment # ── placeholder UI (replaced by ui/dashboard.py in Step 4) ─────────────────── def _health_text() -> str: try: snaps = db.latest_snapshots() sigs = db.recent_signals(5) uni = len(_state.symbols) if _state else 0 lines = [ f"### CRE v{config.APP_VERSION} — running", f"- Universe: **{uni}** symbols ({config.UNIVERSE_MODE})", f"- Market snapshots: **{len(snaps)}** symbols tracked", f"- Signals logged: **{len(db.recent_signals(100000))}**", f"- Alerts: **{'on' if config.ALERTS_ENABLED else 'off (no Telegram creds)'}**", f"- Persistence: **{'HF bucket' if sync.ENABLED else 'ephemeral'}**", ] if sigs: lines.append("\n**Recent signals:**") for s in sigs: lines.append(f"- {s['symbol']} {s['direction']} · {s['tier']} · " f"conf {s['score_total']} · {s['state']}") return "\n".join(lines) except Exception as e: return f"booting… ({type(e).__name__})" def _build_placeholder(): with gr.Blocks(title="CRE v1.0") as demo: gr.Markdown("# 🚀 Confluence Reversal Engine v1.0") status = gr.Markdown(_health_text()) timer = gr.Timer(5.0) timer.tick(_health_text, outputs=status) return demo def main() -> None: _boot_db() threading.Thread(target=_engine_thread, daemon=True, name="cre-engine").start() atexit.register(_shutdown) # Step 4: replace with ui.dashboard.build() try: from ui.dashboard import build as build_ui demo = build_ui(lambda: _state) except Exception: demo = _build_placeholder() demo.queue().launch(server_name="0.0.0.0", server_port=7860, show_api=False) if __name__ == "__main__": main()