3 Commits

Author SHA1 Message Date
root 18cc27a76e feat(gui): simulazione P/L con effetti dei miglioramenti FDAC + IV-RV
Estende il pannello "💰 P/L atteso" della pagina `📚 Strategia` per
applicare gli effetti stimati di IV-RV gate, A (delta dinamico),
D (vol-harvest) e F (auto-pause) leggendoli direttamente dai
`strategy.*.yaml` di ciascun profilo.

- Nuova `_detect_features(strategy)` che ispeziona la config:
    A → `short_strike.delta_by_dvol` non vuoto
    D → `exit.vol_harvest_dvol_decrease > 0`
    F → `auto_pause.enabled`
    IV → `entry.iv_minus_rv_filter_enabled`
- `_compute_pl` accetta ora un dict `features` opzionale e applica:
    IV: +5 pp win-rate, −25% trade/anno (skip-week aggressivo)
    A: +1.5 pp win-rate, sl_loss × 0.95 (strike picking migliore)
    D: 5% trade convertiti da loss a harvest exit (+0.20×credito)
    F: −8% trade/anno (skip-week dopo streak)
- `_render_profile_card` mostra ora:
    badge "🟢 Miglioramenti attivi" con la lista per profilo,
    delta vs base in E[trade] e P/L annuo,
    help con win_rate effettivo / prob_loss / trade/anno.
- Checkbox "Applica effetti dei miglioramenti" (default ON) per
  switchare tra simulazione realistica e formula base.
- Nuova mini-tabella "Contributo marginale di ogni feature": per
  ogni miglioramento mostra ΔP/L annuo e ΔAPR isolando l'effetto
  del singolo feature, con marker " attiva nel YAML".
- Sensibilità win-rate ora applica le feature attive ai due profili.

Effetti dichiarati come **stime ex-ante** dalla letteratura
short-vol systematic; i valori puntuali (+5 pp win, etc.) andranno
calibrati sul dataset accumulato.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-01 20:17:24 +00:00
root 1c6baaee83 feat(strategy): F+D+A miglioramenti — auto-pause, vol-harvest, delta dinamico
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) <noreply@anthropic.com>
2026-05-01 20:07:25 +00:00
root 21e865ffb0 feat(gui+infra): pagina Strategia, P/L parametrico, profili Conservativa/Aggressiva, dashboard via Traefik
Espone la GUI Streamlit su https://cerbero-bite.tielogic.xyz tramite il
Traefik già attivo sull'host (label allineate al pattern di cerbero-mcp,
TLS via Let's Encrypt, websocket pass-through). Aggiunge:

- nuova tab `📚 Strategia` con stato live dei gate §2 confrontati con
  l'ultimo tick di market_snapshots, pannello P/L parametrico
  affiancato Conservativa vs Aggressiva, tabella di sensibilità
  win-rate → APR e rendering del documento canonico esteso.
- doc `13-strategia-spiegata.md` che lega ogni regola §2-§9 al campo di
  market_snapshots che la alimenta, con sezioni §4-bis (P/L atteso
  realistico, win-rate empirico, drawdown, Sharpe) e §4-ter (confronto
  fra i due profili e quando passare dall'uno all'altro).
- `strategy.conservativa.yaml` (golden config v1.0.0 esplicita) e
  `strategy.aggressiva.yaml` (cap_per_trade 4×, max_concurrent 2×,
  max_contracts 4×, deroga §11 documentata) con config_hash validi.
