Sistema dedicato di raccolta dati per scegliere le soglie dei filtri
sui percentili reali invece di valori a istinto.
Nuovi componenti:
* state/migrations/0003_market_snapshots.sql — tabella + index, PK
composta (timestamp, asset). Ogni colonna numerica è NULL-able per
preservare la continuità della serie quando un singolo MCP fallisce.
* state/models.py — MarketSnapshotRecord Pydantic.
* state/repository.py — record_market_snapshot, list_market_snapshots,
_row_to_market_snapshot.
* runtime/market_snapshot_cycle.py — collettore best-effort che chiama
spot/dvol/realized_vol/dealer_gamma/funding_perp/funding_cross/
liquidation_heatmap/macro per ogni asset; raccoglie gli errori in
fetch_errors_json e segna fetch_ok=false ma persiste comunque la
riga.
* clients/deribit.py — generalizzati dealer_gamma_profile(currency),
realized_vol(currency), spot_perp_price(asset). dealer_gamma_profile_eth
resta come alias per la chiamata dell'entry cycle.
* runtime/orchestrator.py — nuovo job APScheduler `market_snapshot`
cron */15 con assets configurabili (default ETH+BTC); il consumer
manual_actions ora dispatcha anche kind=run_cycle cycle=market_snapshot
per la GUI.
* gui/data_layer.py — load_market_snapshots, enqueue_run_cycle accetta
market_snapshot; tipo MarketSnapshotRecord esposto.
* gui/pages/6_📐_Calibrazione.py — selezione asset+finestra, conteggio
fetch_ok, per ogni metrica: istogramma, soglia da strategy.yaml come
vline rossa, percentili P5/P10/P25/P50/P75/P90/P95, % di tick che la
soglia avrebbe filtrato.
* gui/pages/1_📊_Status.py — bottone "📐 Forza snapshot" (4° del pannello
Forza ciclo) per popolare la tabella senza aspettare il cron.
5 nuovi test sul collector (happy, fault tolerance, asset switch,
macro fail, empty assets); test_orchestrator job set aggiornato.
368/368 tests pass; ruff clean; mypy strict src clean.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Localizzazione italiana di tutte le pagine (Stato, Audit, Equity,
Storico, Posizione) e della home; date relative ("5s fa", "12m fa").
* Logo Cerbero (cane a tre teste) in src/cerbero_bite/gui/assets/
cerbero_logo.png — sostituisce l'emoji 🐺 (lupo, semanticamente
errata) sia come favicon (`page_icon`) sia in sidebar e header.
* Caricamento automatico di `.env` dal CWD all'avvio della CLI (skip
sotto pytest tramite PYTEST_CURRENT_TEST), evitando di doversi
esportare manualmente le 4 URL MCP. Aggiunto python-dotenv come
dipendenza, `.env.example` committato come template, `.env` resta
ignorato da git.
* Pagina Stato: nuovo pannello "Saldi exchange" che fa fetch live
via gateway MCP (Deribit USDC + USDT, Hyperliquid USDC + opzionale
USDT spot) con cache TTL 60s e bottone refresh; tile riassuntivi
totale USD / EUR / cambio.
* Pagina Stato: nuovo pannello "Forza ciclo" con tre bottoni
(entry/monitor/health) che accodano azioni `run_cycle` nella tabella
manual_actions; il consumer dell'engine — quando in esecuzione —
dispatcha al `Orchestrator.run_*` corrispondente.
* manual_actions: nuovo `kind="run_cycle"` nello schema
ManualAction; consumer accetta dict di cycle_runners che
l'orchestrator popola in install_scheduler. 3 nuovi test (dispatch
entry, ciclo sconosciuto, fallback senza runner).
* gui/live_data.py — modulo dedicato al fetch MCP dalla GUI
(relax controllato della regola "no MCP from GUI" solo per i saldi,
non per i dati di trading).
363/363 tests pass; ruff clean; mypy strict src clean.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Wires the GUI's first write path through the manual_actions queue:
* runtime/manual_actions_consumer.py — drains the queue and
dispatches arm_kill / disarm_kill via KillSwitch (preserving the
audit chain). Unsupported kinds (force_close, approve/reject_proposal)
are marked result="not_supported" so they don't sit forever.
* runtime/orchestrator.py — adds a `manual_actions` job at */1 cron
to the canonical scheduler manifest.
* gui/data_layer.py — write helpers enqueue_arm_kill /
enqueue_disarm_kill (the only write path the GUI uses) plus
load_pending_manual_actions for the pending strip.
* gui/pages/1_📊_Status.py — kill-switch arm/disarm panel with typed
confirmation ("yes I am sure") + reason field; pending-actions table
rendered when the queue is non-empty.
End-to-end smoke against the testnet state.sqlite:
GUI enqueue → consumer dispatch → KillSwitch transition → audit
chain hash linkage holds, "source":"manual_gui" recorded.
7 new unit tests for the consumer (arm, disarm, drain, unsupported,
default-reason, KillSwitchError handling, empty queue); 360/360 pass.
ruff clean; mypy strict src clean.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Each bot now manages its own notification + portfolio aggregation:
* TelegramClient calls the public Bot API directly via httpx, reading
CERBERO_BITE_TELEGRAM_BOT_TOKEN / CERBERO_BITE_TELEGRAM_CHAT_ID from
env. No credentials → silent disabled mode.
* PortfolioClient composes DeribitClient + HyperliquidClient + the new
MacroClient.get_asset_price/eur_usd_rate to expose equity (EUR) and
per-asset exposure as the bot's own slice (no cross-bot view).
* mcp-telegram and mcp-portfolio removed from MCP_SERVICES / McpEndpoints
and the cerbero-bite ping CLI; health_check no longer probes portfolio.
Docs (02/04/06/07) and docker-compose updated to reflect the new
architecture.
353/353 tests pass; ruff clean; mypy src clean.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Integra due nuovi filtri dal pacchetto quant indicators rilasciato in
Cerbero_mcp (commit a13e3fe). 335 test pass, mypy strict pulito,
ruff clean.
Filtri (§2.8 — nuovo):
- dealer-gamma: blocca entry quando total_net_dealer_gamma <
dealer_gamma_min (default 0). Long-gamma regime favorisce credit
spread (vol-suppressing dealer flow); short-gamma flow lo amplifica
ed è da evitare.
- liquidation-heatmap: blocca entry quando il segnale euristico di
cerbero-sentiment riporta long o short squeeze risk = "high"
(cluster di liquidations imminenti entro 24h).
Entrambi sono best-effort: se il tool MCP fallisce o restituisce
dati anomali l'entry_cycle popola EntryContext con None e
validate_entry salta il gate per non bloccare entry su problemi
infrastrutturali.
Wrapper:
- DeribitClient.dealer_gamma_profile_eth → DealerGammaSnapshot.
- SentimentClient.liquidation_heatmap → LiquidationHeatmap con
property has_high_squeeze_risk.
Schema:
- EntryConfig.dealer_gamma_min, dealer_gamma_filter_enabled,
liquidation_filter_enabled.
- EntryContext.dealer_net_gamma, liquidation_squeeze_risk_high
opzionali.
- strategy.yaml: nuovi campi documentati con commento + hash
ricalcolato (4c2be4c5...).
Documentazione:
- docs/04-mcp-integration.md riscritto al modello attuale (HTTP
REST, no mcp SDK, no memory/brain-bridge, place_combo_order
documentato, environment_info al boot).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Sei interventi MEDIA priorità sul sistema. 323 test pass, mypy strict
pulito, ruff clean.
1. Docker HEALTHCHECK + cerbero-bite healthcheck:
- nuovo subcommand che esce 0 se kill_switch=0 e last_health_check
entro --max-staleness-s (default 600s);
- HEALTHCHECK direttiva nel Dockerfile (60s interval, 5s timeout,
start_period 120s, retries 3);
- healthcheck definition nel docker-compose.yml.
2. Audit hash chain anti-truncation:
- migration 0002: nuova colonna system_state.last_audit_hash;
- AuditLog accetta callback on_append, dependencies.py la wire al
repository.set_last_audit_hash;
- Orchestrator.boot verifica che il tail file matcha l'anchor
persistito; mismatch → kill switch CRITICAL.
3. return_4h bootstrap da deribit get_historical:
- quando dvol_history è vuoto _fetch_return_4h cade su
deribit.historical_close (1h candle 4h fa);
- alert LOW se anche il fallback fallisce.
4. execution.environment + execution.eur_to_usd in strategy.yaml:
- ExecutionConfig promosso a typed schema con i due campi
consumati al boot;
- CLI start preferisce i valori da config; CLI flag overridano
solo quando differenti dai default.
5. Cycle correlation ID:
- structlog.contextvars.bind_contextvars in run_entry/run_monitor/
run_health propaga cycle_id e cycle nei log strutturati.
6. SIGTERM/SIGINT clean shutdown:
- run_forever installa loop.add_signal_handler per SIGTERM e
SIGINT; il segnale set()ta un asyncio.Event che termina il
blocco principale, scheduler.shutdown e ctx.aclose finalizzano.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Sei interventi mirati sui rischi operativi rilevati nell'audit
post-Fase 4. 317 test pass, mypy strict pulito, ruff clean.
1. status CLI: legge SQLite reale e mostra kill_switch, posizioni
aperte, environment, config_version, last_health_check, started_at.
Sostituisce il placeholder "phase 0 skeleton".
2. Lock file single-instance: runtime/lockfile.py acquisisce
data/.lockfile via fcntl.flock al boot di run_forever; un secondo
container fallisce subito con LockError.
3. Backup orario nello scheduler: nuovo job APScheduler 0 * * * *
chiama scripts.backup.backup_database + prune_backups.
4. config_hash enforce su start: il CLI start verifica l'integrità
del file (enforce_hash=True). Mismatch → exit 1 prima di toccare
stato. dry-run resta enforce_hash=False per debug.
5. Connection pooling MCP: RuntimeContext espone un httpx.AsyncClient
long-lived condiviso da tutti i wrapper (limits 20/10
connections/keepalive). aclose() chiamato in run_forever finale.
6. Bias direzionale reale: deribit.historical_close +
deribit.adx_14 popolano TrendContext con spot a 30 giorni e
ADX(14) effettivi. Sblocca bull_put e bear_call. Quando i dati
storici mancano l'engine emette alert MEDIUM e cade su no_entry
in modo deterministico.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Wrapper async tipizzati sui sei servizi MCP HTTP che Cerbero Bite
consuma in autonomia. 277 test pass, copertura clients 93%, mypy
strict pulito, ruff clean.
Base layer:
- clients/_base.py: HttpToolClient con httpx + tenacity (retry
esponenziale 3x, timeout 8s, mapping HTTP→eccezioni tipizzate).
- clients/_exceptions.py: McpAuthError, McpServerError, McpToolError,
McpDataAnomalyError, McpNotFoundError, McpTimeoutError.
- config/mcp_endpoints.py: risoluzione URL via Docker DNS
(mcp-deribit:9011, ...) con override per servizio via env var;
caricamento bearer token da secrets/core.token o
CERBERO_BITE_CORE_TOKEN_FILE.
Wrapper:
- clients/macro.py: next_high_severity_within() per filtro entry §2.5.
- clients/sentiment.py: funding_cross_median_annualized() con
annualizzazione per period nativo per exchange (Binance/Bybit/OKX
1095, Hyperliquid 8760).
- clients/hyperliquid.py: funding_rate_annualized() per filtro §2.6.
- clients/portfolio.py: total_equity_eur(), asset_pct_of_portfolio()
per sizing engine + filtro §2.7.
- clients/telegram.py: notify-only (no callback queue, no
conferme — Bite auto-execute).
- clients/deribit.py: environment_info, index_price_eth,
latest_dvol, options_chain, get_tickers, orderbook_depth_top3,
get_account_summary, get_positions, place_combo_order (combo
atomico), cancel_order.
CLI:
- cerbero-bite ping: health-check parallelo di tutti gli MCP con
tabella rich (OK/FAIL/SKIPPED).
Docker:
- Dockerfile multi-stage Python 3.13 + uv, user non-root.
- docker-compose.yml con rete external "cerbero-suite", secret
core_token montato a /run/secrets/core_token, env per ogni MCP.
- secrets/README.md documenta il setup del token.
Documentazione di intervento:
- docs/12-mcp-deribit-changes.md: spec delle modifiche apportate
al server mcp-deribit (place_combo_order + override testnet via
DERIBIT_TESTNET).
Dipendenze:
- aggiunto pytest-httpx per i test HTTP.
- rimosso mcp>=1.0 (non usiamo l'SDK MCP, parliamo via HTTP REST).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Implementa i sette algoritmi puri di docs/03-algorithms.md con
disciplina TDD: 112 test, copertura statement+branch al 100% su
core/ e config/, mypy --strict pulito, ruff pulito.
Moduli:
- config/schema.py: StrategyConfig Pydantic v2 con validatori di
consistenza (kelly, delta, OTM, spread width, profit/stop).
- core/types.py: OptionQuote e OptionLeg condivisi.
- core/entry_validator.py: validate_entry (accumula motivi) e
compute_bias (bull_put/bear_call/iron_condor/None).
- core/liquidity_gate.py: check OI/volume/spread/depth + slippage
stimato in % del credito.
- core/sizing_engine.py: Quarter Kelly con cap 200/1000 EUR e
bande DVOL.
- core/combo_builder.py: select_strikes (DTE/OTM/delta/width/credit)
e build (ComboProposal con credit/max_loss/breakeven).
- core/greeks_aggregator.py: somma firmata BUY/SELL, theta in USD.
- core/exit_decision.py: 6 trigger ordinati con eccezione skip-time
vicino a profit (mark in (50%,70%] credito).
- core/kelly_recalibration.py: full/quarter Kelly, confidence per
sample size, blend medio in fascia 30-99 trade.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>