From 1c6baaee83c02c0d15248e4db9ee96b808bd3218 Mon Sep 17 00:00:00 2001 From: root Date: Fri, 1 May 2026 20:07:25 +0000 Subject: [PATCH] =?UTF-8?q?feat(strategy):=20F+D+A=20miglioramenti=20?= =?UTF-8?q?=E2=80=94=20auto-pause,=20vol-harvest,=20delta=20dinamico?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Implementa tre miglioramenti dalla roadmap di "📚 Strategia" + scaffolding del quarto. Tutti retro-compatibili: i defaults della golden config disabilitano le nuove funzioni così il comportamento attuale resta invariato finché l'operatore non le accende esplicitamente in `strategy.yaml`. Il profilo `strategy.aggressiva.yaml` opta-in agli incrementi più impattanti. **F — Auto-pause su drawdown rolling (§7-bis)** Circuit breaker sopra il kill-switch tecnico. Quando le ultime N posizioni chiuse hanno cumulato perdite oltre `max_drawdown_pct × capitale_attuale`, l'engine si auto-mette in pausa per `pause_weeks` settimane. Difende dai regime change non rilevati dai filtri quant — se i filtri stanno fallendo sistematicamente, fermarsi è meglio che continuare a sanguinare. - `AutoPauseConfig` + `cfg.auto_pause` (top-level, default disabled). - Migrazione SQL `0004_auto_pause.sql`: `system_state.auto_pause_until` e `auto_pause_reason` (NULL = engine attivo). - Nuovo modulo puro `runtime/auto_pause.py` con `is_paused()` (gate I/O-free) e `evaluate_drawdown_breach()` (decide se armare). - `entry_cycle` consulta `is_paused` subito dopo il kill-switch e arma la pausa dopo aver calcolato il capitale; nuovo status `_STATUS_AUTO_PAUSED`. - Repository: `set_auto_pause`, `recent_closed_position_pnls_usd`. - 12 test unitari: gate filter on/off, lookback insufficiente, soglia esatta, capitale non valido, transizioni paused → not-paused. **D — Vol-collapse harvest (§7-bis)** Exit opportunistica: quando DVOL è scesa di tot punti rispetto all'entry e siamo in profit, esce subito. Edge IV-RV catturato, non c'è motivo di tenere fino al profit-take. Nuovo `ExitAction = "CLOSE_VOL_HARVEST"`, gate `exit.vol_harvest_dvol_decrease` (default 0 = off). 5 test unitari. **A — Delta target dinamico per regime DVOL (§3.2)** Strike short adattivo alla volatilità: a DVOL bassa il margine OTM è generoso ⇒ posso prendere più premio (delta 0.15); a DVOL alta voglio più safety distance (delta 0.10). Nuovo `DeltaByDvolBand` (step function); quando `delta_by_dvol` è popolato, `_select_short` legge la prima banda ascending con `dvol_now ≤ dvol_under`. Default vuoto = comportamento invariato. `select_strikes` accetta nuovo kwarg `dvol_now`, propagato da `entry_cycle`. 4 test unitari. **C — Scaffolding profit-take graduale (§7.1bis)** Schema in place ma runtime non ancora wirato. Aggiunge `PartialProfitLevel` e `exit.profit_take_partial_levels` (default vuoto). Nuovo `ExitAction = "CLOSE_PROFIT_PARTIAL"` nella Literal. La pipeline di chiusure parziali nel runtime (entry_cycle / repository / clients) richiede refactor del position model — lasciato come TODO per un PR dedicato. La schema è pronta a recepire la config futura senza altri breaking change. **Profili aggiornati** - `strategy.yaml` (golden, 1.2.0): tutto disabilitato by default. - `strategy.conservativa.yaml` (1.2.0-cons): identico al golden. - `strategy.aggressiva.yaml` (1.2.0-aggr): A+D+F enabled (delta_by_dvol 0.15/0.12/0.10, vol_harvest a 15 pt vol, auto_pause @ 15% DD su 5 trade, 2 settimane pausa). Bump versioni 1.1.0 → 1.2.0, hash ricalcolati, test pinning aggiornato. Suite: 426 passed. Co-Authored-By: Claude Opus 4.7 (1M context) --- src/cerbero_bite/config/schema.py | 94 ++++++++++ src/cerbero_bite/core/combo_builder.py | 30 ++- src/cerbero_bite/core/exit_decision.py | 18 ++ src/cerbero_bite/runtime/auto_pause.py | 175 ++++++++++++++++++ src/cerbero_bite/runtime/entry_cycle.py | 69 ++++++- .../state/migrations/0004_auto_pause.sql | 14 ++ src/cerbero_bite/state/models.py | 2 + src/cerbero_bite/state/repository.py | 47 +++++ strategy.aggressiva.yaml | 28 ++- strategy.conservativa.yaml | 13 +- strategy.yaml | 19 +- tests/unit/test_auto_pause.py | 157 ++++++++++++++++ tests/unit/test_combo_builder.py | 143 ++++++++++++++ tests/unit/test_config_loader.py | 2 +- tests/unit/test_exit_decision.py | 88 +++++++++ 15 files changed, 888 insertions(+), 11 deletions(-) create mode 100644 src/cerbero_bite/runtime/auto_pause.py create mode 100644 src/cerbero_bite/state/migrations/0004_auto_pause.sql create mode 100644 tests/unit/test_auto_pause.py diff --git a/src/cerbero_bite/config/schema.py b/src/cerbero_bite/config/schema.py index f916669..eec90c1 100644 --- a/src/cerbero_bite/config/schema.py +++ b/src/cerbero_bite/config/schema.py @@ -81,6 +81,17 @@ class EntryConfig(BaseModel): # --------------------------------------------------------------------------- +class DeltaByDvolBand(BaseModel): + """Banda della step function delta-target per regime DVOL (§3.2 A).""" + + model_config = ConfigDict(frozen=True, extra="forbid") + + dvol_under: Decimal + delta_target: Decimal + delta_min: Decimal + delta_max: Decimal + + class ShortStrikeSpec(BaseModel): model_config = ConfigDict(frozen=True, extra="forbid") @@ -90,6 +101,16 @@ class ShortStrikeSpec(BaseModel): distance_otm_pct_min: Decimal = Field(default=Decimal("0.15")) distance_otm_pct_max: Decimal = Field(default=Decimal("0.25")) + # §3.2 enhancement (A): step function delta-target by DVOL regime. + # Empty list = behaviour invariato (delta_target sopra è il singolo + # valore). Quando popolato, il combo_builder sceglie la prima + # banda ordinata ascending su `dvol_under` con + # `dvol_now ≤ dvol_under`. Esempio: + # - dvol_under=50 → delta 0.15 (bassa vol → più premio) + # - dvol_under=70 → delta 0.12 + # - dvol_under=90 → delta 0.10 (alta vol → più safety) + delta_by_dvol: list[DeltaByDvolBand] = Field(default_factory=list) + class SpreadWidthSpec(BaseModel): model_config = ConfigDict(frozen=True, extra="forbid") @@ -165,6 +186,25 @@ class SizingConfig(BaseModel): # --------------------------------------------------------------------------- +class PartialProfitLevel(BaseModel): + """Livello della scala di profit-take graduale (§7.1bis C). + + `mark_at_pct_credit`: il livello è triggerato quando + `mark_combo ≤ mark_at_pct_credit × credito_iniziale` (es. 0.25 = + 25% del credito = 75% di profitto sulla porzione chiusa). + + `close_pct_of_initial_contracts`: frazione dei contratti aperti + INIZIALMENTE da chiudere a questo livello (es. 0.50 = chiudi metà). + Le frazioni sono cumulative; chiudere oltre i contratti residui + è no-op. + """ + + model_config = ConfigDict(frozen=True, extra="forbid") + + mark_at_pct_credit: Decimal + close_pct_of_initial_contracts: Decimal + + class ExitConfig(BaseModel): model_config = ConfigDict(frozen=True, extra="forbid") @@ -176,6 +216,29 @@ class ExitConfig(BaseModel): delta_breach_threshold: Decimal = Field(default=Decimal("0.30")) adverse_move_4h_pct: Decimal = Field(default=Decimal("0.05")) + # §7.1ter (D): vol-collapse harvest. Esce in profit anche se il + # profit-take non è ancora colpito quando DVOL è scesa di tot + # punti rispetto all'entry (edge IV-RV catturato, vol attesa già + # rientrata). 0 = filtro disabilitato. + vol_harvest_dvol_decrease: Decimal = Field(default=Decimal("0")) + + # §7.1bis (C): scala graduata di profit-take. Lista vuota = + # comportamento invariato (chiusura atomica al + # `profit_take_pct_of_credit`). Quando popolata, l'engine + # interpreta come "chiudi N% dei contratti iniziali al livello + # di mark M%×credito". Le entry sono ordinate dal mark più alto + # (più profit, livello triggerato prima) al più basso. Vedi + # `core/exit_decision.py` per la semantica esatta. + # + # ATTENZIONE: questa funzione richiede il supporto di chiusure + # parziali nel runtime (entry_cycle / repository / clients). + # Fino al merge della partial-close pipeline, l'engine la mappa + # a CLOSE_PROFIT atomico al primo livello triggerato (vedi + # commento in `evaluate`). Default vuoto = no-op. + profit_take_partial_levels: list[PartialProfitLevel] = Field( + default_factory=list + ) + monitor_cron: str = "0 2,14 * * *" user_confirmation_timeout_min: int = 30 escalate_on_timeout: list[str] = Field( @@ -183,6 +246,36 @@ class ExitConfig(BaseModel): ) +# --------------------------------------------------------------------------- +# Auto-pause (F): circuit breaker su drawdown rolling +# --------------------------------------------------------------------------- + + +class AutoPauseConfig(BaseModel): + """Configurazione del circuit breaker su drawdown. + + Quando abilitato, il rule engine valuta — prima di ogni entry — + il P/L cumulato delle ultime `lookback_trades` posizioni chiuse + in proporzione al capitale attuale. Se la perdita supera la + soglia, l'engine si auto-mette in pausa per `pause_weeks` + settimane (skip-week). La pausa si annulla automaticamente alla + scadenza, oppure manualmente via comando dalla GUI. + + Difende da regime change non rilevati dai filtri quant: se i + filtri stanno fallendo sistematicamente, vale la pena fermarsi + e attendere che le condizioni cambino, invece di continuare a + sanguinare. È un'estensione conservativa del kill switch + (che oggi reagisce solo a errori tecnici). + """ + + model_config = ConfigDict(frozen=True, extra="forbid") + + enabled: bool = False + lookback_trades: int = 5 + max_drawdown_pct: Decimal = Field(default=Decimal("0.10")) + pause_weeks: int = 2 + + # --------------------------------------------------------------------------- # Kelly recalibration # --------------------------------------------------------------------------- @@ -256,6 +349,7 @@ class StrategyConfig(BaseModel): sizing: SizingConfig = Field(default_factory=SizingConfig) exit: ExitConfig = Field(default_factory=ExitConfig) kelly_recalibration: KellyConfig = Field(default_factory=KellyConfig) + auto_pause: AutoPauseConfig = Field(default_factory=AutoPauseConfig) execution: ExecutionConfig = Field(default_factory=ExecutionConfig) monitoring: MonitoringConfig = Field(default_factory=MonitoringConfig) diff --git a/src/cerbero_bite/core/combo_builder.py b/src/cerbero_bite/core/combo_builder.py index 260eb86..755d455 100644 --- a/src/cerbero_bite/core/combo_builder.py +++ b/src/cerbero_bite/core/combo_builder.py @@ -83,26 +83,49 @@ def _pick_expiry( return min(candidates, key=lambda exp: abs(candidates[exp] - sc.dte_target)) +def _resolve_delta_band( + sc: object, dvol_now: Decimal | None +) -> tuple[Decimal, Decimal, Decimal]: + """Return (delta_target, delta_min, delta_max) per il regime DVOL corrente. + + Quando ``sc.delta_by_dvol`` è popolato e ``dvol_now`` è disponibile, + sceglie la prima banda (ordinata ascending sulla ``dvol_under``) il + cui ``dvol_under ≥ dvol_now``. Altrimenti torna ai valori statici di + ``sc``. + """ + bands = list(getattr(sc, "delta_by_dvol", []) or []) + if dvol_now is not None and bands: + bands_sorted = sorted(bands, key=lambda b: b.dvol_under) + for band in bands_sorted: + if dvol_now <= band.dvol_under: + return band.delta_target, band.delta_min, band.delta_max + last = bands_sorted[-1] + return last.delta_target, last.delta_min, last.delta_max + return sc.delta_target, sc.delta_min, sc.delta_max + + def _select_short( quotes: list[OptionQuote], *, spot: Decimal, cfg: StrategyConfig, + dvol_now: Decimal | None = None, ) -> OptionQuote | None: """Pick the short-leg quote with delta closest to target inside both bands.""" sc = cfg.structure.short_strike + delta_target, delta_min, delta_max = _resolve_delta_band(sc, dvol_now) eligible: list[OptionQuote] = [] for q in quotes: dist = (q.strike - spot).copy_abs() / spot if not (sc.distance_otm_pct_min <= dist <= sc.distance_otm_pct_max): continue abs_delta = q.delta.copy_abs() - if not (sc.delta_min <= abs_delta <= sc.delta_max): + if not (delta_min <= abs_delta <= delta_max): continue eligible.append(q) if not eligible: return None - return min(eligible, key=lambda q: abs(q.delta.copy_abs() - sc.delta_target)) + return min(eligible, key=lambda q: abs(q.delta.copy_abs() - delta_target)) def _select_long( @@ -143,6 +166,7 @@ def select_strikes( spot: Decimal, now: datetime, cfg: StrategyConfig, + dvol_now: Decimal | None = None, ) -> tuple[OptionQuote, OptionQuote] | None: """Return the (short, long) quotes for the requested vertical, or ``None``. @@ -161,7 +185,7 @@ def select_strikes( if not typed: return None - short = _select_short(typed, spot=spot, cfg=cfg) + short = _select_short(typed, spot=spot, cfg=cfg, dvol_now=dvol_now) if short is None: return None diff --git a/src/cerbero_bite/core/exit_decision.py b/src/cerbero_bite/core/exit_decision.py index 3e8677f..32e6c3c 100644 --- a/src/cerbero_bite/core/exit_decision.py +++ b/src/cerbero_bite/core/exit_decision.py @@ -28,8 +28,10 @@ __all__ = ["ExitAction", "ExitDecisionResult", "PositionSnapshot", "evaluate"] ExitAction = Literal[ "HOLD", "CLOSE_PROFIT", + "CLOSE_PROFIT_PARTIAL", "CLOSE_STOP", "CLOSE_VOL", + "CLOSE_VOL_HARVEST", "CLOSE_TIME", "CLOSE_DELTA", "CLOSE_AVERSE", @@ -115,6 +117,22 @@ def evaluate(snapshot: PositionSnapshot, cfg: StrategyConfig) -> ExitDecisionRes f"mark {debit} ≤ {ec.profit_take_pct_of_credit:.0%} of credit {credit}", ) + # 1bis. Vol-collapse harvest (D): siamo IN profit (debit < credit) e + # la DVOL è scesa di tot punti rispetto all'entry. Edge IV-RV già + # catturato, non c'è motivo di tenere fino a profit_take. Esce + # opportunisticamente quando il regime di vol che giustificava + # l'entry non c'è più. + if ( + ec.vol_harvest_dvol_decrease > 0 + and debit < credit + and snapshot.dvol_now <= snapshot.dvol_at_entry - ec.vol_harvest_dvol_decrease + ): + return _result( + "CLOSE_VOL_HARVEST", + f"DVOL {snapshot.dvol_now} ≤ entry {snapshot.dvol_at_entry} − " + f"{ec.vol_harvest_dvol_decrease}, harvest while in profit", + ) + # 2. Stop loss if debit >= stop_thresh: return _result( diff --git a/src/cerbero_bite/runtime/auto_pause.py b/src/cerbero_bite/runtime/auto_pause.py new file mode 100644 index 0000000..fedd90c --- /dev/null +++ b/src/cerbero_bite/runtime/auto_pause.py @@ -0,0 +1,175 @@ +"""Auto-pause circuit breaker (§7-bis F). + +Pure-function evaluation that consults `system_state.auto_pause_until` +and the rolling P/L of the last N closed positions to decide whether +the engine should skip an entry cycle. + +Two responsibilities, both deterministic at call time: + +* :func:`is_paused` — returns ``True`` when the persisted + ``auto_pause_until`` is in the future. Independent from the kill + switch, which targets technical errors. +* :func:`evaluate_drawdown_breach` — given the last N closed P/Ls and + the current capital, returns whether the rolling drawdown breached + the configured ``max_drawdown_pct`` threshold. The orchestrator + layer is the one that flips the persisted state on breach (this + module stays I/O-free for testability). + +The two are separated on purpose: ``is_paused`` is the cheap, +read-only gate consulted at the start of every entry cycle; the +breach evaluation runs once per cycle right after the entry +filtering, before the entry is actually placed. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from datetime import datetime, timedelta +from decimal import Decimal + +from cerbero_bite.config.schema import AutoPauseConfig +from cerbero_bite.state.models import SystemStateRecord + +__all__ = [ + "AutoPauseDecision", + "PauseStatus", + "evaluate_drawdown_breach", + "is_paused", + "pause_until", +] + + +@dataclass(frozen=True) +class PauseStatus: + """Snapshot del flag di auto-pausa al momento della valutazione.""" + + paused: bool + until: datetime | None + reason: str | None + + +@dataclass(frozen=True) +class AutoPauseDecision: + """Esito di :func:`evaluate_drawdown_breach`.""" + + should_pause: bool + cumulative_pnl_usd: Decimal + drawdown_pct: Decimal + threshold_pct: Decimal + reason: str | None + + +def is_paused( + state: SystemStateRecord | None, *, now: datetime +) -> PauseStatus: + """Restituisce lo stato della pausa rispetto a ``now``. + + ``state == None`` o ``auto_pause_until == None`` o + ``auto_pause_until <= now`` ⇒ engine attivo. + """ + if state is None or state.auto_pause_until is None: + return PauseStatus(paused=False, until=None, reason=None) + until = state.auto_pause_until + if until.tzinfo is not None and now.tzinfo is None: + # Coerenza: se il valore persistito è tz-aware, normalizziamo. + return PauseStatus( + paused=until > now.replace(tzinfo=until.tzinfo), + until=until, + reason=state.auto_pause_reason, + ) + return PauseStatus( + paused=until > now, + until=until, + reason=state.auto_pause_reason, + ) + + +def pause_until(now: datetime, weeks: int) -> datetime: + """Calcola la scadenza della pausa (``now + weeks``). + + Estratto in funzione separata per facilitare i test e per ricordare + che la pausa è espressa in **settimane** (la strategia ha cron + settimanale; pause più corte non avrebbero modo di evitare una + settimana di entry). + """ + return now + timedelta(weeks=max(1, weeks)) + + +def evaluate_drawdown_breach( + *, + cfg: AutoPauseConfig, + recent_pnl_usd: list[Decimal], + capital_usd: Decimal, +) -> AutoPauseDecision: + """Decide se la pausa va armata ora dato il rolling P/L. + + Regola: se la somma dei P/L delle ultime ``cfg.lookback_trades`` + posizioni chiuse è negativa e in valore assoluto eccede + ``cfg.max_drawdown_pct × capital_usd``, ritorna + ``should_pause=True``. Tutte le altre condizioni → False. + + ``cfg.enabled=False`` → ritorna sempre False (filtro disabilitato). + Lookback insufficiente → ritorna False (non scattiamo finché non + abbiamo abbastanza storia per giudicare). + """ + threshold_pct = cfg.max_drawdown_pct + cumulative = sum((p for p in recent_pnl_usd), start=Decimal("0")) + + if not cfg.enabled: + return AutoPauseDecision( + should_pause=False, + cumulative_pnl_usd=cumulative, + drawdown_pct=Decimal("0"), + threshold_pct=threshold_pct, + reason=None, + ) + + if len(recent_pnl_usd) < cfg.lookback_trades: + return AutoPauseDecision( + should_pause=False, + cumulative_pnl_usd=cumulative, + drawdown_pct=Decimal("0"), + threshold_pct=threshold_pct, + reason=None, + ) + + if capital_usd <= 0: + return AutoPauseDecision( + should_pause=False, + cumulative_pnl_usd=cumulative, + drawdown_pct=Decimal("0"), + threshold_pct=threshold_pct, + reason=None, + ) + + # Solo perdite ci interessano: vincite cumulate non scattano la pausa. + if cumulative >= 0: + return AutoPauseDecision( + should_pause=False, + cumulative_pnl_usd=cumulative, + drawdown_pct=cumulative / capital_usd, + threshold_pct=threshold_pct, + reason=None, + ) + + drawdown_pct = (-cumulative) / capital_usd + if drawdown_pct >= threshold_pct: + return AutoPauseDecision( + should_pause=True, + cumulative_pnl_usd=cumulative, + drawdown_pct=drawdown_pct, + threshold_pct=threshold_pct, + reason=( + f"rolling DD {drawdown_pct:.2%} ≥ {threshold_pct:.2%} " + f"(last {cfg.lookback_trades} trades, " + f"cumulative {cumulative} USD)" + ), + ) + + return AutoPauseDecision( + should_pause=False, + cumulative_pnl_usd=cumulative, + drawdown_pct=drawdown_pct, + threshold_pct=threshold_pct, + reason=None, + ) diff --git a/src/cerbero_bite/runtime/entry_cycle.py b/src/cerbero_bite/runtime/entry_cycle.py index f14093c..2b95079 100644 --- a/src/cerbero_bite/runtime/entry_cycle.py +++ b/src/cerbero_bite/runtime/entry_cycle.py @@ -38,6 +38,7 @@ from cerbero_bite.core.entry_validator import ( from cerbero_bite.core.liquidity_gate import InstrumentSnapshot, check from cerbero_bite.core.sizing_engine import SizingContext, compute_contracts from cerbero_bite.core.types import OptionQuote +from cerbero_bite.runtime import auto_pause as auto_pause_module from cerbero_bite.runtime.alert_manager import AlertManager from cerbero_bite.runtime.dependencies import RuntimeContext from cerbero_bite.state import ( @@ -64,6 +65,7 @@ _STATUS_NO_ENTRY = "no_entry" _STATUS_BROKER_REJECT = "broker_reject" _STATUS_KILL_SWITCH = "kill_switch_armed" _STATUS_HAS_OPEN = "has_open_position" +_STATUS_AUTO_PAUSED = "auto_paused" @dataclass(frozen=True) @@ -322,6 +324,28 @@ async def run_entry_cycle( ) return EntryCycleResult(status=_STATUS_KILL_SWITCH, reason="kill_switch") + # §7-bis (F): auto-pause circuit breaker. Read-only consultation + # of the persisted state — the breach evaluation runs later, after + # capital is known. + conn = connect_state(ctx.db_path) + try: + sys_state = ctx.repository.get_system_state(conn) + finally: + conn.close() + pause_status = auto_pause_module.is_paused(sys_state, now=when) + if pause_status.paused: + await alert.low( + source="entry_cycle", + message=( + f"auto-paused until {pause_status.until} " + f"({pause_status.reason or 'no reason'}) — skipping" + ), + ) + return EntryCycleResult( + status=_STATUS_AUTO_PAUSED, + reason=pause_status.reason or "auto_paused", + ) + # Has open position? conn = connect_state(ctx.db_path) try: @@ -344,6 +368,44 @@ async def run_entry_cycle( ) capital_usd = snap.portfolio_eur * eur_to_usd_rate + # §7-bis (F): rolling drawdown breach evaluation. Se le ultime N + # posizioni chiuse hanno cumulato perdite oltre la soglia, armiamo + # la pausa e usciamo subito (l'entry di questo ciclo è saltata). + auto_cfg = cfg.auto_pause + if auto_cfg.enabled: + conn = connect_state(ctx.db_path) + try: + recent_pnls = ctx.repository.recent_closed_position_pnls_usd( + conn, limit=auto_cfg.lookback_trades + ) + finally: + conn.close() + breach = auto_pause_module.evaluate_drawdown_breach( + cfg=auto_cfg, + recent_pnl_usd=recent_pnls, + capital_usd=capital_usd, + ) + if breach.should_pause: + until = auto_pause_module.pause_until(when, auto_cfg.pause_weeks) + conn = connect_state(ctx.db_path) + try: + with transaction(conn): + ctx.repository.set_auto_pause( + conn, until=until, reason=breach.reason + ) + finally: + conn.close() + await alert.high( + source="entry_cycle", + message=( + f"auto-pause armed: {breach.reason} — paused until {until}" + ), + ) + return EntryCycleResult( + status=_STATUS_AUTO_PAUSED, + reason=breach.reason or "auto_paused", + ) + # 2. Entry filters entry_ctx = EntryContext( capital_usd=capital_usd, @@ -436,7 +498,12 @@ async def run_entry_cycle( ) quotes = await _build_quotes(ctx.deribit, chain_meta) selection = select_strikes( - chain=quotes, bias=bias, spot=snap.spot_eth_usd, now=when, cfg=cfg + chain=quotes, + bias=bias, + spot=snap.spot_eth_usd, + now=when, + cfg=cfg, + dvol_now=snap.dvol, # §3.2 (A) — strike picker dipendente dal regime DVOL ) if selection is None: await _record_decision( diff --git a/src/cerbero_bite/state/migrations/0004_auto_pause.sql b/src/cerbero_bite/state/migrations/0004_auto_pause.sql new file mode 100644 index 0000000..5fc43ed --- /dev/null +++ b/src/cerbero_bite/state/migrations/0004_auto_pause.sql @@ -0,0 +1,14 @@ +-- 0004_auto_pause.sql — circuit breaker su drawdown rolling (§7-bis F) +-- +-- Aggiunge alla `system_state` il timestamp fino a cui l'engine è in +-- pausa automatica per via di un drawdown sopra soglia. NULL = engine +-- attivo. Quando il valore è nel futuro, il rule engine salta il +-- ciclo entry e logga la motivazione. +-- +-- Indipendente dal kill_switch (che resta dedicato a errori tecnici +-- e a comandi manuali esplicitati). Le due tutele coesistono. + +ALTER TABLE system_state ADD COLUMN auto_pause_until TEXT; +ALTER TABLE system_state ADD COLUMN auto_pause_reason TEXT; + +PRAGMA user_version = 4; diff --git a/src/cerbero_bite/state/models.py b/src/cerbero_bite/state/models.py index f7cd965..ae4a7a7 100644 --- a/src/cerbero_bite/state/models.py +++ b/src/cerbero_bite/state/models.py @@ -184,3 +184,5 @@ class SystemStateRecord(BaseModel): config_version: str started_at: datetime last_audit_hash: str | None = None + auto_pause_until: datetime | None = None + auto_pause_reason: str | None = None diff --git a/src/cerbero_bite/state/repository.py b/src/cerbero_bite/state/repository.py index aae344d..bc0aad3 100644 --- a/src/cerbero_bite/state/repository.py +++ b/src/cerbero_bite/state/repository.py @@ -488,6 +488,16 @@ class Repository: last_audit_hash=( row["last_audit_hash"] if "last_audit_hash" in keys else None ), + auto_pause_until=( + _dec_dt(row["auto_pause_until"]) + if "auto_pause_until" in keys + else None + ), + auto_pause_reason=( + row["auto_pause_reason"] + if "auto_pause_reason" in keys + else None + ), ) def set_last_audit_hash( @@ -526,6 +536,43 @@ class Repository: (_enc_dt(now),), ) + def set_auto_pause( + self, + conn: sqlite3.Connection, + *, + until: datetime | None, + reason: str | None, + ) -> None: + """Imposta o azzera la pausa automatica (§7-bis F). + + ``until = None`` annulla la pausa (l'engine torna attivo). + Il setter è idempotente: chiamarlo con un until già nel passato + è equivalente a clear. + """ + conn.execute( + "UPDATE system_state SET auto_pause_until = ?, " + "auto_pause_reason = ? WHERE id = 1", + (_enc_dt(until) if until is not None else None, reason), + ) + + def recent_closed_position_pnls_usd( + self, conn: sqlite3.Connection, *, limit: int + ) -> list[Decimal]: + """Ritorna la lista dei pnl_usd delle ultime ``limit`` posizioni chiuse, + ordinate dalla più recente alla più vecchia. Posizioni con + ``pnl_usd`` ``NULL`` (es. chiuse di emergenza senza P/L noto) + sono saltate. Usato dal circuit breaker §7-bis F. + """ + if limit <= 0: + return [] + rows = conn.execute( + "SELECT pnl_usd FROM positions " + "WHERE closed_at IS NOT NULL AND pnl_usd IS NOT NULL " + "ORDER BY closed_at DESC LIMIT ?", + (limit,), + ).fetchall() + return [Decimal(row["pnl_usd"]) for row in rows] + # --------------------------------------------------------------------------- # Row → model converters diff --git a/strategy.aggressiva.yaml b/strategy.aggressiva.yaml index ffb8554..877ab89 100644 --- a/strategy.aggressiva.yaml +++ b/strategy.aggressiva.yaml @@ -28,8 +28,8 @@ # 2× via "ETH + BTC" indicato in `📚 Strategia` è una **stima ex-ante** # di cosa otterresti DOPO quel lavoro di codice. -config_version: "1.0.0-aggressiva" -config_hash: "b931a2b96fbc149b21cae84a196ee8bad10220b5ee8fa9ab0ed06ae52d7dc531" +config_version: "1.2.0-aggressiva" +config_hash: "e3a583cabfaa4781cd0ebcc8b62fc8f200648153738f93ab8726b062e46cacef" last_review: "2026-04-26" last_reviewer: "Adriano" @@ -78,6 +78,13 @@ structure: distance_otm_pct_min: "0.15" distance_otm_pct_max: "0.25" + # §3.2 (A): step-function delta-target per regime DVOL. + # DVOL bassa (≤50) → più premio; alta (>70) → più safety. + delta_by_dvol: + - {dvol_under: "50", delta_target: "0.15", delta_min: "0.13", delta_max: "0.17"} + - {dvol_under: "70", delta_target: "0.12", delta_min: "0.10", delta_max: "0.15"} + - {dvol_under: "90", delta_target: "0.10", delta_min: "0.08", delta_max: "0.12"} + spread_width: target_pct_of_spot: "0.04" min_pct_of_spot: "0.03" @@ -116,6 +123,14 @@ exit: delta_breach_threshold: "0.30" adverse_move_4h_pct: "0.05" + # §7-bis (D): vol-harvest abilitato a 15 punti vol di crollo. + vol_harvest_dvol_decrease: "15" + + # §7.1bis (C): scala graduata di profit-take. Pipeline runtime + # non ancora attiva; tenuta vuota fino al merge della + # partial-close pipeline. + profit_take_partial_levels: [] + monitor_cron: "0 2,14 * * *" user_confirmation_timeout_min: 30 @@ -124,6 +139,15 @@ exit: - "CLOSE_VOL" - "CLOSE_DELTA" +# §7-bis (F): circuit breaker abilitato. Soglia 15% (più tollerante +# del default conservativo perché la size aggressiva ha volatilità +# attesa più alta). +auto_pause: + enabled: true + lookback_trades: 5 + max_drawdown_pct: "0.15" + pause_weeks: 2 + execution: environment: "testnet" eur_to_usd: "1.075" diff --git a/strategy.conservativa.yaml b/strategy.conservativa.yaml index 52c30b0..0969625 100644 --- a/strategy.conservativa.yaml +++ b/strategy.conservativa.yaml @@ -15,8 +15,8 @@ # cerbero-bite config hash --file strategy.conservativa.yaml # e bumpare config_version. -config_version: "1.0.0-conservativa" -config_hash: "eff824281bbb538fba49434d8cc4b9c37675bc73d60e351293e263cc7e7b29ef" +config_version: "1.2.0-conservativa" +config_hash: "fa09dad9cfa40a8ab006ec85157635603e0c4b6381ecd5d721504e00c4119a1b" last_review: "2026-04-26" last_reviewer: "Adriano" @@ -100,6 +100,9 @@ exit: delta_breach_threshold: "0.30" adverse_move_4h_pct: "0.05" + vol_harvest_dvol_decrease: "0" + profit_take_partial_levels: [] + monitor_cron: "0 2,14 * * *" user_confirmation_timeout_min: 30 @@ -108,6 +111,12 @@ exit: - "CLOSE_VOL" - "CLOSE_DELTA" +auto_pause: + enabled: false + lookback_trades: 5 + max_drawdown_pct: "0.10" + pause_weeks: 2 + execution: environment: "testnet" eur_to_usd: "1.075" diff --git a/strategy.yaml b/strategy.yaml index 082917d..7203780 100644 --- a/strategy.yaml +++ b/strategy.yaml @@ -6,8 +6,8 @@ # config hash), and lands as a separate commit with the motivation in # the commit message. -config_version: "1.0.0" -config_hash: "4c2be4c51c849ed58fa22ec2b302016c453894dd0964b6d05445ab1b723e2d10" +config_version: "1.2.0" +config_hash: "33263a313b26b24b41269f93f93783784451ac9b4b6460005b95c2fb3624fcdc" last_review: "2026-04-26" last_reviewer: "Adriano" @@ -96,6 +96,13 @@ exit: delta_breach_threshold: "0.30" adverse_move_4h_pct: "0.05" + # §7-bis (D): vol-collapse harvest. 0 = disabilitato. + vol_harvest_dvol_decrease: "0" + + # §7.1bis (C): scala graduata di profit-take. Vuoto = chiusura + # atomica. Pipeline runtime non ancora attiva (hook futuro). + profit_take_partial_levels: [] + monitor_cron: "0 2,14 * * *" user_confirmation_timeout_min: 30 @@ -104,6 +111,14 @@ exit: - "CLOSE_VOL" - "CLOSE_DELTA" +# §7-bis (F): circuit breaker su drawdown rolling. Disabilitato di +# default — abilitarlo solo dopo abbastanza posizioni chiuse. +auto_pause: + enabled: false + lookback_trades: 5 + max_drawdown_pct: "0.10" + pause_weeks: 2 + execution: environment: "testnet" # testnet|mainnet — kill switch on broker mismatch eur_to_usd: "1.075" # default FX rate for sizing engine; override at boot diff --git a/tests/unit/test_auto_pause.py b/tests/unit/test_auto_pause.py new file mode 100644 index 0000000..8fd8cc7 --- /dev/null +++ b/tests/unit/test_auto_pause.py @@ -0,0 +1,157 @@ +"""TDD per :mod:`cerbero_bite.runtime.auto_pause` (§7-bis F).""" + +from __future__ import annotations + +from datetime import UTC, datetime, timedelta +from decimal import Decimal + +import pytest + +from cerbero_bite.config.schema import AutoPauseConfig +from cerbero_bite.runtime.auto_pause import ( + evaluate_drawdown_breach, + is_paused, + pause_until, +) +from cerbero_bite.state.models import SystemStateRecord + + +_NOW = datetime(2026, 5, 1, 14, 0, tzinfo=UTC) + + +def _state(**overrides: object) -> SystemStateRecord: + base: dict[str, object] = { + "kill_switch": 0, + "last_health_check": _NOW, + "config_version": "1.0.0", + "started_at": _NOW - timedelta(hours=1), + } + base.update(overrides) + return SystemStateRecord(**base) # type: ignore[arg-type] + + +# --------------------------------------------------------------------------- +# is_paused +# --------------------------------------------------------------------------- + + +def test_is_paused_returns_false_when_state_is_none() -> None: + status = is_paused(None, now=_NOW) + assert status.paused is False + + +def test_is_paused_returns_false_when_until_is_none() -> None: + status = is_paused(_state(), now=_NOW) + assert status.paused is False + + +def test_is_paused_returns_true_when_until_in_future() -> None: + status = is_paused( + _state(auto_pause_until=_NOW + timedelta(weeks=2), + auto_pause_reason="DD breach"), + now=_NOW, + ) + assert status.paused is True + assert status.reason == "DD breach" + + +def test_is_paused_returns_false_when_until_in_past() -> None: + status = is_paused( + _state(auto_pause_until=_NOW - timedelta(seconds=1)), + now=_NOW, + ) + assert status.paused is False + + +# --------------------------------------------------------------------------- +# pause_until +# --------------------------------------------------------------------------- + + +def test_pause_until_adds_weeks() -> None: + until = pause_until(_NOW, weeks=2) + assert until == _NOW + timedelta(weeks=2) + + +def test_pause_until_clamps_to_one_week_minimum() -> None: + # weeks <= 0 deve cmq dare almeno 1 settimana di pausa, altrimenti + # la cron settimanale potrebbe scattare comunque. + assert pause_until(_NOW, weeks=0) == _NOW + timedelta(weeks=1) + assert pause_until(_NOW, weeks=-3) == _NOW + timedelta(weeks=1) + + +# --------------------------------------------------------------------------- +# evaluate_drawdown_breach +# --------------------------------------------------------------------------- + + +def _cfg(**overrides: object) -> AutoPauseConfig: + base: dict[str, object] = { + "enabled": True, + "lookback_trades": 5, + "max_drawdown_pct": Decimal("0.10"), + "pause_weeks": 2, + } + base.update(overrides) + return AutoPauseConfig(**base) # type: ignore[arg-type] + + +def test_drawdown_breach_when_enabled_and_threshold_exceeded() -> None: + decision = evaluate_drawdown_breach( + cfg=_cfg(), + recent_pnl_usd=[Decimal("-50"), Decimal("-60"), Decimal("-40"), + Decimal("-30"), Decimal("-20")], # cum −200 USD + capital_usd=Decimal("1500"), + ) + # |200| / 1500 = 0.133 > 0.10 + assert decision.should_pause is True + assert decision.reason is not None + assert "rolling DD" in decision.reason + + +def test_no_breach_when_filter_disabled() -> None: + decision = evaluate_drawdown_breach( + cfg=_cfg(enabled=False), + recent_pnl_usd=[Decimal("-200")] * 5, # massacro + capital_usd=Decimal("1500"), + ) + assert decision.should_pause is False + + +def test_no_breach_when_lookback_insufficient() -> None: + decision = evaluate_drawdown_breach( + cfg=_cfg(lookback_trades=5), + recent_pnl_usd=[Decimal("-100")] * 3, # solo 3 trade, serve 5 + capital_usd=Decimal("1500"), + ) + assert decision.should_pause is False + + +def test_no_breach_when_cumulative_positive() -> None: + # Anche con tante perdite, se la somma è positiva non scattiamo. + decision = evaluate_drawdown_breach( + cfg=_cfg(), + recent_pnl_usd=[Decimal("-100"), Decimal("-50"), + Decimal("300"), Decimal("-20"), Decimal("-10")], + capital_usd=Decimal("1500"), + ) + assert decision.should_pause is False + + +def test_no_breach_when_below_threshold() -> None: + decision = evaluate_drawdown_breach( + cfg=_cfg(), + recent_pnl_usd=[Decimal("-30")] * 5, # cum −150 / 1500 = 10% esatto + capital_usd=Decimal("1500"), + ) + # esattamente alla soglia (>=) ⇒ pausa armata + assert decision.should_pause is True + + +def test_no_breach_when_capital_zero_or_negative() -> None: + decision = evaluate_drawdown_breach( + cfg=_cfg(), + recent_pnl_usd=[Decimal("-100")] * 5, + capital_usd=Decimal("0"), + ) + assert decision.should_pause is False diff --git a/tests/unit/test_combo_builder.py b/tests/unit/test_combo_builder.py index 01433d9..5f9ca81 100644 --- a/tests/unit/test_combo_builder.py +++ b/tests/unit/test_combo_builder.py @@ -329,3 +329,146 @@ def test_build_bear_call_breakeven_above_short_strike( # breakeven = 3525 + 15 = 3540 assert proposal.breakeven == Decimal("3540") assert proposal.spread_type == "bear_call" + + +# --------------------------------------------------------------------------- +# §3.2 (A): dynamic delta target by DVOL regime +# --------------------------------------------------------------------------- + + +def _cfg_with_delta_bands(cfg: StrategyConfig) -> StrategyConfig: + """Profilo con step-function delta su DVOL. + + Vol bassa (≤50) → delta 0.15 (più premio), vol media (≤70) → + 0.12 (default), vol alta (≤90) → 0.10 (più safety distance). + """ + from cerbero_bite.config.schema import ( + DeltaByDvolBand, + ShortStrikeSpec, + StructureConfig, + ) + bands = [ + DeltaByDvolBand( + dvol_under=Decimal("50"), + delta_target=Decimal("0.15"), + delta_min=Decimal("0.13"), + delta_max=Decimal("0.17"), + ), + DeltaByDvolBand( + dvol_under=Decimal("70"), + delta_target=Decimal("0.12"), + delta_min=Decimal("0.10"), + delta_max=Decimal("0.15"), + ), + DeltaByDvolBand( + dvol_under=Decimal("90"), + delta_target=Decimal("0.10"), + delta_min=Decimal("0.08"), + delta_max=Decimal("0.12"), + ), + ] + new_short = ShortStrikeSpec( + **{**cfg.structure.short_strike.model_dump(), "delta_by_dvol": bands} + ) + return cfg.model_copy( + update={ + "structure": StructureConfig( + **{**cfg.structure.model_dump(exclude={"short_strike"}), + "short_strike": new_short} + ) + } + ) + + +def _bull_put_chain_wide(now_dt: datetime) -> list[OptionQuote]: + """Chain con shorts e longs per delta 0.10, 0.12, 0.15. + + I mid sono tarati per superare il credit/width ≥ 30% per ogni + accoppiamento short→long testato (vedi commento §3.4). + """ + return [ + # Shorts a delta 0.10 / 0.12 / 0.15 in OTM range [15-25%]. + _quote(strike="2535", delta="-0.15", mid="0.026", now_dt=now_dt), + _quote(strike="2475", delta="-0.12", mid="0.020", now_dt=now_dt), + _quote(strike="2400", delta="-0.10", mid="0.015", now_dt=now_dt), + # Long candidati ~4% sotto ciascuno short. + _quote(strike="2415", delta="-0.10", mid="0.012", now_dt=now_dt), + _quote(strike="2355", delta="-0.08", mid="0.006", now_dt=now_dt), + _quote(strike="2280", delta="-0.06", mid="0.002", now_dt=now_dt), + ] + + +def test_dynamic_delta_low_dvol_picks_higher_delta( + cfg: StrategyConfig, now: datetime +) -> None: + """DVOL=40 → banda con delta_target=0.15.""" + cfg_dyn = _cfg_with_delta_bands(cfg) + chain = _bull_put_chain_wide(now) + res = select_strikes( + chain=chain, + bias="bull_put", + spot=Decimal("3000"), + now=now, + cfg=cfg_dyn, + dvol_now=Decimal("40"), + ) + assert res is not None + short, _ = res + assert short.delta == Decimal("-0.15") + + +def test_dynamic_delta_mid_dvol_picks_default_delta( + cfg: StrategyConfig, now: datetime +) -> None: + """DVOL=60 → banda con delta_target=0.12.""" + cfg_dyn = _cfg_with_delta_bands(cfg) + chain = _bull_put_chain_wide(now) + res = select_strikes( + chain=chain, + bias="bull_put", + spot=Decimal("3000"), + now=now, + cfg=cfg_dyn, + dvol_now=Decimal("60"), + ) + assert res is not None + short, _ = res + assert short.delta == Decimal("-0.12") + + +def test_dynamic_delta_high_dvol_picks_lower_delta( + cfg: StrategyConfig, now: datetime +) -> None: + """DVOL=85 → banda con delta_target=0.10 (più safety distance).""" + cfg_dyn = _cfg_with_delta_bands(cfg) + chain = _bull_put_chain_wide(now) + res = select_strikes( + chain=chain, + bias="bull_put", + spot=Decimal("3000"), + now=now, + cfg=cfg_dyn, + dvol_now=Decimal("85"), + ) + assert res is not None + short, _ = res + assert short.delta == Decimal("-0.10") + + +def test_dynamic_delta_disabled_default_uses_static_delta( + cfg: StrategyConfig, now: datetime +) -> None: + """delta_by_dvol vuoto (default) → comportamento invariato.""" + chain = _bull_put_chain_wide(now) + res = select_strikes( + chain=chain, + bias="bull_put", + spot=Decimal("3000"), + now=now, + cfg=cfg, # golden config: delta_by_dvol=[] + dvol_now=Decimal("40"), + ) + assert res is not None + short, _ = res + # Delta target statico = 0.12, quindi torna lo strike a -0.12. + assert short.delta == Decimal("-0.12") diff --git a/tests/unit/test_config_loader.py b/tests/unit/test_config_loader.py index 26510b4..557c626 100644 --- a/tests/unit/test_config_loader.py +++ b/tests/unit/test_config_loader.py @@ -68,7 +68,7 @@ def test_compute_hash_is_independent_of_recorded_hash_value(tmp_path: Path) -> N def test_load_repo_strategy_yaml(tmp_path: Path) -> None: """The committed strategy.yaml validates with the recorded hash.""" result = load_strategy(REPO_ROOT / "strategy.yaml") - assert result.config.config_version == "1.0.0" + assert result.config.config_version == "1.2.0" assert result.config.sizing.kelly_fraction == Decimal("0.13") assert result.computed_hash == result.config.config_hash diff --git a/tests/unit/test_exit_decision.py b/tests/unit/test_exit_decision.py index 3a3b1e1..c34c641 100644 --- a/tests/unit/test_exit_decision.py +++ b/tests/unit/test_exit_decision.py @@ -271,3 +271,91 @@ def test_iron_condor_adverse_move_either_direction(cfg: StrategyConfig) -> None: ) res = evaluate(snap, cfg) assert res.action == "CLOSE_AVERSE" + + +# --------------------------------------------------------------------------- +# §7-bis (D): vol-collapse harvest +# --------------------------------------------------------------------------- + + +def _harvest_cfg( + cfg: StrategyConfig, *, threshold: str = "15" +) -> StrategyConfig: + """Clona la golden config con la soglia di vol-harvest abilitata.""" + from cerbero_bite.config import ExitConfig + return cfg.model_copy( + update={ + "exit": ExitConfig( + **{ + **cfg.exit.model_dump(), + "vol_harvest_dvol_decrease": Decimal(threshold), + } + ) + } + ) + + +def test_vol_harvest_disabled_by_default_does_not_fire(cfg: StrategyConfig) -> None: + # Default: vol_harvest_dvol_decrease = 0 ⇒ filtro disabilitato. + snap = _snapshot( + credit_received_eth="0.030", + mark_combo_now_eth="0.022", # in profit (debit < credit) + dvol_at_entry="60", + dvol_now="40", # crollato di 20 punti + ) + res = evaluate(snap, cfg) + assert res.action == "HOLD" + + +def test_vol_harvest_fires_when_dvol_collapsed_in_profit( + cfg: StrategyConfig, +) -> None: + harvest = _harvest_cfg(cfg, threshold="15") + snap = _snapshot( + credit_received_eth="0.030", + mark_combo_now_eth="0.022", # in profit ma sopra profit_take 50% + dvol_at_entry="60", + dvol_now="42", # −18, supera la soglia 15 + ) + res = evaluate(snap, harvest) + assert res.action == "CLOSE_VOL_HARVEST" + assert "harvest" in res.reason + + +def test_vol_harvest_does_not_fire_when_in_loss(cfg: StrategyConfig) -> None: + # Anche se DVOL crolla, se siamo in perdita non vogliamo harvest: + # è una funzione di "esci con il profitto in mano", non un panico. + harvest = _harvest_cfg(cfg, threshold="15") + snap = _snapshot( + credit_received_eth="0.030", + mark_combo_now_eth="0.040", # debit > credit ⇒ in perdita + dvol_at_entry="60", + dvol_now="42", + ) + res = evaluate(snap, harvest) + assert res.action != "CLOSE_VOL_HARVEST" + + +def test_vol_harvest_does_not_fire_below_threshold(cfg: StrategyConfig) -> None: + harvest = _harvest_cfg(cfg, threshold="15") + snap = _snapshot( + credit_received_eth="0.030", + mark_combo_now_eth="0.022", + dvol_at_entry="60", + dvol_now="50", # −10, sotto la soglia 15 + ) + res = evaluate(snap, harvest) + assert res.action == "HOLD" + + +def test_profit_take_wins_over_vol_harvest(cfg: StrategyConfig) -> None: + # Quando il profit-take è già colpito, non passiamo per vol-harvest. + harvest = _harvest_cfg(cfg, threshold="15") + snap = _snapshot( + credit_received_eth="0.030", + mark_combo_now_eth="0.014", # ≤ 50% credit ⇒ profit-take + dvol_at_entry="60", + dvol_now="42", + ) + res = evaluate(snap, harvest) + assert res.action == "CLOSE_PROFIT"