Phase 4: orchestrator + cycles auto-execute

Componente runtime/ che cabla core+clients+state+safety in un engine
autonomo notify-only: nessuna conferma manuale, ordini combo
piazzati direttamente quando le regole passano. 311 test pass,
copertura totale 94%, runtime/ 90%, mypy strict pulito, ruff clean.

Moduli:
- runtime/alert_manager.py: escalation tree
  LOW/MEDIUM/HIGH/CRITICAL → audit + Telegram + kill switch.
- runtime/dependencies.py: build_runtime() costruisce
  RuntimeContext con tutti i client MCP, repository, audit log,
  kill switch, alert manager.
- runtime/entry_cycle.py: flusso settimanale (snapshot parallelo
  spot/dvol/funding/macro/holdings/equity → validate_entry →
  compute_bias → options_chain → select_strikes →
  liquidity_gate → sizing_engine → combo_builder.build →
  place_combo_order → notify_position_opened).
- runtime/monitor_cycle.py: loop 12h con dvol_history per il
  return_4h, exit_decision.evaluate, close auto-execute.
- runtime/health_check.py: probe parallelo MCP + SQLite +
  environment match; 3 strikes consecutivi → kill switch HIGH.
- runtime/recovery.py: riconciliazione SQLite vs broker
  all'avvio; mismatch → kill switch CRITICAL.
- runtime/scheduler.py: AsyncIOScheduler builder con cron entry
  (lun 14:00), monitor (02/14), health (5min).
- runtime/orchestrator.py: façade boot() + run_entry/monitor/health
  + install_scheduler + run_forever, con env check vs strategy.

CLI:
- start: avvia engine bloccante (asyncio.run + scheduler).
- dry-run --cycle entry|monitor|health: esegue un singolo ciclo
  per debug/test in produzione.
- stop: documenta lo shutdown via SIGTERM al container.

Documentazione:
- docs/06-operational-flow.md riscritto per il modello
  notify-only auto-execute (no conferma manuale, no memory,
  no brain-bridge).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-04-28 00:03:45 +02:00
parent 466e63dc19
commit 42b0fbe1ab
20 changed files with 3715 additions and 131 deletions
+135
View File
@@ -0,0 +1,135 @@
"""Runtime dependency container.
Builds and wires together every long-lived object the engine needs:
HTTP clients, repository, audit log, kill switch, alert manager. The
:func:`build_runtime` factory returns a frozen :class:`RuntimeContext`
that the orchestrator and the cycle modules pass around — no global
state, no implicit singletons.
"""
from __future__ import annotations
from collections.abc import Callable
from dataclasses import dataclass
from datetime import UTC, datetime
from pathlib import Path
from cerbero_bite.clients._base import HttpToolClient
from cerbero_bite.clients.deribit import DeribitClient
from cerbero_bite.clients.hyperliquid import HyperliquidClient
from cerbero_bite.clients.macro import MacroClient
from cerbero_bite.clients.portfolio import PortfolioClient
from cerbero_bite.clients.sentiment import SentimentClient
from cerbero_bite.clients.telegram import TelegramClient
from cerbero_bite.config.mcp_endpoints import McpEndpoints
from cerbero_bite.config.schema import StrategyConfig
from cerbero_bite.runtime.alert_manager import AlertManager
from cerbero_bite.safety.audit_log import AuditLog
from cerbero_bite.safety.kill_switch import KillSwitch
from cerbero_bite.state import (
Repository,
connect,
run_migrations,
transaction,
)
__all__ = ["RuntimeContext", "build_runtime"]
@dataclass(frozen=True)
class RuntimeContext:
"""Bag of every wired object used by the runtime."""
cfg: StrategyConfig
db_path: Path
audit_path: Path
repository: Repository
audit_log: AuditLog
kill_switch: KillSwitch
alert_manager: AlertManager
deribit: DeribitClient
macro: MacroClient
sentiment: SentimentClient
hyperliquid: HyperliquidClient
portfolio: PortfolioClient
telegram: TelegramClient
clock: Callable[[], datetime]
def _utc_now() -> datetime:
return datetime.now(UTC)
def build_runtime(
*,
cfg: StrategyConfig,
endpoints: McpEndpoints,
token: str,
db_path: Path | str,
audit_path: Path | str,
timeout_s: float = 8.0,
retry_max: int = 3,
clock: Callable[[], datetime] | None = None,
) -> RuntimeContext:
"""Wire every dependency the runtime needs.
The SQLite database is migrated and the system_state singleton is
initialised eagerly so the orchestrator can assume both are
present.
"""
db_path = Path(db_path)
audit_path = Path(audit_path)
clk = clock or _utc_now
repository = Repository()
conn = connect(db_path)
try:
run_migrations(conn)
with transaction(conn):
repository.init_system_state(
conn, config_version=cfg.config_version, now=clk()
)
finally:
conn.close()
audit_log = AuditLog(audit_path)
kill_switch = KillSwitch(
connection_factory=lambda: connect(db_path),
repository=repository,
audit_log=audit_log,
clock=clk,
)
def _client(service: str) -> HttpToolClient:
return HttpToolClient(
service=service,
base_url=endpoints.for_service(service),
token=token,
timeout_s=timeout_s,
retry_max=retry_max,
)
telegram = TelegramClient(_client("telegram"))
alert_manager = AlertManager(
telegram=telegram, audit_log=audit_log, kill_switch=kill_switch
)
return RuntimeContext(
cfg=cfg,
db_path=db_path,
audit_path=audit_path,
repository=repository,
audit_log=audit_log,
kill_switch=kill_switch,
alert_manager=alert_manager,
deribit=DeribitClient(_client("deribit")),
macro=MacroClient(_client("macro")),
sentiment=SentimentClient(_client("sentiment")),
hyperliquid=HyperliquidClient(_client("hyperliquid")),
portfolio=PortfolioClient(_client("portfolio")),
telegram=telegram,
clock=clk,
)