File size: 4,305 Bytes
c6262df
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
"""
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()