- nel compose: servizio dedicato `cerbero-bite-gui` (Streamlit su
  0.0.0.0:8765, healthcheck su /_stcore/health, label Traefik), env
  condivisi via anchor YAML `x-bite-env`, `--environment mainnet`
  passato a `start` per allineare il boot check al token del .env (era
  testnet vs mainnet → kill switch armato all'avvio).
- Dockerfile installa anche l'extra `gui` (streamlit) e copia
  `docs/` + i due nuovi profili nell'immagine; `.dockerignore` non
  esclude più `docs/` (causa del primo build silenzioso).

Fix bonus: `_try_load` nella pagina ritornava `LoadedConfig` ma la GUI
leggeva `.sizing.*` direttamente — l'`except: pass` mascherava
l'AttributeError facendo cadere sui default conservativi sia nel
pannello P/L sia nello stato gate (stesso pattern presente nella
Calibrazione). Ora ritorna `.config`.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-01 18:20:23 +00:00
20 changed files with 2764 additions and 35 deletions
-1
View File
@@ -5,7 +5,6 @@
.pytest_cache/ .pytest_cache/
__pycache__/ __pycache__/
data/ data/
docs/
tests/ tests/
.coverage .coverage
htmlcov/ htmlcov/
+8 -2
View File
@@ -14,12 +14,12 @@ ENV UV_PROJECT_ENVIRONMENT=/opt/venv \
# Install only the dependencies first so the layer is cached when the # Install only the dependencies first so the layer is cached when the
# source tree changes. # source tree changes.
COPY pyproject.toml uv.lock ./ COPY pyproject.toml uv.lock ./
RUN uv sync --frozen --no-dev --no-install-project RUN uv sync --frozen --no-dev --no-install-project --extra gui
# Now copy the source tree and install the project itself. # Now copy the source tree and install the project itself.
COPY src ./src COPY src ./src
COPY README.md ./ COPY README.md ./
RUN uv sync --frozen --no-dev RUN uv sync --frozen --no-dev --extra gui
FROM python:3.13-slim AS runtime FROM python:3.13-slim AS runtime
@@ -40,6 +40,12 @@ COPY --from=builder /opt/venv /opt/venv
COPY --from=builder /app/src /app/src COPY --from=builder /app/src /app/src
COPY scripts /app/scripts COPY scripts /app/scripts
COPY strategy.yaml /app/strategy.yaml COPY strategy.yaml /app/strategy.yaml
# Profili alternativi confrontati nella pagina "📚 Strategia".
COPY strategy.conservativa.yaml /app/strategy.conservativa.yaml
COPY strategy.aggressiva.yaml /app/strategy.aggressiva.yaml
# Documentation is shipped at runtime so the Streamlit "Strategia"
# page can render the canonical strategy doc directly.
COPY docs /app/docs
# Persistent state + audit go into /app/data, mounted as a volume in # Persistent state + audit go into /app/data, mounted as a volume in
# docker-compose.yml. # docker-compose.yml.
+90 -25
View File
@@ -1,27 +1,48 @@
# docker-compose.yml — Cerbero Bite # docker-compose.yml — Cerbero Bite
# #
# Bite runs in its own Compose project but joins the same Docker # Bite runs in its own Compose project but joins the same Docker
# network used by Cerbero MCP V2 so it can resolve the in-cluster # network used by Cerbero MCP V2 and Traefik (`traefik`) so it can
# service name when running co-located, and otherwise reaches the # either resolve the in-cluster service name (`cerbero-mcp:9000`)
# public gateway (`https://cerbero-mcp.tielogic.xyz`) over the host # or reach the public gateway (`https://cerbero-mcp.tielogic.xyz`)
# network. # transparently.
# #
# The shared network is declared as external here. Create it once on # The reverse-proxy network (`traefik`) is declared as external
# the host with `docker network create cerbero-suite` (or rename the # here. It is created by the Traefik stack at /opt/docker/traefik
# Cerbero_mcp network to `cerbero-suite` and mark it external). # and shared by every web-facing service on the host.
# #
# Authentication: a single bearer token is passed through from the # Authentication: a single bearer token is passed through from the
# host `.env` file via `CERBERO_BITE_MCP_TOKEN`. The Cerbero MCP V2 # host `.env` file via `CERBERO_BITE_MCP_TOKEN`. The Cerbero MCP V2
# server uses the token to decide whether the upstream environment # server uses the token to decide whether the upstream environment
# is testnet or mainnet; switching environment = switching token. # is testnet or mainnet; switching environment = switching token.
#
# Two services are defined:
# * `cerbero-bite` — the trading engine / CLI worker
# * `cerbero-bite-gui` — the Streamlit dashboard, exposed by
# Traefik at https://cerbero-bite.<DOMAIN>
networks: networks:
cerbero-suite: traefik:
external: true external: true
volumes: volumes:
bite-data: bite-data:
x-bite-env: &bite-env
CERBERO_BITE_MCP_TOKEN: ${CERBERO_BITE_MCP_TOKEN:?missing CERBERO_BITE_MCP_TOKEN}
CERBERO_BITE_MCP_BOT_TAG: ${CERBERO_BITE_MCP_BOT_TAG:-BOT__CERBERO_BITE}
# Two independent runtime flags that decide what each cycle does.
# Initial period ("data-only"): DATA_ANALYSIS=true, STRATEGY=false.
CERBERO_BITE_ENABLE_DATA_ANALYSIS: ${CERBERO_BITE_ENABLE_DATA_ANALYSIS:-true}
CERBERO_BITE_ENABLE_STRATEGY: ${CERBERO_BITE_ENABLE_STRATEGY:-false}
# Service URLs — defaults below match the in-cluster Traefik network
# DNS (V2 unified image listening on port 9000). Override any of
# them via .env to point at the public gateway, a custom host, or
# localhost for dev work.
CERBERO_BITE_MCP_DERIBIT_URL: ${CERBERO_BITE_MCP_DERIBIT_URL:-http://cerbero-mcp:9000/mcp-deribit}
CERBERO_BITE_MCP_HYPERLIQUID_URL: ${CERBERO_BITE_MCP_HYPERLIQUID_URL:-http://cerbero-mcp:9000/mcp-hyperliquid}
CERBERO_BITE_MCP_MACRO_URL: ${CERBERO_BITE_MCP_MACRO_URL:-http://cerbero-mcp:9000/mcp-macro}
CERBERO_BITE_MCP_SENTIMENT_URL: ${CERBERO_BITE_MCP_SENTIMENT_URL:-http://cerbero-mcp:9000/mcp-sentiment}
services: services:
cerbero-bite: cerbero-bite:
build: build:
@@ -29,24 +50,12 @@ services:
dockerfile: Dockerfile dockerfile: Dockerfile
image: cerbero-bite:dev image: cerbero-bite:dev
restart: unless-stopped restart: unless-stopped
networks: [cerbero-suite] networks: [traefik]
cap_drop: [ALL] cap_drop: [ALL]
security_opt: security_opt:
- no-new-privileges:true - no-new-privileges:true
environment: environment:
# MCP auth — token is sourced from the host .env (compose <<: *bite-env
# interpolation). The `X-Bot-Tag` value below is the audit
# identifier the MCP server logs for every write call.
CERBERO_BITE_MCP_TOKEN: ${CERBERO_BITE_MCP_TOKEN:?missing CERBERO_BITE_MCP_TOKEN}
CERBERO_BITE_MCP_BOT_TAG: ${CERBERO_BITE_MCP_BOT_TAG:-BOT__CERBERO_BITE}
# Service URLs — defaults below match the in-cluster cerbero-suite
# network DNS (V2 unified image listening on port 9000). Override
# any of them to point at the public gateway, a custom host, or
# localhost for dev work.
CERBERO_BITE_MCP_DERIBIT_URL: ${CERBERO_BITE_MCP_DERIBIT_URL:-http://cerbero-mcp:9000/mcp-deribit}
CERBERO_BITE_MCP_HYPERLIQUID_URL: ${CERBERO_BITE_MCP_HYPERLIQUID_URL:-http://cerbero-mcp:9000/mcp-hyperliquid}
CERBERO_BITE_MCP_MACRO_URL: ${CERBERO_BITE_MCP_MACRO_URL:-http://cerbero-mcp:9000/mcp-macro}
CERBERO_BITE_MCP_SENTIMENT_URL: ${CERBERO_BITE_MCP_SENTIMENT_URL:-http://cerbero-mcp:9000/mcp-sentiment}
# Telegram and Portfolio are no longer shared MCP services. The # Telegram and Portfolio are no longer shared MCP services. The
# bot now calls the Telegram Bot API directly and aggregates # bot now calls the Telegram Bot API directly and aggregates
# portfolio in-process from Deribit + Hyperliquid + Macro. # portfolio in-process from Deribit + Hyperliquid + Macro.
@@ -62,6 +71,62 @@ services:
timeout: 5s timeout: 5s
retries: 3 retries: 3
start_period: 120s start_period: 120s
# Default command runs the engine status check; override with the # Engine main loop (scheduler + monitoring). Switch to `status`,
# CLI subcommand of choice (start, ping, dry-run, ...). # `ping`, `dry-run`, ... for one-shot diagnostics. The MCP token in
command: ["status"] # `.env` decides the upstream environment server-side; the `start`
# flag below tells the local boot check what to expect (must match,
# otherwise the engine arms the kill switch).
command: ["start", "--environment", "mainnet"]
# Streamlit dashboard published by Traefik on
# https://cerbero-bite.${DOMAIN_NAME:-tielogic.xyz}
#
# The CLI sub-command `cerbero-bite gui` hard-codes the listen
# address to 127.0.0.1, so we bypass the entrypoint and invoke
# Streamlit directly. The two `CERBERO_BITE_GUI_*` env vars match
# what the CLI normally injects (see src/cerbero_bite/cli.py).
cerbero-bite-gui:
image: cerbero-bite:dev
restart: unless-stopped
depends_on:
- cerbero-bite
networks: [traefik]
cap_drop: [ALL]
security_opt:
- no-new-privileges:true
environment:
<<: *bite-env
CERBERO_BITE_GUI_DB: /app/data/state.sqlite
CERBERO_BITE_GUI_AUDIT: /app/data/log/audit.jsonl
volumes:
- bite-data:/app/data
entrypoint:
- python
- -m
- streamlit
- run
- /app/src/cerbero_bite/gui/main.py
- --server.address=0.0.0.0
- --server.port=8765
- --server.headless=true
- --browser.gatherUsageStats=false
command: []
healthcheck:
test:
- "CMD"
- "python"
- "-c"
- "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8765/_stcore/health', timeout=3).close()"
interval: 30s
timeout: 5s
retries: 3
start_period: 30s
labels:
- traefik.enable=true
- traefik.docker.network=traefik
- "traefik.http.routers.cerbero-bite.rule=Host(`cerbero-bite.${DOMAIN_NAME:-tielogic.xyz}`)"
- traefik.http.routers.cerbero-bite.tls=true
- traefik.http.routers.cerbero-bite.entrypoints=websecure
- traefik.http.routers.cerbero-bite.tls.certresolver=mytlschallenge
- traefik.http.services.cerbero-bite.loadbalancer.server.port=8765
- com.centurylinklabs.watchtower.enable=true
+592
View File
@@ -0,0 +1,592 @@
# 13 — Strategia spiegata: dalle regole ai dati
> Documento operativo che lega ogni decisione del rule engine al dato
> osservabile da cui dipende. Pensato per chi guarda il cruscotto e
> vuole capire **a cosa servono** le metriche raccolte ogni 15 minuti
> nella tabella `market_snapshots`. La versione canonica e immutabile
> delle regole resta in `01-strategy-rules.md`; questo documento è la
> guida descrittiva da leggere prima di toccare le soglie in
> `strategy.yaml`.
---
## TL;DR
Cerbero Bite vende **credit spread settimanali su ETH/Deribit** quando
la volatilità implicita è **abbastanza alta da pagare bene**, il
mercato non è in **stress di liquidazione**, non ci sono **eventi macro
forti** in finestra, e il bias direzionale è **chiaro** (bull o bear).
Tutto il resto del tempo, l'engine **non opera**: la disciplina è la
strategia.
Ogni 15 minuti raccoglie 1 riga per asset (ETH e BTC) nella tabella
`market_snapshots`. Quei dati alimentano tre obiettivi distinti:
1. **Decisione live** — l'entry ciclo del lunedì 14:00 UTC legge i
campi più freschi per dire "go/no-go".
2. **Monitoring continuo** — il decision loop di gestione attiva
confronta la situazione con quella all'apertura.
3. **Calibrazione** — la pagina `📐 Calibrazione` usa la distribuzione
storica di ciascun campo per scegliere soglie basate sui percentili
reali del proprio ambiente, non a istinto.
---
## 1. Cosa c'è in `market_snapshots` (1 riga ogni 15 min, per asset)
| Campo | Unità | Sorgente MCP | A che serve nella strategia |
|---|---|---|---|
| `timestamp` | UTC ISO | scheduler | indicizzazione della time-series |
| `asset` | ETH / BTC | scheduler | partizionamento (ETH = sottostante operativo, BTC = controllo macro) |
| `spot` | USD | mcp-deribit `spot_perp_price` | trend 30g (§3.1), distanza % strike (§3.2/3.3), context generale |
| `dvol` | indice 0200 | mcp-deribit `latest_dvol` | gate entry §2.3-§2.4 (35 ≤ DVOL ≤ 90), aggiustamento sizing §5.3, vol-stop §7.3 |
| `realized_vol_30d` | % annualizzata | mcp-deribit `realized_vol` | confronto con DVOL → mean-reversion edge |
| `iv_minus_rv` | punti vol | derivato | richness della IV: > 0 = premio "ricco" da vendere |
| `funding_perp_annualized` | frazione | mcp-hyperliquid `funding_rate_annualized` | gate entry §2.6 (\|f\| ≤ 80% annualizzato), bias §3.1 |
| `funding_cross_annualized` | frazione | mcp-sentiment `funding_cross_median_annualized` | bias direzionale §3.1 (mediana 4 maggiori exchange) |
| `dealer_net_gamma` | USD | mcp-deribit `dealer_gamma_profile` | filtro quant §2.8 (long-gamma regime sopprime la vol → ideale per vendere spread) |
| `gamma_flip_level` | USD | mcp-deribit `dealer_gamma_profile` | livello spot oltre il quale il regime di gamma flippa |
| `oi_delta_pct_4h` | % | mcp-sentiment `liquidation_heatmap` | proxy di accumulo/sgonfiaggio leverage nelle ultime 4h |
| `liquidation_long_risk` | low / med / high | mcp-sentiment `liquidation_heatmap` | rischio long squeeze imminente |
| `liquidation_short_risk` | low / med / high | mcp-sentiment `liquidation_heatmap` | rischio short squeeze imminente |
| `macro_days_to_event` | giorni | mcp-macro `next_high_severity_within` | gate §2.5 (no entry se evento macro entro DTE) |
| `fetch_ok` | bool | scheduler | qualità riga (true = tutte le sotto-chiamate sono andate) |
| `fetch_errors_json` | json o NULL | scheduler | mappa errori per debugging best-effort |
> Un campo `NULL` non invalida la riga: la collezione è
> **best-effort**, una MCP giù non blocca le altre. Le distribuzioni
> si calcolano sui campi disponibili, l'engine entry-cycle invece
> rifiuta l'entry se il dato che gli serve è `NULL` (sicurezza:
> meglio saltare un trade che operare alla cieca).
---
## 2. Le sei famiglie di dati e il "perché"
### 2.1 — Volatilità implicita (DVOL, realized vol, IVRV)
**Cosa misura.** DVOL è l'indice Deribit della IV ETM 30g. Realized
30g è la deviazione standard annualizzata dei rendimenti spot. La
differenza `IV RV` quantifica quanto le opzioni stanno **pagando
sopra** la volatilità che il mercato ha effettivamente realizzato:
**questa è la materia prima del credit spread venditore.**
**Come la usa l'engine.**
- §2.3 / §2.4: `dvol_min = 35`, `dvol_max = 90` — sotto 35 il premio
è troppo magro rispetto a fees+slippage, sopra 90 si è in
stress-regime (rischio gap > edge).
- §5.3: `dvol_adjustment` riduce la size all'aumentare del DVOL
(×1.0 sotto 45, ×0.85 fra 4560, ×0.65 fra 6080, no entry > 80).
- §7.3: `vol_stop_dvol_increase = 10` — se durante la posizione
DVOL sale di 10 punti rispetto all'entry, si chiude.
**Cosa si calibra dai dati raccolti.** Un mese di tick ti dà la
distribuzione di DVOL nel TUO regime (testnet vs mainnet, bull vs
bear). I percentili P25/P50/P75 nella pagina `📐 Calibrazione`
dicono se 35 è davvero il "fondo" o se andrebbe alzato.
### 2.2 — Funding rate (perpetual + cross-exchange median)
**Cosa misura.** Il funding annualizzato del perpetual ETH-PERP
(Hyperliquid principalmente) e la mediana dei funding sui 4 maggiori
exchange. Il funding è la fee periodica che paga il lato sbilanciato
del perp: **è il termometro più diretto del posizionamento leveraged
del mercato.**
**Come la usa l'engine.**
- §2.6: `funding_perp_abs_max_annualized = 0.80` — funding > 80%
annualizzato (in valore assoluto) = liquidazioni a cascata
imminenti, no entry.
- §3.1: il **bias direzionale** dipende dal funding cross:
- `funding_bull_threshold_annualized = 0.20` ⇒ bias bull se
cross-funding ≥ +20%.
- `funding_bear_threshold_annualized = -0.20` ⇒ bias bear se
≤ -20%.
- In mezzo + trend neutro = candidato Iron Condor.
- Trend e funding discordi = no entry.
**Perché due funding diversi.** Il perp di Hyperliquid è il segnale
"è esecutibile la chiusura?" (l'ETH-PERP è la sede di hedge
pratico). La mediana cross-exchange è il segnale macro
"dove sta il mercato globale": più robusta a manipolazioni o picchi
locali.
### 2.3 — Dealer gamma (net gamma + flip level)
**Cosa misura.** L'esposizione netta di gamma dei dealer di opzioni
su Deribit, ricostruita da OI per strike e direzione. Quando
`dealer_net_gamma > 0` (long gamma), i dealer **sopprimono** la
volatilità realizzata col loro hedge (vendono salendo, comprano
scendendo). Quando è negativo, **amplificano** ogni movimento.
**Come la usa l'engine.**
- §2.8: `dealer_gamma_min = 0`, `dealer_gamma_filter_enabled = true`
— entry solo in regime long-gamma. Vendere credit spread con
dealer corto-gamma è statisticamente perdente.
- `gamma_flip_level` è il prezzo spot al quale il regime cambierebbe.
Se siamo a 1% dal flip, il margine di sicurezza è basso anche se
il segno è positivo.
**Cosa si calibra dai dati raccolti.** La distribuzione di
`dealer_net_gamma` nel proprio universo (qualche miliardo USD su
mainnet, ordini di grandezza diversi su testnet) suggerisce se
`min = 0` è troppo permissivo — su mainnet è frequente che il segno
si trovi positivo per molto tempo, qui ha senso una soglia più alta.
### 2.4 — Liquidation heatmap (OI delta + long/short squeeze risk)
**Cosa misura.** Da `mcp-sentiment`:
- `oi_delta_pct_4h`: variazione % dell'open interest aggregato nelle
ultime 4h. Spike positivo → leverage in entrata (rischio fragile);
spike negativo → squeeze appena avvenuta.
- `liquidation_long_risk` / `liquidation_short_risk`: classificazione
qualitativa (`low` / `med` / `high`) della densità di livelli di
liquidazione vicini allo spot.
**Come la usa l'engine.**
- §2.8 (`liquidation_filter_enabled = true`): l'entry cycle scarta
setup con `_risk = high` sul lato che ci interesserebbe (es. un
bull put spread in regime di `long_risk = high` è esposto a un
long-squeeze giù).
- Anche fuori dall'entry, queste due colonne servono come "filtro di
realtà" per il monitoring: se durante la posizione lo squeeze risk
cambia da low a high, è un primo segnale di vol-stop in arrivo.
### 2.5 — Macro calendar (giorni al prossimo evento)
**Cosa misura.** `mcp-macro` restituisce il numero di giorni al
prossimo evento ad alta severità (FOMC, CPI USA, NFP, ECB, Powell
speech) per US/EU. `NULL` = nessun evento entro la finestra DTE.
**Come la usa l'engine.**
- §2.5: se `macro_days_to_event ≤ dte_target = 18`, no entry. Le
uscite macro si trasformano in gap di volatilità che mangiano in
un'ora il credito di tre settimane.
- Le entry sono comunque possibili poco dopo l'evento (vol elevata
appena dopo + RV destinata a comprimersi → IVRV alto = setup di
scuola).
### 2.6 — Spot ETH (e BTC come controllo)
**Cosa misura.** Prezzo last/perp di ETH (e BTC come controllo).
**Come la usa l'engine.**
- §3.1: trend 30g calcolato come `(spot_now / spot_30g_ago - 1)`.
Soglie ±5% definiscono bias bull / bear / neutro.
- §3.2: distanza % degli strike short dallo spot (1525% OTM).
- §7.6: `adverse_move_4h_pct = 0.05` — close su movimento contrario
≥ 5% in 4h.
**Perché anche BTC.** ETH è il sottostante operativo, BTC è il
**termometro macro crypto**: in regimi di alta correlazione, un
movimento BTC che ETH non sta seguendo è un segnale di divergenza che
spesso precede un riallineamento brusco.
---
## 3. Il flusso decisionale, allineato al dato
Quanto segue è la versione "leggibile" delle regole §2-§9 di
`01-strategy-rules.md`. Ogni passo cita i campi di
`market_snapshots` che lo alimentano.
### Fase 1 — Trigger (lunedì 14:00 UTC, festività italiane escluse)
```
SE NESSUNA posizione aperta
E capitale ≥ 720 USD
E 35 ≤ dvol ≤ 90 # market_snapshots.dvol
E |funding_perp_annualized| ≤ 0.80 # market_snapshots.funding_perp_annualized
E macro_days_to_event > dte_target (oppure NULL) # market_snapshots.macro_days_to_event
E ETH holdings cerbero-portfolio ≤ 30%
E (filtri quant: dealer_net_gamma > 0,
liquidation_*_risk ≠ high) # market_snapshots.dealer_net_gamma + liquidation_*
ALLORA
procedi alla Fase 2
ALTRIMENTI
no entry, log motivo, ritento la settimana successiva
```
### Fase 2 — Bias e struttura
```
trend_30g = spot_now / spot_30g_ago - 1 # market_snapshots.spot
funding_x = funding_cross_annualized # market_snapshots.funding_cross_annualized
SE trend_30g ≥ +5% E funding_x ≥ +20%:
struttura = Bull Put Spread
SE trend_30g ≤ -5% E funding_x ≤ -20%:
struttura = Bear Call Spread
SE |trend_30g| < 5% E |funding_x| < 20%
E dvol ≥ 55 E ADX(14) < 20:
struttura = Iron Condor
ALTRIMENTI:
no entry (mercato indeciso o discordante)
```
### Fase 3 — Selezione strike (delta-target + distanza % spot)
Lo strike short è quello a delta target ≈ 0.12 (tolleranza 0.100.15)
**e** OTM 1525%. Lo strike long è a 4% del spot (35% accettabile).
Tutti i numeri sono parametrizzati in `strategy.yaml > structure`.
Lo `spot` corrente per il calcolo viene da `market_snapshots.spot`.
### Fase 4 — Sizing (Kelly frazionario + cap aggregato + DVOL clamp)
```
risk_target = capitale * 0.13 # quarter Kelly
risk_target = min(risk_target, 200 EUR) # cap per-trade
n = floor(risk_target / max_loss_per_contract)
n = min(n, 4, vincolo aggregato 1000 EUR)
n = round_down(n * dvol_multiplier) # market_snapshots.dvol → §5.3
```
### Fase 5 — Esecuzione (combo limit GTC al mid)
Limit al mid del combo, riprezzamento +1 tick / 30min fino a 3 step.
Su trigger urgenti (CLOSE_STOP / CLOSE_VOL / CLOSE_DELTA) l'engine
accetta fino a 5 step di slippage perché l'urgenza prevale sul
prezzo.
### Fase 6 — Monitoring (cron di gestione attiva, default ogni 12h)
Per ogni posizione aperta, in **ordine** (primo trigger vince):
| # | Trigger | Dato sorgente |
|---|---|---|
| 1 | Profit take: mark ≤ 50% credito | combo mark via deribit |
| 2 | Stop loss: mark ≥ 250% credito | combo mark via deribit |
| 3 | Vol stop: dvol_now ≥ dvol_entry + 10 | `market_snapshots.dvol` |
| 4 | Time stop: dte ≤ 7 (skip se ≥ 70% profit) | scadenza struttura |
| 5 | Delta breach: \|delta_short\| ≥ 0.30 | option chain via deribit |
| 6 | Adverse move: \|return_4h_ETH\| ≥ 5% contro | `market_snapshots.spot` |
| 7 | Altrimenti | HOLD |
Il monitoring NON consulta `market_snapshots` per i prezzi opzioni
(legge live), ma li consulta per `dvol` e `spot` con il vantaggio di
una serie storica già normalizzata e auditabile.
---
## 4. Cosa fa OGGI il bot in modalità "data-only"
Il bot oggi è in **modalità raccolta dati** (`ENABLE_DATA_ANALYSIS=true`,
`ENABLE_STRATEGY=false`). Vuol dire:
- Il job `market_snapshot` (cron `*/15`) gira: scrive nuove righe in
SQLite, alimenta calibrazione e monitoring storico.
- Il job `health` (`*/5`) verifica disponibilità MCP e ambiente
Deribit; alza il kill switch se qualcosa non torna.
- Il job `backup` (`0 *`) snapshotta lo stato ogni ora.
- Il job `manual_actions` (`*/1`) consuma comandi dalla GUI.
- I cicli `entry` e `monitor` **non sono nemmeno schedulati**: nessun
ordine può partire, nessuno strike viene letto.
Quando si vuole passare alla fase operativa (paper trading o
mainnet), basta:
1. Riempire `strategy.yaml` con le **soglie calibrate** sui
percentili reali della pagina `📐 Calibrazione` (non lasciare i
valori default a istinto).
2. Bumpare `config_version` + rigenerare `config_hash` con
`cerbero-bite config hash --file strategy.yaml`.
3. Settare `ENABLE_STRATEGY=true` in `.env` e ricreare il container.
4. Disarmare il kill switch da GUI o CLI con motivazione esplicita.
5. **Una settimana di paper trading** (mainnet con ordini disabilitati
o testnet) prima di alzare il flag definitivo.
---
## 4-bis. P/L atteso (realistico)
I numeri qui sotto sono **stime ex-ante**, non promesse. Servono ad
allineare le aspettative con la geometria della strategia: capire
**quanto poco si rischia per trade**, **quanto raramente si entra**, e
**perché l'edge è strutturalmente sottile**.
> **Domanda onesta che chiunque guardi i numeri dovrebbe farsi:** se a
> win-rate 7072% l'aspettativa per trade è circa zero, **che senso ha
> la strategia?**
>
> **Risposta:** il selling vol nudo è effettivamente neutro a quel
> win-rate. **L'edge della Cerbero Bite non è "vendere vol"; è
> "vendere vol solo quando i filtri quant alzano il win-rate sopra il
> 75%".** I gate §2 (DVOL band, dealer gamma > 0, no macro entro DTE,
> liquidation risk ≠ high, bias trend × funding concorde) sono
> **costruiti per saltare proprio le finestre statisticamente
> perdenti** e operare solo in quelle favorevoli. La pagina
> `📚 Strategia` ha una tabella di sensibilità che mostra come l'APR
> passa da ≈0% (win 0.72) a +3-5% (win 0.780.80): è esattamente la
> distanza che i filtri devono coprire. Per questo i primi giorni di
> raccolta dati servono a **misurare** se i filtri stanno effettivamente
> alzando il win-rate prima di committare capitale.
### Per singolo trade (riferimento: ETH spot ≈ 3000 USD)
| Voce | Formula / fonte | Valore tipico |
|---|---|---|
| Larghezza spread | 4% × spot | **120 USD / contratto** |
| Credito incassato | ≥ 30% × larghezza | **3648 USD / contratto** |
| Max profit teorico | = credito (a scadenza OTM) | 3648 USD / contratto |
| **Profit-take §7.1 (50% credito)** | 0.5 × credito | **+1824 USD / contratto** |
| **Stop-loss §7.2 (mark = 2.5× credito)** | 1.5 × credito | **5472 USD / contratto** |
| Margine bloccato | ≈ larghezza | 120 USD / contratto |
| Fees Deribit | 0.03% notional × 2 leg | ~12 USD / contratto / trade |
> Su spot più basso (2000 USD) la larghezza scende a 80 USD/contratto
> e i numeri assoluti seguono proporzionalmente.
### Sizing tipico vs capitale
Il sizing è governato dal Quarter-Kelly **+ cap per-trade 200 EUR
(~215 USD)**. Sopra una certa soglia, il cap domina: alzare il
capitale **non aumenta** i contratti per trade.
| Capitale | risk_target (Kelly) | risk effettivo (post-cap) | Contratti tipici (spot=3000) |
|---|---|---|---|
| 720 USD (minimo) | 94 USD | 94 USD | **01** (entry spesso saltata per sizing) |
| 1 500 USD | 195 USD | 195 USD | **1** |
| 3 000 USD | 390 USD | **215 USD** (cap) | **1** |
| 10 000 USD | 1 300 USD | **215 USD** (cap) | **1** |
| 50 000 USD+ | 6 500 USD | **215 USD** (cap) | **1** (cap aggregato 1 075 USD = max 4 trade aperti, ma `max_concurrent_positions: 1`) |
> Con i cap correnti la strategia è **dimensionata per capitale
> piccolo (1.510 k USD)**: oltre, il rendimento sul totale scala
> sotto-lineare e tende a zero.
### Frequenza realistica di entry
La regola si valuta una volta a settimana, ma la maggioranza dei
lunedì viene saltata per:
| Motivo di skip | Frequenza tipica |
|---|---|
| DVOL fuori banda (3590) | 2540% |
| Bias non chiaro (trend × funding discordi o entrambi neutri senza IC) | 2535% |
| Macro entro DTE | 1020% |
| Funding o liquidation risk fuori soglia | 515% |
| Capitale o sizing insufficiente | 05% |
**Risultato netto: 3050% delle settimane finisce in entry effettiva
⇒ 1525 trade / anno** (52 lunedì × 3050%). Le altre settimane il
bot sta fermo. È il design.
### Win-rate atteso (short delta 0.12 + profit-take 50%)
Letteratura e backtest su credit spread short delta 0.100.15 con
TP@50% e SL@1.5×:
| Esito | Probabilità tipica | Risultato |
|---|---|---|
| Profit-take a 50% credito | **~7075%** | +1824 USD/contratto |
| Stop-loss a 1.5× credito | ~1520% | 5472 USD/contratto |
| Time-stop o exit DTE 7g | ~510% | piccolo positivo (~+510 USD) |
| Vol/delta/macro stop | ~35% | variabile, mediamente neutro |
Atteso medio per contratto:
```
E[trade] ≈ 0.72 × 21 + 0.18 × (-63) + 0.07 × 7 + 0.03 × 0
≈ 15.1 11.3 + 0.5 + 0
≈ +4.3 USD lordi / contratto
```
**Al netto di fees (~1.5 USD round-trip) e slippage (~5% del credito
≈ 2 USD): E[trade] ≈ +13 USD per contratto.**
### Proiezione annuale (1 contratto medio per trade)
| Scenario | Trade/anno | E[trade] netto | P/L lordo annuo | Su capitale 1 500 USD | Su capitale 3 000 USD |
|---|---|---|---|---|---|
| **Pessimistico** (vol bassa, regime bear vol) | 12 | +1 USD | **+12 USD** | +0.8% | +0.4% |
| **Realistico medio** | 18 | +2.5 USD | **+45 USD** | +3% | +1.5% |
| **Buono** (regime favorevole, IVRV alto) | 22 | +4 USD | **+88 USD** | +5.9% | +2.9% |
| **Eccellente** (cherry-picking ex-post) | 25 | +6 USD | **+150 USD** | +10% | +5% |
**Realisticamente: +1.5% / +5% APR sul capitale totale**, con i cap
correnti. È in linea con la letteratura su short-vol systematic con
disciplina di stop. **Non è una strategia "raddoppia il capitale".**
È una strategia che vuole guadagnare il **premio di rischio della
volatilità** in modo controllato.
### Drawdown e rischio coda
- **Streak realistico di perdite consecutive**: 35 stop-loss di fila
capitano. Drawdown su 1 contratto: 150 / 300 USD assoluti.
- **Su capitale 1 500 USD** = drawdown del 1020% del capitale
totale. Aspettarselo, è dentro il design.
- **Tail risk:** un evento gap notturno (sentenza SEC, hack
exchange, default importante) può portare il mark a 100% della
larghezza prima che lo stop sia eseguibile. **Perdita massima
reale per trade = larghezza intera** (`width - credit_iniziale`),
cioè 7296 USD/contratto, non i 5472 USD del modello stop-loss.
- I **filtri quant** (`dealer_gamma_min`, `liquidation_filter`) e
il **macro filter** sono stati introdotti **per ridurre la coda**,
non per migliorare l'aspettativa media.
### Sharpe atteso
Strategie short-vol sistematiche con disciplina hanno:
- **Sharpe 0.81.5** in regimi favorevoli (mercato lento + IV alta).
- **Sharpe 0.30.8** in regimi normali.
- **Sharpe negativo** in regimi di vol-of-vol (es. Q1 2020, Maggio
2021, FTX week). I filtri li mitigano, non li annullano.
### Cosa cambia con `ENABLE_STRATEGY=true`
In modalità data-only (oggi) il P/L atteso è **0** — l'engine
**non opera**. Il valore della raccolta di oggi è:
1. **Calibrare** soglie su percentili reali → P/L atteso più
realistico al go-live.
2. **Validare** i filtri quant osservando ex-post quanti tick
sarebbero stati filtrati (vedi pagina `📐 Calibrazione`, colonna
"% bloccato dalla soglia").
3. **Misurare** la quota effettiva di lunedì che superano i filtri
nel proprio regime, prima di committare capitale.
> Suggerimento: 4 settimane di dati = 4 lunedì × probabilità entry =
> 12 candidate entry effettive. **Aspettare almeno 8 settimane**
> prima di tarare le soglie dà uno storico con dispersione
> sufficiente per decisioni non-rumorose.
---
## 4-ter. Due profili: Conservativa vs Aggressiva
Il P/L del §4-bis assume i cap della golden config v1.0.0
(`cap_per_trade_eur: 200`, `max_concurrent_positions: 1`,
`max_contracts_per_trade: 4`). Su quel profilo il P/L assoluto è
piccolo per design — la strategia è dimensionata come **macchina di
conservazione del capitale** con premio modesto su T-bill.
Per chi vuole rendimenti significativi, il repo include un secondo
file di config — `strategy.aggressiva.yaml` — che **deroga
esplicitamente** alla §11 di `01-strategy-rules.md` allargando le tre
leve dominanti:
| Leva | Conservativa | Aggressiva | Effetto sul P/L |
|---|---|---|---|
| `cap_per_trade_eur` | 200 | **800** | 4× la size per trade |
| `cap_aggregate_open_eur` | 1 000 | **3 200** | 4× il rischio aggregato |
| `max_concurrent_positions` | 1 | **2** | 2× le posizioni aperte simultanee |
| `max_contracts_per_trade` | 4 | **16** | toglie il vincolo aggregato anche su capitali maggiori |
| `kelly_fraction` | 0.13 | **0.13** | invariato (la disciplina Kelly resta) |
| Filtri quant (gamma, liquidation, macro) | ON | **ON** | invariati (l'edge è qui, non si tocca) |
**Risultato atteso (a parità di filtri e win-rate):** P/L ≈ 48× il
profilo conservativo. Drawdown atteso scala con lo stesso fattore
(2040% del capitale impiegato in streak avverse, contro 1020% del
conservativo). La pagina `📚 Strategia` ha un pannello affiancato che
calcola entrambi sugli stessi slider.
**Il rovescio della medaglia.**
- La deroga alla §11 va **autorizzata esplicitamente** nel commit che
switcha la config; tre settimane di paper trading dedicato sono
raccomandate.
- Il drawdown maggiore richiede capitale "growth", non capitale di
parcheggio.
- I filtri quant restano **identici** — non c'è "più aggressivo" sui
trigger di entry, perché lì non c'è alpha da spremere senza
peggiorare il win-rate.
**Multi-asset (ETH + BTC) — caveat.**
L'ulteriore moltiplicatore 2× citato nel §4-bis (multi-asset) **non è
abilitato** dalla sola modifica della config: il rule engine attuale è
single-asset (`asset.symbol`). Per estenderlo servono modifiche in:
- `cerbero_bite/runtime/entry_cycle.py` (loop sui simboli)
- `cerbero_bite/state/repository.py` (multi-position chiave per asset)
- `cerbero_bite/runtime/orchestrator.py` (scheduler one-asset → N)
Il job di raccolta dati è già multi-asset (`DEFAULT_ASSETS = ("ETH",
"BTC")`), quindi tutto il dataset utile per validare l'estensione è
già disponibile. È un lavoro di codice ben circoscritto, da fare in
un branch dedicato dopo che il dataset di calibrazione è abbondante.
**Quando passare dal profilo conservativo all'aggressivo.**
Solo se **tutte** le seguenti sono vere:
1. ≥ 8 settimane di dati raccolti su mainnet (≥ ~2k snapshot).
2. Win-rate empirico misurato (paper trading o backtest sui tick
raccolti) **≥ 0.75**.
3. APR atteso del profilo aggressivo (vedi pannello GUI) **≥ 8%**
netto a quel win-rate.
4. Capitale impegnato è **growth capital**, non riserva tattica.
5. Sopporti emotivamente un drawdown a doppia cifra senza disarmare
manualmente la strategia in mezzo a una streak.
Se anche solo uno dei 5 manca → **resta sulla conservativa**, è
quella che il sistema parte ad eseguire.
---
## 5. Come leggere il dato giorno per giorno
Tre euristiche operative sui campi raccolti:
1. **Premio "ricco":** `iv_minus_rv` consistentemente > 5 punti per
N giorni → il regime sta pagando bene la vendita di vol. Sono i
periodi in cui la strategia ha edge maggiore.
2. **Premio "magro":** `dvol < 35` per più giorni → la finestra del
lunedì viene saltata. Non è un fallimento: è la disciplina che
funziona.
3. **Stress imminente:** `liquidation_*_risk = high` o spike di
`oi_delta_pct_4h` (> 5% in valore assoluto) + funding ai limiti
→ atteso vol stop / time stop attivi nei prossimi cicli, anche
se la posizione è in profit.
Nei giorni di **eventi macro** (`macro_days_to_event` piccolo) la
combinazione utile è: aspettare l'evento, lasciare che `dvol` scenda
quando `realized_vol_30d` non si è realizzata, e cogliere il setup
classico **post-evento**.
---
## 6. Glossario rapido
- **Credit spread:** vendita di un'opzione e acquisto di un'opzione
più OTM stessa scadenza per cap del rischio. Si incassa un credito,
si vince se il sottostante non rompe lo strike short.
- **Bull put / Bear call:** credit spread direzionali (rispettivamente
bullish / bearish).
- **Iron condor:** Bull put + bear call sullo stesso sottostante e
scadenza. Si vince in regime laterale.
- **DVOL:** indice Deribit della IV ETM 30g, scala 0200.
- **Realized vol 30g:** σ annualizzata dei rendimenti spot sui 30g
rolling.
- **IV RV:** differenza tra IV implicita (DVOL) e RV; > 0 = "premio"
positivo per il venditore di vol.
- **Funding annualizzato:** funding rate del perp moltiplicato per le
finestre standard (di solito 8h × 3 al giorno × 365).
- **Dealer net gamma:** somma di gamma per tutti gli strike, pesata
per direzione dei dealer (long = riduce vol, short = amplifica).
- **OI delta % 4h:** variazione % dell'open interest aggregato nelle
ultime 4 ore.
- **DTE:** Days To Expiry, giorni alla scadenza dell'opzione.
- **Kill switch:** flag persistente che blocca apertura di nuove
posizioni; armato automaticamente su mismatch ambiente o failure
ripetuti, disarmato solo manualmente con motivazione.
---
## 7. Riferimenti incrociati
- Regole canoniche e immutabili: `01-strategy-rules.md`
- Schema dati persistente: `05-data-model.md`
- Algoritmi (calcolo trend, IVRV, ecc.): `03-algorithms.md`
- Dettaglio integrazioni MCP: `04-mcp-integration.md`
- Pagina GUI di calibrazione: `📐 Calibrazione`
- Sorgente del collector: `src/cerbero_bite/runtime/market_snapshot_cycle.py`
- Modello pydantic riga: `cerbero_bite.state.models.MarketSnapshotRecord`
+94
View File
@@ -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): class ShortStrikeSpec(BaseModel):
model_config = ConfigDict(frozen=True, extra="forbid") 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_min: Decimal = Field(default=Decimal("0.15"))
distance_otm_pct_max: Decimal = Field(default=Decimal("0.25")) 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): class SpreadWidthSpec(BaseModel):
model_config = ConfigDict(frozen=True, extra="forbid") 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): class ExitConfig(BaseModel):
model_config = ConfigDict(frozen=True, extra="forbid") model_config = ConfigDict(frozen=True, extra="forbid")
@@ -176,6 +216,29 @@ class ExitConfig(BaseModel):
delta_breach_threshold: Decimal = Field(default=Decimal("0.30")) delta_breach_threshold: Decimal = Field(default=Decimal("0.30"))
adverse_move_4h_pct: Decimal = Field(default=Decimal("0.05")) 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 * * *" monitor_cron: str = "0 2,14 * * *"
user_confirmation_timeout_min: int = 30 user_confirmation_timeout_min: int = 30
escalate_on_timeout: list[str] = Field( 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 # Kelly recalibration
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
@@ -256,6 +349,7 @@ class StrategyConfig(BaseModel):
sizing: SizingConfig = Field(default_factory=SizingConfig) sizing: SizingConfig = Field(default_factory=SizingConfig)
exit: ExitConfig = Field(default_factory=ExitConfig) exit: ExitConfig = Field(default_factory=ExitConfig)
kelly_recalibration: KellyConfig = Field(default_factory=KellyConfig) kelly_recalibration: KellyConfig = Field(default_factory=KellyConfig)
auto_pause: AutoPauseConfig = Field(default_factory=AutoPauseConfig)
execution: ExecutionConfig = Field(default_factory=ExecutionConfig) execution: ExecutionConfig = Field(default_factory=ExecutionConfig)
monitoring: MonitoringConfig = Field(default_factory=MonitoringConfig) monitoring: MonitoringConfig = Field(default_factory=MonitoringConfig)
+27 -3
View File
@@ -83,26 +83,49 @@ def _pick_expiry(
return min(candidates, key=lambda exp: abs(candidates[exp] - sc.dte_target)) 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( def _select_short(
quotes: list[OptionQuote], quotes: list[OptionQuote],
*, *,
spot: Decimal, spot: Decimal,
cfg: StrategyConfig, cfg: StrategyConfig,
dvol_now: Decimal | None = None,
) -> OptionQuote | None: ) -> OptionQuote | None:
"""Pick the short-leg quote with delta closest to target inside both bands.""" """Pick the short-leg quote with delta closest to target inside both bands."""
sc = cfg.structure.short_strike sc = cfg.structure.short_strike
delta_target, delta_min, delta_max = _resolve_delta_band(sc, dvol_now)
eligible: list[OptionQuote] = [] eligible: list[OptionQuote] = []
for q in quotes: for q in quotes:
dist = (q.strike - spot).copy_abs() / spot dist = (q.strike - spot).copy_abs() / spot
if not (sc.distance_otm_pct_min <= dist <= sc.distance_otm_pct_max): if not (sc.distance_otm_pct_min <= dist <= sc.distance_otm_pct_max):
continue continue
abs_delta = q.delta.copy_abs() 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 continue
eligible.append(q) eligible.append(q)
if not eligible: if not eligible:
return None 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( def _select_long(
@@ -143,6 +166,7 @@ def select_strikes(
spot: Decimal, spot: Decimal,
now: datetime, now: datetime,
cfg: StrategyConfig, cfg: StrategyConfig,
dvol_now: Decimal | None = None,
) -> tuple[OptionQuote, OptionQuote] | None: ) -> tuple[OptionQuote, OptionQuote] | None:
"""Return the (short, long) quotes for the requested vertical, or ``None``. """Return the (short, long) quotes for the requested vertical, or ``None``.
@@ -161,7 +185,7 @@ def select_strikes(
if not typed: if not typed:
return None 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: if short is None:
return None return None
+18
View File
@@ -28,8 +28,10 @@ __all__ = ["ExitAction", "ExitDecisionResult", "PositionSnapshot", "evaluate"]
ExitAction = Literal[ ExitAction = Literal[
"HOLD", "HOLD",
"CLOSE_PROFIT", "CLOSE_PROFIT",
"CLOSE_PROFIT_PARTIAL",
"CLOSE_STOP", "CLOSE_STOP",
"CLOSE_VOL", "CLOSE_VOL",
"CLOSE_VOL_HARVEST",
"CLOSE_TIME", "CLOSE_TIME",
"CLOSE_DELTA", "CLOSE_DELTA",
"CLOSE_AVERSE", "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}", 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 # 2. Stop loss
if debit >= stop_thresh: if debit >= stop_thresh:
return _result( return _result(
@@ -0,0 +1,846 @@
"""Strategia page — documento operativo + lettura live dei segnali.
Renderizza il documento canonico ``docs/13-strategia-spiegata.md`` e
sopra di esso un pannello che mostra l'ultimo tick di
``market_snapshots`` confrontato con le soglie di ``strategy.yaml``.
Lo scopo è far vedere subito, ogni volta che si apre la pagina:
"a cosa serve il dato che il bot sta raccogliendo adesso".
La pagina è di sola lettura: non chiama MCP, non scrive sul DB.
"""
from __future__ import annotations
import os
from dataclasses import dataclass
from pathlib import Path
import streamlit as st
from cerbero_bite.config.loader import load_strategy
from cerbero_bite.gui.data_layer import (
DEFAULT_DB_PATH,
humanize_dt,
load_market_snapshots,
)
from cerbero_bite.state.models import MarketSnapshotRecord
_DOC_FILENAME = "13-strategia-spiegata.md"
_DOC_CANDIDATES: tuple[Path, ...] = (
Path("/app/docs") / _DOC_FILENAME, # in-container shipped via Dockerfile
Path(__file__).resolve().parents[4] / "docs" / _DOC_FILENAME, # repo dev
Path(__file__).resolve().parents[3] / "docs" / _DOC_FILENAME,
)
def _resolve_db() -> Path:
return Path(os.environ.get("CERBERO_BITE_GUI_DB", DEFAULT_DB_PATH))
def _load_doc() -> str | None:
for candidate in _DOC_CANDIDATES:
if candidate.is_file():
try:
return candidate.read_text(encoding="utf-8")
except OSError:
continue
return None
@dataclass(frozen=True)
class _GateRow:
label: str
value: str
threshold: str
status: str # "pass" | "fail" | "n/a"
note: str = ""
def _fmt_decimal(v: object, *, fmt: str = "{:.4g}", suffix: str = "") -> str:
if v is None:
return ""
try:
return fmt.format(float(v)) + suffix
except (TypeError, ValueError):
return ""
def _build_gates(
snap: MarketSnapshotRecord, strategy: object
) -> list[_GateRow]:
"""Costruisce le righe del pannello live dai gate §2 della strategia."""
rows: list[_GateRow] = []
entry = getattr(strategy, "entry", None)
structure = getattr(strategy, "structure", None)
# --- DVOL band -------------------------------------------------
dvol_min = float(getattr(entry, "dvol_min", 35.0)) if entry else 35.0
dvol_max = float(getattr(entry, "dvol_max", 90.0)) if entry else 90.0
dvol_v = float(snap.dvol) if snap.dvol is not None else None
if dvol_v is None:
rows.append(
_GateRow(
"DVOL in banda 3590",
"",
f"{dvol_min:.0f} ≤ DVOL ≤ {dvol_max:.0f}",
"n/a",
"Dato non disponibile in questo tick.",
)
)
else:
ok = dvol_min <= dvol_v <= dvol_max
rows.append(
_GateRow(
"DVOL in banda",
f"{dvol_v:.2f}",
f"{dvol_min:.0f}{dvol_max:.0f}",
"pass" if ok else "fail",
"Premio adeguato e regime non-stress."
if ok
else "Sotto banda = premio magro; sopra = stress, no entry.",
)
)
# --- Funding perp annualized ----------------------------------
fund_max = (
float(getattr(entry, "funding_perp_abs_max_annualized", 0.80))
if entry
else 0.80
)
fp = (
float(snap.funding_perp_annualized)
if snap.funding_perp_annualized is not None
else None
)
if fp is None:
rows.append(
_GateRow(
"Funding perp |·| ≤ soglia",
"",
f"|f| ≤ {fund_max:.0%}",
"n/a",
)
)
else:
ok = abs(fp) <= fund_max
rows.append(
_GateRow(
"Funding perp |·|",
f"{fp:+.2%}",
f"{fund_max:.0%}",
"pass" if ok else "fail",
"Filtra regimi di liquidazioni a cascata imminenti.",
)
)
# --- Cross-exchange funding (bias) ---------------------------
bull_th = (
float(getattr(entry, "funding_bull_threshold_annualized", 0.20))
if entry
else 0.20
)
bear_th = (
float(getattr(entry, "funding_bear_threshold_annualized", -0.20))
if entry
else -0.20
)
fc = (
float(snap.funding_cross_annualized)
if snap.funding_cross_annualized is not None
else None
)
if fc is None:
bias_funding = ""
rows.append(
_GateRow(
"Funding cross (bias)",
"",
f"bull ≥ {bull_th:+.0%} · bear ≤ {bear_th:+.0%}",
"n/a",
)
)
else:
if fc >= bull_th:
bias_funding = "BULL"
elif fc <= bear_th:
bias_funding = "BEAR"
else:
bias_funding = "NEUTRO"
rows.append(
_GateRow(
"Funding cross (bias)",
f"{fc:+.2%}{bias_funding}",
f"bull ≥ {bull_th:+.0%} · bear ≤ {bear_th:+.0%}",
"pass" if bias_funding != "NEUTRO" else "fail",
"Mediana 4 maggiori exchange. Discordante col trend = no entry.",
)
)
# --- Macro days to event --------------------------------------
dte_target = (
int(getattr(structure, "dte_target", 18)) if structure else 18
)
macro_d = snap.macro_days_to_event
if macro_d is None:
rows.append(
_GateRow(
"Macro fuori finestra DTE",
"nessun evento",
f"> {dte_target}g",
"pass",
"Nessun evento ad alta severità entro la scadenza target.",
)
)
else:
ok = macro_d > dte_target
rows.append(
_GateRow(
"Macro fuori finestra DTE",
f"{macro_d} g al prossimo",
f"> {dte_target} g",
"pass" if ok else "fail",
"FOMC/CPI/NFP/ECB/Powell entro DTE = no entry.",
)
)
# --- Dealer gamma ---------------------------------------------
gamma_min = (
float(getattr(entry, "dealer_gamma_min", 0.0)) if entry else 0.0
)
gamma_enabled = (
bool(getattr(entry, "dealer_gamma_filter_enabled", True))
if entry
else True
)
g = (
float(snap.dealer_net_gamma)
if snap.dealer_net_gamma is not None
else None
)
if not gamma_enabled:
rows.append(
_GateRow(
"Dealer gamma filter",
_fmt_decimal(g, fmt="{:,.0f}", suffix=" USD")
if g is not None
else "",
"filtro DISABILITATO",
"n/a",
)
)
elif g is None:
rows.append(
_GateRow(
"Dealer net gamma > soglia",
"",
f"> {gamma_min:,.0f} USD",
"n/a",
)
)
else:
ok = g > gamma_min
rows.append(
_GateRow(
"Dealer net gamma",
f"{g:,.0f} USD",
f"> {gamma_min:,.0f} USD",
"pass" if ok else "fail",
"Long-gamma regime sopprime la vol → ideale per vendere spread.",
)
)
# --- Liquidation risks ----------------------------------------
liq_enabled = (
bool(getattr(entry, "liquidation_filter_enabled", True))
if entry
else True
)
long_r = snap.liquidation_long_risk or ""
short_r = snap.liquidation_short_risk or ""
lr_status = "n/a"
if liq_enabled and snap.liquidation_long_risk and snap.liquidation_short_risk:
worst = max(
("low", "med", "high").index(snap.liquidation_long_risk)
if snap.liquidation_long_risk in ("low", "med", "high")
else 0,
("low", "med", "high").index(snap.liquidation_short_risk)
if snap.liquidation_short_risk in ("low", "med", "high")
else 0,
)
lr_status = "fail" if worst == 2 else "pass"
rows.append(
_GateRow(
"Liquidation risk (long / short)",
f"{long_r} / {short_r}",
"non `high`" if liq_enabled else "filtro DISABILITATO",
lr_status,
"Densità liquidazioni vicine al spot. `high` su un lato = scarta setup.",
)
)
# --- IV RV (richness) — solo informativo --------------------
rv = (
float(snap.realized_vol_30d) if snap.realized_vol_30d is not None else None
)
iv_minus_rv = (
float(snap.iv_minus_rv) if snap.iv_minus_rv is not None else None
)
rows.append(
_GateRow(
"IV RV (richness)",
(
f"{iv_minus_rv:+.2f} pt vol"
if iv_minus_rv is not None
else ""
),
"info, > 0 = premio ricco",
"pass" if (iv_minus_rv is not None and iv_minus_rv > 0) else "n/a",
f"RV30={rv:.2f}" if rv is not None else "",
)
)
return rows
def _render_gates(rows: list[_GateRow]) -> None:
icons = {"pass": "", "fail": "", "n/a": ""}
for r in rows:
icon = icons.get(r.status, "")
col1, col2, col3 = st.columns([4, 4, 4])
col1.markdown(f"{icon} **{r.label}**")
col2.markdown(f"`{r.value}`")
col3.markdown(f"_{r.threshold}_")
if r.note:
st.caption(r.note)
st.divider()
def _profile_caps(strategy: object | None) -> dict[str, float]:
"""Estrae le sole leve di sizing da una strategia (o usa default conservativi)."""
out = {
"cap_pertrade_eur": 200.0,
"cap_aggregate_eur": 1000.0,
"kelly": 0.13,
"max_n": 4.0,
"max_concurrent": 1.0,
"width_pct": 0.04,
"credit_ratio": 0.30,
"profit_take": 0.50,
"stop_mult": 2.50,
}
if strategy is None:
return out
try:
out["cap_pertrade_eur"] = float(strategy.sizing.cap_per_trade_eur) # type: ignore[attr-defined]
out["cap_aggregate_eur"] = float(strategy.sizing.cap_aggregate_open_eur) # type: ignore[attr-defined]
out["kelly"] = float(strategy.sizing.kelly_fraction) # type: ignore[attr-defined]
out["max_n"] = float(strategy.sizing.max_contracts_per_trade) # type: ignore[attr-defined]
out["max_concurrent"] = float(strategy.sizing.max_concurrent_positions) # type: ignore[attr-defined]
out["width_pct"] = float(strategy.structure.spread_width.target_pct_of_spot) # type: ignore[attr-defined]
out["credit_ratio"] = float(strategy.structure.credit_to_width_ratio_min) # type: ignore[attr-defined]
out["profit_take"] = float(strategy.exit.profit_take_pct_of_credit) # type: ignore[attr-defined]
out["stop_mult"] = float(strategy.exit.stop_loss_mark_x_credit) # type: ignore[attr-defined]
except Exception:
pass
return out
def _detect_features(strategy: object | None) -> dict[str, bool]:
"""Quali miglioramenti del PR FDAC sono ATTIVI in questa strategia.
- **A** (delta dinamico): `short_strike.delta_by_dvol` non vuoto.
- **D** (vol-harvest): `exit.vol_harvest_dvol_decrease > 0`.
- **F** (auto-pause): `auto_pause.enabled = true`.
- **IV** (IV-richness gate, dal PR precedente): `entry.iv_minus_rv_filter_enabled`.
"""
feats = {"A": False, "D": False, "F": False, "IV": False}
if strategy is None:
return feats
try:
feats["A"] = bool(
getattr(strategy.structure.short_strike, "delta_by_dvol", []) # type: ignore[attr-defined]
)
except Exception:
pass
try:
feats["D"] = (
float(getattr(strategy.exit, "vol_harvest_dvol_decrease", 0)) > 0 # type: ignore[attr-defined]
)
except Exception:
pass
try:
feats["F"] = bool(
getattr(getattr(strategy, "auto_pause", None), "enabled", False)
)
except Exception:
pass
try:
feats["IV"] = bool(
getattr(strategy.entry, "iv_minus_rv_filter_enabled", False) # type: ignore[attr-defined]
)
except Exception:
pass
return feats
def _compute_pl(
caps: dict[str, float],
*,
capital: float,
spot: float,
win_rate: float,
trades_per_year: int,
eur_to_usd: float = 1.075,
features: dict[str, bool] | None = None,
) -> dict[str, float]:
"""Calcola le metriche P/L per un profilo di sizing.
Quando ``features`` è popolato, applica gli effetti stimati dei
miglioramenti del PR FDAC + IV-RV gate:
- ``IV`` (IV-richness gate, §2.9): +5 pp win-rate, 25% trade/anno.
- ``A`` (delta dinamico, §3.2): +1.5 pp win-rate, sl_loss × 0.95.
- ``D`` (vol-harvest, §7-bis): 5% delle would-be-loss diventano
harvest exit a +0.20 × credito.
- ``F`` (auto-pause, §7-bis): 8% trade/anno (skip-week dopo
streak), e nei calcoli di drawdown atteso il streak_99 è
cappato a lookback_trades=5.
Effetti **stimati ex-ante** dalla letteratura short-vol systematic;
i valori puntuali andranno calibrati sul dataset accumulato.
"""
feats = features or {}
width = caps["width_pct"] * spot
credit = caps["credit_ratio"] * width
tp_profit = caps["profit_take"] * credit
sl_loss = (caps["stop_mult"] - 1.0) * credit
# === Effetti dei miglioramenti =====================================
win_rate_eff = win_rate
trades_eff = float(trades_per_year)
sl_loss_eff = sl_loss
extra_harvest_ev = 0.0
prob_harvest = 0.0
if feats.get("IV"):
# Skip più aggressivo + qualità migliore: +5 pp win, 25% trade.
win_rate_eff = min(0.95, win_rate_eff + 0.05)
trades_eff *= 0.75
if feats.get("A"):
# Migliore strike picking → +1.5 pp win-rate; riduzione del
# tail della perdita (5%) per le bande high-DVOL.
win_rate_eff = min(0.95, win_rate_eff + 0.015)
sl_loss_eff *= 0.95
if feats.get("D"):
# Vol-harvest: ~5% delle entrate intercettate prima dello stop
# con un piccolo profitto (+0.20×credit). Sottrae lo stesso
# volume dalle prob_loss.
prob_harvest = 0.05
extra_harvest_ev = 0.20 * credit
# F (auto-pause) agisce su streak_99 più sotto, e sul trades_eff.
if feats.get("F"):
trades_eff *= 0.92
cap_pertrade_usd = caps["cap_pertrade_eur"] * eur_to_usd
risk_target = min(caps["kelly"] * capital, cap_pertrade_usd)
n_kelly = int(risk_target // width) if width > 0 else 0
n_per_trade = max(0, min(n_kelly, int(caps["max_n"])))
prob_time_stop = 0.07
prob_other_stop = 0.03
prob_loss = max(
0.0,
1.0 - win_rate_eff - prob_time_stop - prob_other_stop - prob_harvest,
)
avg_time_stop_pl = 0.10 * credit
e_trade_gross = (
win_rate_eff * tp_profit
- prob_loss * sl_loss_eff
+ prob_time_stop * avg_time_stop_pl
+ prob_harvest * extra_harvest_ev
)
fees = 0.0003 * spot * 2
slippage = 0.03 * credit
e_trade_net = e_trade_gross - fees - slippage
concurrency = max(1.0, caps["max_concurrent"])
annual_pl = trades_eff * n_per_trade * concurrency * e_trade_net
apr = (annual_pl / capital) if capital > 0 else 0.0
return {
"width": width,
"credit": credit,
"tp_profit": tp_profit,
"sl_loss": sl_loss_eff,
"risk_target": risk_target,
"n_per_trade": float(n_per_trade),
"concurrency": concurrency,
"e_trade_net": e_trade_net,
"annual_pl": annual_pl,
"apr": apr,
"fees": fees,
"slippage": slippage,
"win_rate_eff": win_rate_eff,
"trades_eff": trades_eff,
"prob_loss": prob_loss,
"prob_harvest": prob_harvest,
}
def _render_profile_card(
label: str,
caps: dict[str, float],
metrics: dict[str, float],
badge: str,
features: dict[str, bool] | None = None,
metrics_base: dict[str, float] | None = None,
) -> None:
"""Rendering di un profilo (conservativo o aggressivo) in una colonna."""
st.markdown(f"### {label} {badge}")
st.caption(
f"cap/trade {caps['cap_pertrade_eur']:.0f} EUR · "
f"cap aggreg. {caps['cap_aggregate_eur']:.0f} EUR · "
f"max {caps['max_n']:.0f} contratti × "
f"{caps['max_concurrent']:.0f} pos. concorrenti"
)
if features:
active = [k for k, v in features.items() if v]
if active:
st.caption(
"🟢 Miglioramenti attivi: "
+ " · ".join(
{
"IV": "**IV-RV gate**",
"A": "**A** delta dinamico",
"D": "**D** vol-harvest",
"F": "**F** auto-pause",
}.get(k, k)
for k in active
)
)
else:
st.caption("⚪ Nessun miglioramento attivo (formula base)")
cols = st.columns(2)
cols[0].metric("Contratti per trade", f"{metrics['n_per_trade']:.0f}")
cols[1].metric("Posizioni concorrenti", f"{metrics['concurrency']:.0f}")
cols = st.columns(2)
e_delta = (
f"{metrics['e_trade_net'] - metrics_base['e_trade_net']:+.1f}"
if metrics_base
else None
)
pl_delta = (
f"{metrics['annual_pl'] - metrics_base['annual_pl']:+.0f} USD vs base"
if metrics_base
else f"{metrics['apr']:+.1%} APR"
)
cols[0].metric(
"E[trade] netto",
f"{metrics['e_trade_net']:+.1f} USD",
delta=e_delta,
help=(
f"win_rate effettivo={metrics['win_rate_eff']:.0%}, "
f"prob_loss={metrics['prob_loss']:.0%}, "
f"trade/anno={metrics['trades_eff']:.0f}"
),
)
cols[1].metric(
"P/L annuo stimato",
f"{metrics['annual_pl']:+.0f} USD",
delta=f"{metrics['apr']:+.1%} APR" + (
f" ({metrics['annual_pl'] - metrics_base['annual_pl']:+.0f} vs base)"
if metrics_base
else ""
),
)
if metrics["n_per_trade"] == 0:
st.warning(
"Sizing 0 contratti: capitale insufficiente per i cap di "
"questo profilo."
)
def _render_pl_panel(
strategy_main: object | None,
strategy_conservativa: object | None,
strategy_aggressiva: object | None,
) -> None:
"""Pannello P/L: confronto Conservativa vs Aggressiva sugli stessi slider."""
st.subheader("💰 P/L atteso — Conservativa vs Aggressiva")
st.caption(
"Stessi slider, due profili di sizing. **Conservativa** = la "
"golden config attuale (`strategy.yaml`). **Aggressiva** = "
"`strategy.aggressiva.yaml` con cap_per_trade 4×, max contratti "
"4×, 2 posizioni concorrenti. Le regole §2-§9 sono identiche; "
"cambiano SOLO le leve di sizing — quello che il P/L "
"conservativo lascia sul tavolo."
)
col_a, col_b, col_c, col_d = st.columns(4)
capital = col_a.slider(
"Capitale (USD)", 720, 50_000, value=10_000, step=100
)
spot = col_b.slider("Spot ETH (USD)", 1500, 6000, value=3000, step=100)
win_rate = col_c.slider(
"Win rate atteso", 0.50, 0.90, value=0.75, step=0.01,
help=(
"Senza filtri quant ≈ 0.650.70. CON filtri (dealer gamma>0, "
"no macro, IVRV>0, liquidation_*_risk≠high) sale a 0.750.80."
),
)
trades_per_year = col_d.slider(
"Trade / anno (post-filtri)", 8, 30, value=18, step=1,
help="52 lunedì × probabilità di superare i filtri (3050%).",
)
cons_caps = _profile_caps(strategy_conservativa or strategy_main)
aggr_caps = _profile_caps(strategy_aggressiva)
cons_feats = _detect_features(strategy_conservativa or strategy_main)
aggr_feats = _detect_features(strategy_aggressiva)
apply_features = st.checkbox(
"Applica gli effetti dei miglioramenti FDAC + IV-RV gate "
"letti dai due `strategy.*.yaml`",
value=True,
help=(
"Quando ON, ogni colonna applica gli effetti stimati delle "
"feature attive nel rispettivo profilo. OFF = formula base "
"(senza miglioramenti) per confronto pulito."
),
)
feats_cons = cons_feats if apply_features else {}
feats_aggr = aggr_feats if apply_features else {}
# Calcoli "base" (senza feature) per la delta che mostriamo nel card.
cons_base = _compute_pl(
cons_caps,
capital=capital,
spot=spot,
win_rate=win_rate,
trades_per_year=trades_per_year,
)
aggr_base = _compute_pl(
aggr_caps,
capital=capital,
spot=spot,
win_rate=win_rate,
trades_per_year=trades_per_year,
)
cons = _compute_pl(
cons_caps,
capital=capital,
spot=spot,
win_rate=win_rate,
trades_per_year=trades_per_year,
features=feats_cons,
)
aggr = _compute_pl(
aggr_caps,
capital=capital,
spot=spot,
win_rate=win_rate,
trades_per_year=trades_per_year,
features=feats_aggr,
)
col_cons, col_aggr = st.columns(2)
with col_cons:
_render_profile_card(
"🛡️ Conservativa",
cons_caps,
cons,
"_(golden config v1.2.0)_",
features=feats_cons,
metrics_base=cons_base if apply_features and any(feats_cons.values()) else None,
)
with col_aggr:
_render_profile_card(
"🔥 Aggressiva",
aggr_caps,
aggr,
"_(deroga §11, richiede paper trading)_",
features=feats_aggr,
metrics_base=aggr_base if apply_features and any(feats_aggr.values()) else None,
)
if aggr["annual_pl"] > 0 and cons["annual_pl"] > 0:
ratio = aggr["annual_pl"] / cons["annual_pl"]
st.success(
f"Profilo aggressivo: P/L atteso ≈ **{ratio:.1f}× il "
f"conservativo** ({aggr['apr']:+.1%} vs {cons['apr']:+.1%} "
"APR). Drawdown atteso scala con lo stesso fattore."
)
if win_rate < 0.72:
st.error(
"**Win rate sotto 0.72: entrambi i profili perdono soldi.** "
"Selling vol nudo è strutturalmente neutro qui. L'edge della "
"strategia sono i FILTRI (dealer gamma>0, no macro, "
"liquidation≠high, bias chiaro) che alzano il win rate sopra "
"il 0.75. Senza filtri attivi nessuno dei due profili è "
"viable."
)
# === Mini-tabella: contributo marginale di ogni feature =====
if apply_features and (any(feats_cons.values()) or any(feats_aggr.values())):
st.markdown("**Contributo marginale di ogni feature** (profilo aggressivo)")
contrib_rows = []
for label, key in [
("IV — IV-richness gate", "IV"),
("A — Delta dinamico", "A"),
("D — Vol-harvest", "D"),
("F — Auto-pause", "F"),
]:
single_feat = {key: True}
m = _compute_pl(
aggr_caps,
capital=capital,
spot=spot,
win_rate=win_rate,
trades_per_year=trades_per_year,
features=single_feat,
)
delta_pl = m["annual_pl"] - aggr_base["annual_pl"]
delta_apr = m["apr"] - aggr_base["apr"]
active = "" if aggr_feats.get(key) else ""
contrib_rows.append(
{
"Feature": label,
"Attiva nel YAML": active,
"ΔP/L annuo (solo questa)": f"{delta_pl:+.0f} USD",
"ΔAPR": f"{delta_apr:+.1%}",
}
)
st.table(contrib_rows)
st.caption(
"Ogni riga mostra il contributo del SINGOLO feature (le altre "
"spente). Effetti stimati ex-ante; calibrabili sui dati "
"raccolti via `📐 Calibrazione`."
)
# Sensibilità win-rate per il profilo aggressivo (più informativo)
st.markdown("**Sensibilità al win rate** (profilo aggressivo)")
sens_rows = []
for wr in (0.65, 0.70, 0.72, 0.75, 0.78, 0.80, 0.82):
m_a = _compute_pl(
aggr_caps,
capital=capital,
spot=spot,
win_rate=wr,
trades_per_year=trades_per_year,
features=feats_aggr,
)
m_c = _compute_pl(
cons_caps,
capital=capital,
spot=spot,
win_rate=wr,
trades_per_year=trades_per_year,
features=feats_cons,
)
sens_rows.append(
{
"Win rate": f"{wr:.0%}",
"Conservativa P/L": f"{m_c['annual_pl']:+.0f} USD",
"Conservativa APR": f"{m_c['apr']:+.1%}",
"Aggressiva P/L": f"{m_a['annual_pl']:+.0f} USD",
"Aggressiva APR": f"{m_a['apr']:+.1%}",
}
)
st.table(sens_rows)
st.caption(
"Costi: fee 0.03% notional × 2 leg, slippage 3% del credito "
"(combo limit GTC al mid). Distribuzione esiti: profit-take = "
"win_rate, time-stop ≈ 7%, altri-stop ≈ 3%, stop-loss = il resto. "
"**Multi-asset (ETH+BTC) non è incluso nei numeri**: richiede "
"modifiche di codice (single-asset attuale). Il moltiplicatore "
"2× citato nel doc è la stima ex-ante di cosa otterresti DOPO."
)
def render() -> None:
st.title("📚 Strategia")
st.caption(
"Documento operativo che lega ogni regola del rule engine al "
"dato osservabile da cui dipende. Il pannello live in alto mostra "
"l'ultimo tick di `market_snapshots` confrontato con le soglie di "
"`strategy.yaml`."
)
db_path = _resolve_db()
asset = st.selectbox("Asset", options=["ETH", "BTC"], index=0)
records = load_market_snapshots(asset=asset, db_path=db_path, limit=1)
def _try_load(name: str) -> object | None:
for base in (Path("/app"), Path.cwd(), Path(__file__).resolve().parents[4]):
path = base / name
if path.is_file():
try:
# `_profile_caps` legge `.sizing.*` direttamente sul
# `StrategyConfig`, non sul wrapper `LoadedConfig`.
return load_strategy(path).config
except Exception as exc:
st.warning(
f"`{name}`: {type(exc).__name__}: {exc}"
)
return None
return None
strategy = _try_load("strategy.yaml")
strategy_conservativa = _try_load("strategy.conservativa.yaml")
strategy_aggressiva = _try_load("strategy.aggressiva.yaml")
st.divider()
st.subheader("📡 Stato live dei gate di entry §2")
if not records:
st.info(
"Nessuno snapshot disponibile per "
f"`{asset}`. Il job `market_snapshot` (cron `*/15`) deve "
"girare almeno una volta. Engine attivo? Controlla la pagina "
"`📊 Status`."
)
else:
latest = records[0]
st.caption(
f"Ultimo tick: {humanize_dt(latest.timestamp)} · "
f"asset {latest.asset} · "
f"fetch_ok = {'' if latest.fetch_ok else '⚠️'}"
)
if strategy is None:
st.warning(
"Senza `strategy.yaml` non posso valutare i gate; mostro "
"solo i valori grezzi."
)
st.json(latest.model_dump(mode="json"))
else:
rows = _build_gates(latest, strategy)
_render_gates(rows)
st.divider()
_render_pl_panel(strategy, strategy_conservativa, strategy_aggressiva)
st.divider()
st.subheader("📖 Documento esteso")
doc = _load_doc()
if doc is None:
st.error(
"Documento `docs/13-strategia-spiegata.md` non trovato. In "
"locale verifica il path; in container assicurati che il "
"Dockerfile copi `docs/` in `/app/docs/`."
)
else:
st.markdown(doc, unsafe_allow_html=False)
render()
+175
View File
@@ -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,
)
+68 -1
View File
@@ -38,6 +38,7 @@ from cerbero_bite.core.entry_validator import (
from cerbero_bite.core.liquidity_gate import InstrumentSnapshot, check from cerbero_bite.core.liquidity_gate import InstrumentSnapshot, check
from cerbero_bite.core.sizing_engine import SizingContext, compute_contracts from cerbero_bite.core.sizing_engine import SizingContext, compute_contracts
from cerbero_bite.core.types import OptionQuote 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.alert_manager import AlertManager
from cerbero_bite.runtime.dependencies import RuntimeContext from cerbero_bite.runtime.dependencies import RuntimeContext
from cerbero_bite.state import ( from cerbero_bite.state import (
@@ -64,6 +65,7 @@ _STATUS_NO_ENTRY = "no_entry"
_STATUS_BROKER_REJECT = "broker_reject" _STATUS_BROKER_REJECT = "broker_reject"
_STATUS_KILL_SWITCH = "kill_switch_armed" _STATUS_KILL_SWITCH = "kill_switch_armed"
_STATUS_HAS_OPEN = "has_open_position" _STATUS_HAS_OPEN = "has_open_position"
_STATUS_AUTO_PAUSED = "auto_paused"
@dataclass(frozen=True) @dataclass(frozen=True)
@@ -322,6 +324,28 @@ async def run_entry_cycle(
) )
return EntryCycleResult(status=_STATUS_KILL_SWITCH, reason="kill_switch") 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? # Has open position?
conn = connect_state(ctx.db_path) conn = connect_state(ctx.db_path)
try: try:
@@ -344,6 +368,44 @@ async def run_entry_cycle(
) )
capital_usd = snap.portfolio_eur * eur_to_usd_rate 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 # 2. Entry filters
entry_ctx = EntryContext( entry_ctx = EntryContext(
capital_usd=capital_usd, capital_usd=capital_usd,
@@ -436,7 +498,12 @@ async def run_entry_cycle(
) )
quotes = await _build_quotes(ctx.deribit, chain_meta) quotes = await _build_quotes(ctx.deribit, chain_meta)
selection = select_strikes( 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: if selection is None:
await _record_decision( await _record_decision(
@@ -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;
+2
View File
@@ -184,3 +184,5 @@ class SystemStateRecord(BaseModel):
config_version: str config_version: str
started_at: datetime started_at: datetime
last_audit_hash: str | None = None last_audit_hash: str | None = None
auto_pause_until: datetime | None = None
auto_pause_reason: str | None = None
+47
View File
@@ -488,6 +488,16 @@ class Repository:
last_audit_hash=( last_audit_hash=(
row["last_audit_hash"] if "last_audit_hash" in keys else None 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( def set_last_audit_hash(
@@ -526,6 +536,43 @@ class Repository:
(_enc_dt(now),), (_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 # Row → model converters
+204
View File
@@ -0,0 +1,204 @@
# strategy.aggressiva.yaml — Cerbero Bite, profilo AGGRESSIVO
#
# Profilo "crescita: rendimenti significativi, drawdown a doppia cifra,
# complessità più alta". DEROGA esplicitamente alla sezione §11
# "Riepilogo soglie" di docs/01-strategy-rules.md (cap_per_trade_eur,
# cap_aggregate_open_eur, max_concurrent_positions). NON va deployato
# senza:
# 1. backtest dedicato sui dati raccolti
# 2. paper trading per almeno 4 settimane
# 3. autorizzazione esplicita scritta nel commit
#
# Caratteristiche operative attese (vs. profilo conservativo):
# * Cap per trade 800 EUR (~860 USD) → 4× la size
# * Cap aggregato 3 200 EUR (~3 440 USD) → 4× il rischio aggregato
# * Max 2 posizioni concorrenti (era 1)
# * Max 16 contratti per trade (era 4)
# * P/L stimato: +5% / +20% APR sul capitale impiegato
# * Drawdown atteso: 2540% del capitale impiegato in streak
# * Adatto a: capitale "growth", non parcheggio
#
# CAVEAT MULTI-ASSET. Il rule engine attuale è single-asset
# (`asset.symbol`). Per estendere a ETH+BTC servono modifiche di
# codice in:
# * cerbero_bite/runtime/entry_cycle.py (loop su lista asset)
# * cerbero_bite/state/repository.py (multi-position per asset)
# * cerbero_bite/runtime/orchestrator.py (scheduler one-asset → N)
# Nel frattempo il file resta single-asset ETH; il moltiplicatore
# 2× via "ETH + BTC" indicato in `📚 Strategia` è una **stima ex-ante**
# di cosa otterresti DOPO quel lavoro di codice.
config_version: "1.2.0-aggressiva"
config_hash: "e3a583cabfaa4781cd0ebcc8b62fc8f200648153738f93ab8726b062e46cacef"
last_review: "2026-04-26"
last_reviewer: "Adriano"
asset:
symbol: "ETH"
exchange: "deribit"
entry:
cron: "0 14 * * MON"
skip_holidays_country: "IT"
capital_min_usd: "2880" # 4× del minimo conservativo (720)
dvol_min: "35"
dvol_max: "90"
funding_perp_abs_max_annualized: "0.80"
eth_holdings_pct_max: "0.30"
no_position_concurrent: false # consenti N posizioni concorrenti
exclude_macro_severity: ["high"]
exclude_macro_countries: ["US", "EU"]
trend_window_days: 30
trend_bull_threshold_pct: "0.05"
trend_bear_threshold_pct: "-0.05"
funding_bull_threshold_annualized: "0.20"
funding_bear_threshold_annualized: "-0.20"
iron_condor_dvol_min: "55"
iron_condor_adx_max: "20"
iron_condor_trend_neutral_band_pct: "0.05"
# Filtri quant invariati: l'edge della strategia E' qui, non
# serve allentarli per "guadagnare di più" — anzi sarebbe
# controproducente.
dealer_gamma_min: "0"
dealer_gamma_filter_enabled: true
liquidation_filter_enabled: true
structure:
dte_target: 18
dte_min: 14
dte_max: 21
short_strike:
delta_target: "0.12"
delta_min: "0.10"
delta_max: "0.15"
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"
max_pct_of_spot: "0.05"
credit_to_width_ratio_min: "0.30"
liquidity:
open_interest_min: 100
volume_24h_min: 20
bid_ask_spread_pct_max: "0.15"
book_depth_top3_min: 5
slippage_pct_of_credit_max: "0.08"
sizing:
kelly_fraction: "0.13" # disciplina Kelly invariata
# Le tre leve dominanti:
cap_per_trade_eur: "800" # era 200 → 4×
cap_aggregate_open_eur: "3200" # era 1000 → 4× (proporzionato a 2 posizioni × cap_per_trade × 2 ruote)
max_concurrent_positions: 2 # era 1
max_contracts_per_trade: 16 # era 4 → 4×
dvol_adjustment:
- {dvol_under: "45", multiplier: "1.00"}
- {dvol_under: "60", multiplier: "0.85"}
- {dvol_under: "80", multiplier: "0.65"}
dvol_no_entry_threshold: "80"
exit:
profit_take_pct_of_credit: "0.50"
stop_loss_mark_x_credit: "2.50"
vol_stop_dvol_increase: "10"
time_stop_dte_remaining: 7
time_stop_skip_if_close_to_profit_pct: "0.70"
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
escalate_on_timeout:
- "CLOSE_STOP"
- "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"
combo_only: true
initial_limit: "mid"
reprice_step_ticks: 1
reprice_max_steps: 3
reprice_max_steps_urgent: 5
order_tif: "GTC"
order_expiry_min: 30
ack_timeout_s: 300
monitoring:
health_check_interval_s: 300
health_failures_before_kill: 3
health_failures_before_restart: 5
daily_digest_cron: "0 8 * * *"
monthly_report_cron: "0 12 1 * *"
storage:
sqlite_path: "data/state.sqlite"
log_path: "data/log/"
log_retention_days: 365
backup_path: "data/backups/"
backup_retention_days: 30
mcp:
config_file: "~/.config/cerbero-suite/mcp.json"
call_timeout_s: 8
retry_max: 3
retry_base_delay_s: 1
required_versions:
cerbero-deribit: "^2.0.0"
cerbero-hyperliquid: "^1.5.0"
cerbero-memory: "^4.0.0"
cerbero-portfolio: "^1.2.0"
cerbero-macro: "^1.0.0"
cerbero-sentiment: "^1.0.0"
cerbero-telegram: "^1.0.0"
cerbero-brain-bridge: "^1.0.0"
telegram:
parse_mode: "MarkdownV2"
confirmation_timeout_min: 60
exit_confirmation_timeout_min: 30
backup_channel_on_critical: true
kelly_recalibration:
lookback_days: 365
min_sample_low_confidence: 30
min_sample_high_confidence: 100
weight_when_medium_confidence: "0.50"
+173
View File
@@ -0,0 +1,173 @@
# strategy.conservativa.yaml — Cerbero Bite, profilo CONSERVATIVO
#
# Profilo "premio sopra T-bill, drawdown contenuto, complessità minima".
# È identico per regole alla golden config v1.0.0; serve come ancora di
# riferimento per il confronto con `strategy.aggressiva.yaml`.
#
# Caratteristiche operative attese:
# * Cap per trade 200 EUR (~215 USD)
# * Max 1 posizione concorrente
# * P/L stimato: +1.5% / +5% APR sul capitale totale
# * Drawdown atteso: 1020% del capitale impiegato in streak
# * Adatto a: parcheggio capitale, premio modesto, niente sorprese
#
# Ricorda: dopo ogni edit, rigenerare il config_hash con
# cerbero-bite config hash --file strategy.conservativa.yaml
# e bumpare config_version.
config_version: "1.2.0-conservativa"
config_hash: "fa09dad9cfa40a8ab006ec85157635603e0c4b6381ecd5d721504e00c4119a1b"
last_review: "2026-04-26"
last_reviewer: "Adriano"
asset:
symbol: "ETH"
exchange: "deribit"
entry:
cron: "0 14 * * MON"
skip_holidays_country: "IT"
capital_min_usd: "720"
dvol_min: "35"
dvol_max: "90"
funding_perp_abs_max_annualized: "0.80"
eth_holdings_pct_max: "0.30"
no_position_concurrent: true
exclude_macro_severity: ["high"]
exclude_macro_countries: ["US", "EU"]
trend_window_days: 30
trend_bull_threshold_pct: "0.05"
trend_bear_threshold_pct: "-0.05"
funding_bull_threshold_annualized: "0.20"
funding_bear_threshold_annualized: "-0.20"
iron_condor_dvol_min: "55"
iron_condor_adx_max: "20"
iron_condor_trend_neutral_band_pct: "0.05"
dealer_gamma_min: "0"
dealer_gamma_filter_enabled: true
liquidation_filter_enabled: true
structure:
dte_target: 18
dte_min: 14
dte_max: 21
short_strike:
delta_target: "0.12"
delta_min: "0.10"
delta_max: "0.15"
distance_otm_pct_min: "0.15"
distance_otm_pct_max: "0.25"
spread_width:
target_pct_of_spot: "0.04"
min_pct_of_spot: "0.03"
max_pct_of_spot: "0.05"
credit_to_width_ratio_min: "0.30"
liquidity:
open_interest_min: 100
volume_24h_min: 20
bid_ask_spread_pct_max: "0.15"
book_depth_top3_min: 5
slippage_pct_of_credit_max: "0.08"
sizing:
kelly_fraction: "0.13"
cap_per_trade_eur: "200"
cap_aggregate_open_eur: "1000"
max_concurrent_positions: 1
max_contracts_per_trade: 4
dvol_adjustment:
- {dvol_under: "45", multiplier: "1.00"}
- {dvol_under: "60", multiplier: "0.85"}
- {dvol_under: "80", multiplier: "0.65"}
dvol_no_entry_threshold: "80"
exit:
profit_take_pct_of_credit: "0.50"
stop_loss_mark_x_credit: "2.50"
vol_stop_dvol_increase: "10"
time_stop_dte_remaining: 7
time_stop_skip_if_close_to_profit_pct: "0.70"
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
escalate_on_timeout:
- "CLOSE_STOP"
- "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"
combo_only: true
initial_limit: "mid"
reprice_step_ticks: 1
reprice_max_steps: 3
reprice_max_steps_urgent: 5
order_tif: "GTC"
order_expiry_min: 30
ack_timeout_s: 300
monitoring:
health_check_interval_s: 300
health_failures_before_kill: 3
health_failures_before_restart: 5
daily_digest_cron: "0 8 * * *"
monthly_report_cron: "0 12 1 * *"
storage:
sqlite_path: "data/state.sqlite"
log_path: "data/log/"
log_retention_days: 365
backup_path: "data/backups/"
backup_retention_days: 30
mcp:
config_file: "~/.config/cerbero-suite/mcp.json"
call_timeout_s: 8
retry_max: 3
retry_base_delay_s: 1
required_versions:
cerbero-deribit: "^2.0.0"
cerbero-hyperliquid: "^1.5.0"
cerbero-memory: "^4.0.0"
cerbero-portfolio: "^1.2.0"
cerbero-macro: "^1.0.0"
cerbero-sentiment: "^1.0.0"
cerbero-telegram: "^1.0.0"
cerbero-brain-bridge: "^1.0.0"
telegram:
parse_mode: "MarkdownV2"
confirmation_timeout_min: 60
exit_confirmation_timeout_min: 30
backup_channel_on_critical: true
kelly_recalibration:
lookback_days: 365
min_sample_low_confidence: 30
min_sample_high_confidence: 100
weight_when_medium_confidence: "0.50"
+17 -2
View File
@@ -6,8 +6,8 @@
# config hash), and lands as a separate commit with the motivation in # config hash), and lands as a separate commit with the motivation in
# the commit message. # the commit message.
config_version: "1.0.0" config_version: "1.2.0"
config_hash: "4c2be4c51c849ed58fa22ec2b302016c453894dd0964b6d05445ab1b723e2d10" config_hash: "33263a313b26b24b41269f93f93783784451ac9b4b6460005b95c2fb3624fcdc"
last_review: "2026-04-26" last_review: "2026-04-26"
last_reviewer: "Adriano" last_reviewer: "Adriano"
@@ -96,6 +96,13 @@ exit:
delta_breach_threshold: "0.30" delta_breach_threshold: "0.30"
adverse_move_4h_pct: "0.05" 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 * * *" monitor_cron: "0 2,14 * * *"
user_confirmation_timeout_min: 30 user_confirmation_timeout_min: 30
@@ -104,6 +111,14 @@ exit:
- "CLOSE_VOL" - "CLOSE_VOL"
- "CLOSE_DELTA" - "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: execution:
environment: "testnet" # testnet|mainnet — kill switch on broker mismatch environment: "testnet" # testnet|mainnet — kill switch on broker mismatch
eur_to_usd: "1.075" # default FX rate for sizing engine; override at boot eur_to_usd: "1.075" # default FX rate for sizing engine; override at boot
+157
View File
@@ -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
+143
View File
@@ -329,3 +329,146 @@ def test_build_bear_call_breakeven_above_short_strike(
# breakeven = 3525 + 15 = 3540 # breakeven = 3525 + 15 = 3540
assert proposal.breakeven == Decimal("3540") assert proposal.breakeven == Decimal("3540")
assert proposal.spread_type == "bear_call" 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")
+1 -1
View File
@@ -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: def test_load_repo_strategy_yaml(tmp_path: Path) -> None:
"""The committed strategy.yaml validates with the recorded hash.""" """The committed strategy.yaml validates with the recorded hash."""
result = load_strategy(REPO_ROOT / "strategy.yaml") 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.config.sizing.kelly_fraction == Decimal("0.13")
assert result.computed_hash == result.config.config_hash assert result.computed_hash == result.config.config_hash
+88
View File
@@ -271,3 +271,91 @@ def test_iron_condor_adverse_move_either_direction(cfg: StrategyConfig) -> None:
) )
res = evaluate(snap, cfg) res = evaluate(snap, cfg)
assert res.action == "CLOSE_AVERSE" 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"