Compare commits
4 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 954baaa354 | |||
| 3e46169278 | |||
| c0a0ee416f | |||
| 21e865ffb0 |
@@ -5,7 +5,6 @@
|
||||
.pytest_cache/
|
||||
__pycache__/
|
||||
data/
|
||||
docs/
|
||||
tests/
|
||||
.coverage
|
||||
htmlcov/
|
||||
|
||||
+8
-2
@@ -14,12 +14,12 @@ ENV UV_PROJECT_ENVIRONMENT=/opt/venv \
|
||||
# Install only the dependencies first so the layer is cached when the
|
||||
# source tree changes.
|
||||
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.
|
||||
COPY src ./src
|
||||
COPY README.md ./
|
||||
RUN uv sync --frozen --no-dev
|
||||
RUN uv sync --frozen --no-dev --extra gui
|
||||
|
||||
|
||||
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 scripts /app/scripts
|
||||
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
|
||||
# docker-compose.yml.
|
||||
|
||||
+90
-25
@@ -1,27 +1,48 @@
|
||||
# docker-compose.yml — Cerbero Bite
|
||||
#
|
||||
# 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
|
||||
# service name when running co-located, and otherwise reaches the
|
||||
# public gateway (`https://cerbero-mcp.tielogic.xyz`) over the host
|
||||
# network.
|
||||
# network used by Cerbero MCP V2 and Traefik (`traefik`) so it can
|
||||
# either resolve the in-cluster service name (`cerbero-mcp:9000`)
|
||||
# or reach the public gateway (`https://cerbero-mcp.tielogic.xyz`)
|
||||
# transparently.
|
||||
#
|
||||
# The shared network is declared as external here. Create it once on
|
||||
# the host with `docker network create cerbero-suite` (or rename the
|
||||
# Cerbero_mcp network to `cerbero-suite` and mark it external).
|
||||
# The reverse-proxy network (`traefik`) is declared as external
|
||||
# here. It is created by the Traefik stack at /opt/docker/traefik
|
||||
# and shared by every web-facing service on the host.
|
||||
#
|
||||
# Authentication: a single bearer token is passed through from the
|
||||
# host `.env` file via `CERBERO_BITE_MCP_TOKEN`. The Cerbero MCP V2
|
||||
# server uses the token to decide whether the upstream environment
|
||||
# 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:
|
||||
cerbero-suite:
|
||||
traefik:
|
||||
external: true
|
||||
|
||||
volumes:
|
||||
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:
|
||||
cerbero-bite:
|
||||
build:
|
||||
@@ -29,24 +50,12 @@ services:
|
||||
dockerfile: Dockerfile
|
||||
image: cerbero-bite:dev
|
||||
restart: unless-stopped
|
||||
networks: [cerbero-suite]
|
||||
networks: [traefik]
|
||||
cap_drop: [ALL]
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
environment:
|
||||
# MCP auth — token is sourced from the host .env (compose
|
||||
# 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}
|
||||
<<: *bite-env
|
||||
# Telegram and Portfolio are no longer shared MCP services. The
|
||||
# bot now calls the Telegram Bot API directly and aggregates
|
||||
# portfolio in-process from Deribit + Hyperliquid + Macro.
|
||||
@@ -62,6 +71,62 @@ services:
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
start_period: 120s
|
||||
# Default command runs the engine status check; override with the
|
||||
# CLI subcommand of choice (start, ping, dry-run, ...).
|
||||
command: ["status"]
|
||||
# Engine main loop (scheduler + monitoring). Switch to `status`,
|
||||
# `ping`, `dry-run`, ... for one-shot diagnostics. The MCP token in
|
||||
# `.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
|
||||
|
||||
@@ -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 0–200 | 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, IV−RV)
|
||||
|
||||
**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 45–60, ×0.65 fra 60–80, 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 → IV−RV 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 (15–25% 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.10–0.15)
|
||||
**e** OTM 15–25%. Lo strike long è a 4% del spot (3–5% 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 70–72% 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.78–0.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 | **36–48 USD / contratto** |
|
||||
| Max profit teorico | = credito (a scadenza OTM) | 36–48 USD / contratto |
|
||||
| **Profit-take §7.1 (50% credito)** | 0.5 × credito | **+18–24 USD / contratto** |
|
||||
| **Stop-loss §7.2 (mark = 2.5× credito)** | 1.5 × credito | **−54–72 USD / contratto** |
|
||||
| Margine bloccato | ≈ larghezza | 120 USD / contratto |
|
||||
| Fees Deribit | 0.03% notional × 2 leg | ~1–2 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 | **0–1** (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.5–10 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 (35–90) | 25–40% |
|
||||
| Bias non chiaro (trend × funding discordi o entrambi neutri senza IC) | 25–35% |
|
||||
| Macro entro DTE | 10–20% |
|
||||
| Funding o liquidation risk fuori soglia | 5–15% |
|
||||
| Capitale o sizing insufficiente | 0–5% |
|
||||
|
||||
**Risultato netto: 30–50% delle settimane finisce in entry effettiva
|
||||
⇒ 15–25 trade / anno** (52 lunedì × 30–50%). 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.10–0.15 con
|
||||
TP@50% e SL@1.5×:
|
||||
|
||||
| Esito | Probabilità tipica | Risultato |
|
||||
|---|---|---|
|
||||
| Profit-take a 50% credito | **~70–75%** | +18–24 USD/contratto |
|
||||
| Stop-loss a 1.5× credito | ~15–20% | −54–72 USD/contratto |
|
||||
| Time-stop o exit DTE 7g | ~5–10% | piccolo positivo (~+5–10 USD) |
|
||||
| Vol/delta/macro stop | ~3–5% | 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] ≈ +1–3 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, IV−RV 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**: 3–5 stop-loss di fila
|
||||
capitano. Drawdown su 1 contratto: −150 / −300 USD assoluti.
|
||||
- **Su capitale 1 500 USD** = drawdown del 10–20% 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è 72–96 USD/contratto, non i 54–72 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.8–1.5** in regimi favorevoli (mercato lento + IV alta).
|
||||
- **Sharpe 0.3–0.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 =
|
||||
> 1–2 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 ≈ 4–8× il
|
||||
profilo conservativo. Drawdown atteso scala con lo stesso fattore
|
||||
(20–40% del capitale impiegato in streak avverse, contro 10–20% 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 0–200.
|
||||
- **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, IV−RV, 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`
|
||||
+236
-1
@@ -13,7 +13,7 @@ import asyncio
|
||||
import os
|
||||
import sys
|
||||
from collections.abc import Callable
|
||||
from datetime import UTC, datetime
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from decimal import Decimal
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
@@ -812,6 +812,241 @@ def state_inspect(db: Path) -> None:
|
||||
console.print(table)
|
||||
|
||||
|
||||
@main.group(name="option-chain")
|
||||
def option_chain() -> None:
|
||||
"""Strumenti per la catena opzioni storica (`option_chain_snapshots`)."""
|
||||
|
||||
|
||||
@option_chain.command(name="trigger")
|
||||
@click.option(
|
||||
"--strategy",
|
||||
"strategy_path",
|
||||
type=click.Path(exists=True, dir_okay=False, path_type=Path),
|
||||
default=_DEFAULT_STRATEGY_PATH,
|
||||
show_default=True,
|
||||
)
|
||||
@click.option(
|
||||
"--db",
|
||||
"db_path",
|
||||
type=click.Path(dir_okay=False, path_type=Path),
|
||||
default=_DEFAULT_DB_PATH,
|
||||
show_default=True,
|
||||
)
|
||||
@click.option(
|
||||
"--audit",
|
||||
"audit_path",
|
||||
type=click.Path(dir_okay=False, path_type=Path),
|
||||
default=_DEFAULT_AUDIT_PATH,
|
||||
show_default=True,
|
||||
)
|
||||
@click.option(
|
||||
"--token",
|
||||
type=str,
|
||||
default=None,
|
||||
help="MCP bearer token (override su CERBERO_BITE_MCP_TOKEN).",
|
||||
)
|
||||
@click.option("--asset", default="ETH", show_default=True)
|
||||
def option_chain_trigger(
|
||||
strategy_path: Path,
|
||||
db_path: Path,
|
||||
audit_path: Path,
|
||||
token: str | None,
|
||||
asset: str,
|
||||
) -> None:
|
||||
"""Esegue UNA volta il collector della catena opzioni e persiste in DB.
|
||||
|
||||
Utile per popolare i dati senza aspettare il cron settimanale del
|
||||
job ``option_chain_snapshot``. Riusa esattamente la stessa pipeline
|
||||
schedulata.
|
||||
"""
|
||||
from cerbero_bite.runtime.dependencies import build_runtime # noqa: PLC0415
|
||||
from cerbero_bite.runtime.option_chain_snapshot_cycle import ( # noqa: PLC0415
|
||||
collect_option_chain_snapshot,
|
||||
)
|
||||
|
||||
cfg = load_strategy(strategy_path).config
|
||||
ctx = build_runtime(
|
||||
cfg=cfg,
|
||||
endpoints=load_endpoints(),
|
||||
token=load_token(value=token),
|
||||
db_path=db_path,
|
||||
audit_path=audit_path,
|
||||
bot_tag=load_bot_tag(),
|
||||
)
|
||||
n = asyncio.run(collect_option_chain_snapshot(ctx, asset=asset))
|
||||
console.print(
|
||||
f"[green]Persisted {n} option chain quote(s) for {asset}[/green]"
|
||||
if n > 0
|
||||
else f"[yellow]No quotes persisted (chain empty or fetch failed)[/yellow]"
|
||||
)
|
||||
|
||||
|
||||
@option_chain.command(name="analyze")
|
||||
@click.option(
|
||||
"--strategy",
|
||||
"strategy_path",
|
||||
type=click.Path(exists=True, dir_okay=False, path_type=Path),
|
||||
default=_DEFAULT_STRATEGY_PATH,
|
||||
show_default=True,
|
||||
)
|
||||
@click.option(
|
||||
"--db",
|
||||
"db_path",
|
||||
type=click.Path(dir_okay=False, path_type=Path),
|
||||
default=_DEFAULT_DB_PATH,
|
||||
show_default=True,
|
||||
)
|
||||
@click.option("--asset", default="ETH", show_default=True)
|
||||
@click.option(
|
||||
"--bias",
|
||||
type=click.Choice(["bull_put", "bear_call"], case_sensitive=False),
|
||||
default="bull_put",
|
||||
show_default=True,
|
||||
help="Direzione da simulare (il rule engine lo deciderebbe da trend×funding).",
|
||||
)
|
||||
def option_chain_analyze(
|
||||
strategy_path: Path,
|
||||
db_path: Path,
|
||||
asset: str,
|
||||
bias: str,
|
||||
) -> None:
|
||||
"""Analizza l'ultimo snapshot di catena salvato.
|
||||
|
||||
Per la strategia indicata, simula la selezione strike (delta
|
||||
target, OTM range, width 4%, credit/width ratio min) e mostra:
|
||||
* lo strike che il rule engine sceglierebbe come short e long,
|
||||
* credito atteso, larghezza, rapporto credit/width,
|
||||
* pass/fail del gate `credit_to_width_ratio_min`.
|
||||
"""
|
||||
from cerbero_bite.core.combo_builder import select_strikes # noqa: PLC0415
|
||||
from cerbero_bite.core.types import OptionQuote # noqa: PLC0415
|
||||
|
||||
cfg = load_strategy(strategy_path).config
|
||||
|
||||
conn = connect_state(db_path)
|
||||
try:
|
||||
repo = Repository()
|
||||
latest_ts = repo.latest_option_chain_timestamp(conn, asset=asset.upper())
|
||||
if latest_ts is None:
|
||||
console.print(
|
||||
"[red]Nessuno snapshot di catena trovato. Lancia prima "
|
||||
"`cerbero-bite option-chain trigger`.[/red]"
|
||||
)
|
||||
sys.exit(1)
|
||||
quotes_records = repo.list_option_chain_snapshots(
|
||||
conn, asset=asset.upper(), start=latest_ts, end=latest_ts,
|
||||
)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
console.print(
|
||||
f"[cyan]Snapshot del {latest_ts.isoformat()} — {len(quotes_records)} "
|
||||
f"quote totali[/cyan]"
|
||||
)
|
||||
|
||||
# Costruzione OptionQuote da OptionChainQuoteRecord per riusare select_strikes.
|
||||
quotes: list[OptionQuote] = []
|
||||
for q in quotes_records:
|
||||
if q.bid is None or q.ask is None or q.mid is None or q.delta is None:
|
||||
continue
|
||||
quotes.append(
|
||||
OptionQuote(
|
||||
instrument=q.instrument_name,
|
||||
strike=q.strike,
|
||||
expiry=q.expiry,
|
||||
option_type=q.option_type,
|
||||
bid=q.bid,
|
||||
ask=q.ask,
|
||||
mid=q.mid,
|
||||
delta=q.delta,
|
||||
gamma=q.gamma or Decimal("0"),
|
||||
theta=q.theta or Decimal("0"),
|
||||
vega=q.vega or Decimal("0"),
|
||||
open_interest=q.open_interest or 0,
|
||||
volume_24h=q.volume_24h or 0,
|
||||
book_depth_top3=q.book_depth_top3 or 0,
|
||||
)
|
||||
)
|
||||
|
||||
if not quotes:
|
||||
console.print("[red]Nessun quote completo per la simulazione.[/red]")
|
||||
sys.exit(1)
|
||||
|
||||
# Lo spot al momento dello snapshot: estraiamo dall'ultimo
|
||||
# `market_snapshot` ETH a quel timestamp (tolleranza ±15 min).
|
||||
spot = _resolve_spot_at(db_path, asset=asset.upper(), at=latest_ts)
|
||||
if spot is None:
|
||||
console.print(
|
||||
"[yellow]Spot non recuperabile dai market_snapshots; "
|
||||
"stimato dal mid ATM.[/yellow]"
|
||||
)
|
||||
spot = _atm_spot_proxy(quotes)
|
||||
|
||||
selection = select_strikes(
|
||||
chain=quotes,
|
||||
bias=bias, # type: ignore[arg-type]
|
||||
spot=spot,
|
||||
now=latest_ts,
|
||||
cfg=cfg,
|
||||
)
|
||||
if selection is None:
|
||||
console.print(
|
||||
"[red]Il rule engine NON aprirebbe trade con questa catena[/red] "
|
||||
"(no strike compatibile coi gate delta/distance/width/credit-ratio)."
|
||||
)
|
||||
sys.exit(0)
|
||||
|
||||
short, long_ = selection
|
||||
width_usd = (short.strike - long_.strike).copy_abs()
|
||||
credit_eth = short.mid - long_.mid
|
||||
credit_usd = credit_eth * spot
|
||||
ratio = credit_usd / width_usd if width_usd > 0 else Decimal("0")
|
||||
ratio_target = cfg.structure.credit_to_width_ratio_min
|
||||
|
||||
table = Table(title=f"Simulazione picker — bias={bias}, spot={spot:.0f}")
|
||||
table.add_column("Campo", style="cyan")
|
||||
table.add_column("Valore", style="bold")
|
||||
table.add_row("Short strike", f"{short.strike} ({short.delta:+.3f}δ)")
|
||||
table.add_row("Long strike", f"{long_.strike} ({long_.delta:+.3f}δ)")
|
||||
table.add_row("Width", f"{width_usd:.0f} USD")
|
||||
table.add_row("Credit", f"{credit_eth:.4f} ETH ≈ {credit_usd:.2f} USD")
|
||||
table.add_row(
|
||||
"Credit/width ratio",
|
||||
f"{ratio:.2%} (gate ≥ {float(ratio_target):.0%})",
|
||||
)
|
||||
pass_str = (
|
||||
"[green]PASS — entry possibile[/green]"
|
||||
if ratio >= ratio_target
|
||||
else "[red]FAIL — premio troppo magro[/red]"
|
||||
)
|
||||
table.add_row("Verdetto gate ratio", pass_str)
|
||||
console.print(table)
|
||||
|
||||
|
||||
def _resolve_spot_at(db_path: Path, *, asset: str, at: datetime) -> Decimal | None:
|
||||
"""Best-effort lookup dello spot al timestamp ``at`` ± 15 min."""
|
||||
conn = connect_state(db_path)
|
||||
try:
|
||||
rows = Repository().list_market_snapshots(
|
||||
conn,
|
||||
asset=asset,
|
||||
start=at - timedelta(minutes=15),
|
||||
end=at + timedelta(minutes=15),
|
||||
limit=1,
|
||||
)
|
||||
finally:
|
||||
conn.close()
|
||||
if not rows:
|
||||
return None
|
||||
return rows[0].spot
|
||||
|
||||
|
||||
def _atm_spot_proxy(quotes: list[Any]) -> Decimal:
|
||||
"""Stima dello spot prendendo lo strike il cui delta è più vicino a 0.5."""
|
||||
quote = min(quotes, key=lambda q: abs(abs(q.delta) - Decimal("0.5")))
|
||||
return quote.strike
|
||||
|
||||
|
||||
def _entrypoint() -> None:
|
||||
"""Wrapper used by ``cerbero-bite`` console script."""
|
||||
try:
|
||||
|
||||
@@ -0,0 +1,648 @@
|
||||
"""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 35–90",
|
||||
"—",
|
||||
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 _compute_pl(
|
||||
caps: dict[str, float],
|
||||
*,
|
||||
capital: float,
|
||||
spot: float,
|
||||
win_rate: float,
|
||||
trades_per_year: int,
|
||||
eur_to_usd: float = 1.075,
|
||||
) -> dict[str, float]:
|
||||
"""Calcola le metriche P/L per un profilo di sizing."""
|
||||
width = caps["width_pct"] * spot
|
||||
credit = caps["credit_ratio"] * width
|
||||
tp_profit = caps["profit_take"] * credit
|
||||
sl_loss = (caps["stop_mult"] - 1.0) * credit
|
||||
|
||||
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 - prob_time_stop - prob_other_stop)
|
||||
avg_time_stop_pl = 0.10 * credit
|
||||
|
||||
e_trade_gross = (
|
||||
win_rate * tp_profit
|
||||
- prob_loss * sl_loss
|
||||
+ prob_time_stop * avg_time_stop_pl
|
||||
)
|
||||
fees = 0.0003 * spot * 2
|
||||
slippage = 0.03 * credit
|
||||
e_trade_net = e_trade_gross - fees - slippage
|
||||
|
||||
# Multi-posizione concorrente: il P/L scala col numero di posizioni
|
||||
# aperte simultaneamente (il loop entry crea N trade indipendenti
|
||||
# quando max_concurrent > 1). Vedi caveat aggressiva.yaml: il
|
||||
# supporto multi-asset richiede modifiche di codice; questo
|
||||
# moltiplicatore stima cosa otterresti DOPO.
|
||||
concurrency = max(1.0, caps["max_concurrent"])
|
||||
annual_pl = trades_per_year * 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,
|
||||
"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,
|
||||
}
|
||||
|
||||
|
||||
def _render_profile_card(
|
||||
label: str,
|
||||
caps: dict[str, float],
|
||||
metrics: dict[str, float],
|
||||
badge: str,
|
||||
) -> 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"
|
||||
)
|
||||
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)
|
||||
cols[0].metric(
|
||||
"E[trade] netto",
|
||||
f"{metrics['e_trade_net']:+.1f} USD",
|
||||
help=(
|
||||
f"fees={metrics['fees']:.2f} USD, "
|
||||
f"slippage={metrics['slippage']:.2f} USD"
|
||||
),
|
||||
)
|
||||
cols[1].metric(
|
||||
"P/L annuo stimato",
|
||||
f"{metrics['annual_pl']:+.0f} USD",
|
||||
delta=f"{metrics['apr']:+.1%} APR",
|
||||
)
|
||||
|
||||
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.65–0.70. CON filtri (dealer gamma>0, "
|
||||
"no macro, IV−RV>0, liquidation_*_risk≠high) sale a 0.75–0.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 (30–50%).",
|
||||
)
|
||||
|
||||
cons_caps = _profile_caps(strategy_conservativa or strategy_main)
|
||||
aggr_caps = _profile_caps(strategy_aggressiva)
|
||||
cons = _compute_pl(
|
||||
cons_caps,
|
||||
capital=capital,
|
||||
spot=spot,
|
||||
win_rate=win_rate,
|
||||
trades_per_year=trades_per_year,
|
||||
)
|
||||
aggr = _compute_pl(
|
||||
aggr_caps,
|
||||
capital=capital,
|
||||
spot=spot,
|
||||
win_rate=win_rate,
|
||||
trades_per_year=trades_per_year,
|
||||
)
|
||||
|
||||
col_cons, col_aggr = st.columns(2)
|
||||
with col_cons:
|
||||
_render_profile_card(
|
||||
"🛡️ Conservativa",
|
||||
cons_caps,
|
||||
cons,
|
||||
"_(golden config v1.0.0)_",
|
||||
)
|
||||
with col_aggr:
|
||||
_render_profile_card(
|
||||
"🔥 Aggressiva",
|
||||
aggr_caps,
|
||||
aggr,
|
||||
"_(deroga §11, richiede paper trading)_",
|
||||
)
|
||||
|
||||
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."
|
||||
)
|
||||
|
||||
# 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,
|
||||
)
|
||||
m_c = _compute_pl(
|
||||
cons_caps,
|
||||
capital=capital,
|
||||
spot=spot,
|
||||
win_rate=wr,
|
||||
trades_per_year=trades_per_year,
|
||||
)
|
||||
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()
|
||||
@@ -0,0 +1,185 @@
|
||||
"""Periodic option-chain snapshot collector (§13).
|
||||
|
||||
Fetches the Deribit option chain for every strike entro la finestra
|
||||
DTE configurata, prima del trigger entry settimanale (cron
|
||||
``55 13 * * MON`` di default). Persiste un quote per ogni strumento
|
||||
in ``option_chain_snapshots`` con un timestamp condiviso, che diventa
|
||||
il dato di base per:
|
||||
|
||||
* il backtest non-stilizzato (vedi ``core/backtest.py``),
|
||||
* la calibrazione empirica dello skew premium e del credit/width
|
||||
ratio sui regimi reali,
|
||||
* l'analisi ex-post degli strike picker.
|
||||
|
||||
Il collector è **best-effort**: se ``get_tickers`` fallisce per un
|
||||
batch, gli altri batch passano comunque; se manca completamente la
|
||||
chain, il job ritorna 0 senza alzare eccezioni e logga il problema.
|
||||
Non chiama l'order book per ogni strike (sarebbe troppo costoso) —
|
||||
``book_depth_top3`` resta NULL nel quote, il liquidity gate del live
|
||||
lo legge al volo solo per gli strike che gli interessano.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from decimal import Decimal
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from cerbero_bite.state import connect, transaction
|
||||
from cerbero_bite.state.models import OptionChainQuoteRecord
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from cerbero_bite.runtime.dependencies import RuntimeContext
|
||||
|
||||
__all__ = ["DEFAULT_BATCH_SIZE", "collect_option_chain_snapshot"]
|
||||
|
||||
|
||||
_log = logging.getLogger("cerbero_bite.runtime.option_chain_snapshot")
|
||||
|
||||
|
||||
DEFAULT_BATCH_SIZE = 20 # Deribit get_ticker_batch limit
|
||||
|
||||
|
||||
def _to_decimal_or_none(value: Any) -> Decimal | None:
|
||||
if value is None:
|
||||
return None
|
||||
try:
|
||||
return Decimal(str(value))
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
async def _fetch_tickers_in_batches(
|
||||
ctx: RuntimeContext, names: list[str], *, batch_size: int = DEFAULT_BATCH_SIZE
|
||||
) -> dict[str, dict[str, Any]]:
|
||||
"""Best-effort fetch dei ticker per tutti i nomi richiesti."""
|
||||
out: dict[str, dict[str, Any]] = {}
|
||||
for i in range(0, len(names), batch_size):
|
||||
batch = names[i : i + batch_size]
|
||||
try:
|
||||
tickers = await ctx.deribit.get_tickers(batch)
|
||||
except Exception as exc:
|
||||
_log.warning(
|
||||
"get_tickers failed for batch starting %s: %s",
|
||||
batch[0] if batch else "<empty>", exc,
|
||||
)
|
||||
continue
|
||||
for t in tickers:
|
||||
name = t.get("instrument_name") or t.get("instrument")
|
||||
if isinstance(name, str):
|
||||
out[name] = t
|
||||
return out
|
||||
|
||||
|
||||
async def collect_option_chain_snapshot(
|
||||
ctx: RuntimeContext,
|
||||
*,
|
||||
asset: str = "ETH",
|
||||
now: datetime | None = None,
|
||||
batch_size: int = DEFAULT_BATCH_SIZE,
|
||||
) -> int:
|
||||
"""Collect + persist a single chain snapshot for ``asset``. Returns
|
||||
the number of quotes persisted (0 on best-effort failure).
|
||||
|
||||
Filtra le scadenze nella finestra ``[dte_min, dte_max]`` di
|
||||
``cfg.structure`` per non sprecare richieste su scadenze che il
|
||||
rule engine non userebbe mai.
|
||||
"""
|
||||
when = (now or datetime.now(UTC)).astimezone(UTC)
|
||||
cfg = ctx.cfg
|
||||
|
||||
expiry_from = when + timedelta(days=cfg.structure.dte_min)
|
||||
expiry_to = when + timedelta(days=cfg.structure.dte_max)
|
||||
|
||||
try:
|
||||
chain = await ctx.deribit.options_chain(
|
||||
currency=asset.upper(),
|
||||
expiry_from=expiry_from,
|
||||
expiry_to=expiry_to,
|
||||
min_open_interest=int(cfg.liquidity.open_interest_min),
|
||||
)
|
||||
except Exception:
|
||||
_log.exception("option chain fetch failed")
|
||||
return 0
|
||||
|
||||
if not chain:
|
||||
_log.info("option chain empty for %s in window", asset)
|
||||
return 0
|
||||
|
||||
names = [meta.name for meta in chain]
|
||||
tickers = await _fetch_tickers_in_batches(ctx, names, batch_size=batch_size)
|
||||
|
||||
quotes: list[OptionChainQuoteRecord] = []
|
||||
for meta in chain:
|
||||
ticker = tickers.get(meta.name)
|
||||
if ticker is None:
|
||||
# Lasciamo comunque la riga senza quote: utile sapere
|
||||
# che lo strumento esisteva.
|
||||
quotes.append(
|
||||
OptionChainQuoteRecord(
|
||||
timestamp=when,
|
||||
asset=asset.upper(),
|
||||
instrument_name=meta.name,
|
||||
strike=meta.strike,
|
||||
expiry=meta.expiry,
|
||||
option_type=meta.option_type,
|
||||
open_interest=int(meta.open_interest)
|
||||
if meta.open_interest is not None
|
||||
else None,
|
||||
)
|
||||
)
|
||||
continue
|
||||
greeks = ticker.get("greeks") or {}
|
||||
quotes.append(
|
||||
OptionChainQuoteRecord(
|
||||
timestamp=when,
|
||||
asset=asset.upper(),
|
||||
instrument_name=meta.name,
|
||||
strike=meta.strike,
|
||||
expiry=meta.expiry,
|
||||
option_type=meta.option_type,
|
||||
bid=_to_decimal_or_none(ticker.get("bid")),
|
||||
ask=_to_decimal_or_none(ticker.get("ask")),
|
||||
mid=_to_decimal_or_none(ticker.get("mark_price")),
|
||||
iv=_to_decimal_or_none(ticker.get("mark_iv")),
|
||||
delta=_to_decimal_or_none(greeks.get("delta")),
|
||||
gamma=_to_decimal_or_none(greeks.get("gamma")),
|
||||
theta=_to_decimal_or_none(greeks.get("theta")),
|
||||
vega=_to_decimal_or_none(greeks.get("vega")),
|
||||
open_interest=int(meta.open_interest)
|
||||
if meta.open_interest is not None
|
||||
else None,
|
||||
volume_24h=(
|
||||
int(ticker["volume_24h"])
|
||||
if ticker.get("volume_24h") is not None
|
||||
else None
|
||||
),
|
||||
# book_depth_top3: NULL — non lo prendiamo per ogni
|
||||
# strike per non saturare l'API. Il liquidity gate
|
||||
# del live lo chiede on-the-fly per gli strike
|
||||
# candidati al picker.
|
||||
)
|
||||
)
|
||||
|
||||
persisted = 0
|
||||
try:
|
||||
conn = connect(ctx.db_path)
|
||||
try:
|
||||
with transaction(conn):
|
||||
persisted = ctx.repository.record_option_chain_snapshot(
|
||||
conn, quotes
|
||||
)
|
||||
finally:
|
||||
conn.close()
|
||||
except Exception:
|
||||
_log.exception("persist option chain snapshot failed")
|
||||
return 0
|
||||
|
||||
_log.info("option_chain_snapshot persisted %d quote(s)", persisted)
|
||||
return persisted
|
||||
|
||||
|
||||
# Avoid unused import warning for asyncio in lint when only used as type
|
||||
_ = asyncio
|
||||
@@ -34,6 +34,9 @@ from cerbero_bite.runtime.market_snapshot_cycle import (
|
||||
DEFAULT_ASSETS,
|
||||
collect_market_snapshot,
|
||||
)
|
||||
from cerbero_bite.runtime.option_chain_snapshot_cycle import (
|
||||
collect_option_chain_snapshot,
|
||||
)
|
||||
from cerbero_bite.runtime.monitor_cycle import MonitorCycleResult, run_monitor_cycle
|
||||
from cerbero_bite.runtime.recovery import recover_state
|
||||
from cerbero_bite.runtime.scheduler import JobSpec, build_scheduler
|
||||
@@ -53,6 +56,7 @@ _CRON_HEALTH = "*/5 * * * *"
|
||||
_CRON_BACKUP = "0 * * * *"
|
||||
_CRON_MANUAL_ACTIONS = "*/1 * * * *"
|
||||
_CRON_MARKET_SNAPSHOT = "*/15 * * * *"
|
||||
_CRON_OPTION_CHAIN_SNAPSHOT = "55 13 * * MON" # 5 min prima del trigger entry
|
||||
_BACKUP_RETENTION_DAYS = 30
|
||||
|
||||
|
||||
@@ -217,6 +221,8 @@ class Orchestrator:
|
||||
manual_actions_cron: str = _CRON_MANUAL_ACTIONS,
|
||||
market_snapshot_cron: str = _CRON_MARKET_SNAPSHOT,
|
||||
market_snapshot_assets: tuple[str, ...] = DEFAULT_ASSETS,
|
||||
option_chain_cron: str = _CRON_OPTION_CHAIN_SNAPSHOT,
|
||||
option_chain_asset: str = "ETH",
|
||||
backup_dir: Path | None = None,
|
||||
backup_retention_days: int = _BACKUP_RETENTION_DAYS,
|
||||
) -> AsyncIOScheduler:
|
||||
@@ -282,6 +288,14 @@ class Orchestrator:
|
||||
|
||||
await _safe("market_snapshot", _do)
|
||||
|
||||
async def _option_chain_snapshot() -> None:
|
||||
async def _do() -> None:
|
||||
await collect_option_chain_snapshot(
|
||||
self._ctx, asset=option_chain_asset
|
||||
)
|
||||
|
||||
await _safe("option_chain_snapshot", _do)
|
||||
|
||||
jobs: list[JobSpec] = [
|
||||
JobSpec(name="health", cron=health_cron, coro_factory=_health),
|
||||
JobSpec(name="backup", cron=backup_cron, coro_factory=_backup),
|
||||
@@ -309,6 +323,13 @@ class Orchestrator:
|
||||
coro_factory=_market_snapshot,
|
||||
)
|
||||
)
|
||||
jobs.append(
|
||||
JobSpec(
|
||||
name="option_chain_snapshot",
|
||||
cron=option_chain_cron,
|
||||
coro_factory=_option_chain_snapshot,
|
||||
)
|
||||
)
|
||||
else:
|
||||
_log.warning(
|
||||
"data analysis disabled (CERBERO_BITE_ENABLE_DATA_ANALYSIS="
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
-- 0004_option_chain_snapshots.sql — catena opzioni storica
|
||||
--
|
||||
-- Snapshot della option chain Deribit, prelevata settimanalmente (cron
|
||||
-- 55 13 * * MON, appena prima del trigger entry alle 14:00 UTC) per
|
||||
-- ogni strike entro ±30% dallo spot e per ogni scadenza in finestra
|
||||
-- 14-28 DTE. Dato di base per il backtest non-stilizzato e per
|
||||
-- calibrare empiricamente lo skew premium del modello BS.
|
||||
--
|
||||
-- Granularità: una riga per (snapshot_ts, instrument). Lo
|
||||
-- snapshot_ts è il timestamp del cron tick — TUTTI i quote raccolti
|
||||
-- in quello stesso tick condividono il timestamp, così filtrare per
|
||||
-- "lo snapshot del 2026-05-04 alle 13:55" è una semplice
|
||||
-- WHERE timestamp = X.
|
||||
|
||||
CREATE TABLE option_chain_snapshots (
|
||||
timestamp TEXT NOT NULL,
|
||||
asset TEXT NOT NULL,
|
||||
instrument_name TEXT NOT NULL,
|
||||
strike TEXT NOT NULL,
|
||||
expiry TEXT NOT NULL,
|
||||
option_type TEXT NOT NULL CHECK (option_type IN ('C','P')),
|
||||
bid TEXT,
|
||||
ask TEXT,
|
||||
mid TEXT,
|
||||
iv TEXT,
|
||||
delta TEXT,
|
||||
gamma TEXT,
|
||||
theta TEXT,
|
||||
vega TEXT,
|
||||
open_interest INTEGER,
|
||||
volume_24h INTEGER,
|
||||
book_depth_top3 INTEGER,
|
||||
PRIMARY KEY (timestamp, instrument_name)
|
||||
) WITHOUT ROWID;
|
||||
|
||||
CREATE INDEX idx_option_chain_asset_ts
|
||||
ON option_chain_snapshots(asset, timestamp DESC);
|
||||
|
||||
CREATE INDEX idx_option_chain_expiry
|
||||
ON option_chain_snapshots(asset, expiry);
|
||||
|
||||
PRAGMA user_version = 5;
|
||||
@@ -22,6 +22,7 @@ __all__ = [
|
||||
"InstructionRecord",
|
||||
"ManualAction",
|
||||
"MarketSnapshotRecord",
|
||||
"OptionChainQuoteRecord",
|
||||
"PositionRecord",
|
||||
"PositionStatus",
|
||||
"SystemStateRecord",
|
||||
@@ -148,6 +149,36 @@ class MarketSnapshotRecord(BaseModel):
|
||||
fetch_errors_json: str | None = None
|
||||
|
||||
|
||||
class OptionChainQuoteRecord(BaseModel):
|
||||
"""Row of the ``option_chain_snapshots`` table.
|
||||
|
||||
One row per (snapshot_ts, instrument) — the same ``timestamp`` is
|
||||
shared by every quote prelevato nello stesso tick del cron. Tutti
|
||||
i campi numerici sono opzionali perché il collector è
|
||||
best-effort: un ticker mancante non invalida il resto della chain.
|
||||
"""
|
||||
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
timestamp: datetime
|
||||
asset: str
|
||||
instrument_name: str
|
||||
strike: Decimal
|
||||
expiry: datetime
|
||||
option_type: Literal["C", "P"]
|
||||
bid: Decimal | None = None
|
||||
ask: Decimal | None = None
|
||||
mid: Decimal | None = None
|
||||
iv: Decimal | None = None
|
||||
delta: Decimal | None = None
|
||||
gamma: Decimal | None = None
|
||||
theta: Decimal | None = None
|
||||
vega: Decimal | None = None
|
||||
open_interest: int | None = None
|
||||
volume_24h: int | None = None
|
||||
book_depth_top3: int | None = None
|
||||
|
||||
|
||||
class ManualAction(BaseModel):
|
||||
"""Row of the ``manual_actions`` table."""
|
||||
|
||||
|
||||
@@ -24,6 +24,7 @@ from cerbero_bite.state.models import (
|
||||
InstructionRecord,
|
||||
ManualAction,
|
||||
MarketSnapshotRecord,
|
||||
OptionChainQuoteRecord,
|
||||
PositionRecord,
|
||||
PositionStatus,
|
||||
SystemStateRecord,
|
||||
@@ -407,6 +408,103 @@ class Repository:
|
||||
).fetchall()
|
||||
return [_row_to_market_snapshot(r) for r in rows]
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# option_chain_snapshots
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def record_option_chain_snapshot(
|
||||
self,
|
||||
conn: sqlite3.Connection,
|
||||
quotes: list[OptionChainQuoteRecord],
|
||||
) -> int:
|
||||
"""Bulk-insert dei quote di un singolo tick. Tutti i quote
|
||||
condividono lo stesso ``timestamp``. Idempotente per
|
||||
(timestamp, instrument_name)."""
|
||||
if not quotes:
|
||||
return 0
|
||||
rows = [
|
||||
(
|
||||
_enc_dt(q.timestamp),
|
||||
q.asset,
|
||||
q.instrument_name,
|
||||
_enc_dec(q.strike),
|
||||
_enc_dt(q.expiry),
|
||||
q.option_type,
|
||||
_enc_dec(q.bid),
|
||||
_enc_dec(q.ask),
|
||||
_enc_dec(q.mid),
|
||||
_enc_dec(q.iv),
|
||||
_enc_dec(q.delta),
|
||||
_enc_dec(q.gamma),
|
||||
_enc_dec(q.theta),
|
||||
_enc_dec(q.vega),
|
||||
q.open_interest,
|
||||
q.volume_24h,
|
||||
q.book_depth_top3,
|
||||
)
|
||||
for q in quotes
|
||||
]
|
||||
conn.executemany(
|
||||
"INSERT OR REPLACE INTO option_chain_snapshots("
|
||||
"timestamp, asset, instrument_name, strike, expiry, option_type, "
|
||||
"bid, ask, mid, iv, delta, gamma, theta, vega, "
|
||||
"open_interest, volume_24h, book_depth_top3) "
|
||||
"VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
|
||||
rows,
|
||||
)
|
||||
return len(rows)
|
||||
|
||||
def list_option_chain_snapshots(
|
||||
self,
|
||||
conn: sqlite3.Connection,
|
||||
*,
|
||||
asset: str,
|
||||
start: datetime | None = None,
|
||||
end: datetime | None = None,
|
||||
expiry_from: datetime | None = None,
|
||||
expiry_to: datetime | None = None,
|
||||
limit: int = 50000,
|
||||
) -> list[OptionChainQuoteRecord]:
|
||||
clauses: list[str] = ["asset = ?"]
|
||||
params: list[Any] = [asset]
|
||||
if start is not None:
|
||||
clauses.append("timestamp >= ?")
|
||||
params.append(_enc_dt(start))
|
||||
if end is not None:
|
||||
clauses.append("timestamp <= ?")
|
||||
params.append(_enc_dt(end))
|
||||
if expiry_from is not None:
|
||||
clauses.append("expiry >= ?")
|
||||
params.append(_enc_dt(expiry_from))
|
||||
if expiry_to is not None:
|
||||
clauses.append("expiry <= ?")
|
||||
params.append(_enc_dt(expiry_to))
|
||||
params.append(int(limit))
|
||||
rows = conn.execute(
|
||||
f"SELECT * FROM option_chain_snapshots "
|
||||
f"WHERE {' AND '.join(clauses)} "
|
||||
f"ORDER BY timestamp DESC, instrument_name ASC LIMIT ?",
|
||||
params,
|
||||
).fetchall()
|
||||
return [_row_to_option_chain_quote(r) for r in rows]
|
||||
|
||||
def latest_option_chain_timestamp(
|
||||
self,
|
||||
conn: sqlite3.Connection,
|
||||
*,
|
||||
asset: str,
|
||||
) -> datetime | None:
|
||||
"""Timestamp dell'ultimo snapshot raccolto per ``asset``,
|
||||
utile per stimare la freschezza del dato dalla GUI."""
|
||||
row = conn.execute(
|
||||
"SELECT timestamp FROM option_chain_snapshots "
|
||||
"WHERE asset = ? ORDER BY timestamp DESC LIMIT 1",
|
||||
(asset,),
|
||||
).fetchone()
|
||||
if row is None:
|
||||
return None
|
||||
return _dec_dt(row["timestamp"])
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# manual_actions
|
||||
# ------------------------------------------------------------------
|
||||
@@ -645,6 +743,38 @@ def _row_to_market_snapshot(row: sqlite3.Row) -> MarketSnapshotRecord:
|
||||
)
|
||||
|
||||
|
||||
def _row_to_option_chain_quote(row: sqlite3.Row) -> OptionChainQuoteRecord:
|
||||
return OptionChainQuoteRecord(
|
||||
timestamp=_dec_dt_required(row["timestamp"]),
|
||||
asset=row["asset"],
|
||||
instrument_name=row["instrument_name"],
|
||||
strike=_dec_dec_required(row["strike"]),
|
||||
expiry=_dec_dt_required(row["expiry"]),
|
||||
option_type=row["option_type"],
|
||||
bid=_dec_dec(row["bid"]),
|
||||
ask=_dec_dec(row["ask"]),
|
||||
mid=_dec_dec(row["mid"]),
|
||||
iv=_dec_dec(row["iv"]),
|
||||
delta=_dec_dec(row["delta"]),
|
||||
gamma=_dec_dec(row["gamma"]),
|
||||
theta=_dec_dec(row["theta"]),
|
||||
vega=_dec_dec(row["vega"]),
|
||||
open_interest=(
|
||||
int(row["open_interest"])
|
||||
if row["open_interest"] is not None
|
||||
else None
|
||||
),
|
||||
volume_24h=(
|
||||
int(row["volume_24h"]) if row["volume_24h"] is not None else None
|
||||
),
|
||||
book_depth_top3=(
|
||||
int(row["book_depth_top3"])
|
||||
if row["book_depth_top3"] is not None
|
||||
else None
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _dec_dec_required(value: Any) -> Decimal:
|
||||
out = _dec_dec(value)
|
||||
if out is None:
|
||||
|
||||
@@ -0,0 +1,180 @@
|
||||
# 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: 25–40% 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.0.0-aggressiva"
|
||||
config_hash: "b931a2b96fbc149b21cae84a196ee8bad10220b5ee8fa9ab0ed06ae52d7dc531"
|
||||
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"
|
||||
|
||||
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"
|
||||
|
||||
monitor_cron: "0 2,14 * * *"
|
||||
user_confirmation_timeout_min: 30
|
||||
|
||||
escalate_on_timeout:
|
||||
- "CLOSE_STOP"
|
||||
- "CLOSE_VOL"
|
||||
- "CLOSE_DELTA"
|
||||
|
||||
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"
|
||||
@@ -0,0 +1,164 @@
|
||||
# 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: 10–20% 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.0.0-conservativa"
|
||||
config_hash: "eff824281bbb538fba49434d8cc4b9c37675bc73d60e351293e263cc7e7b29ef"
|
||||
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"
|
||||
|
||||
monitor_cron: "0 2,14 * * *"
|
||||
user_confirmation_timeout_min: 30
|
||||
|
||||
escalate_on_timeout:
|
||||
- "CLOSE_STOP"
|
||||
- "CLOSE_VOL"
|
||||
- "CLOSE_DELTA"
|
||||
|
||||
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"
|
||||
@@ -129,6 +129,7 @@ def test_install_scheduler_registers_canonical_jobs(tmp_path: Path) -> None:
|
||||
"backup",
|
||||
"manual_actions",
|
||||
"market_snapshot",
|
||||
"option_chain_snapshot",
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
"""TDD per :mod:`cerbero_bite.runtime.option_chain_snapshot_cycle`."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime
|
||||
from decimal import Decimal
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
from cerbero_bite.clients.deribit import InstrumentMeta
|
||||
from cerbero_bite.runtime.option_chain_snapshot_cycle import (
|
||||
collect_option_chain_snapshot,
|
||||
)
|
||||
from cerbero_bite.state.models import OptionChainQuoteRecord
|
||||
|
||||
|
||||
_NOW = datetime(2026, 5, 4, 13, 55, tzinfo=UTC)
|
||||
|
||||
|
||||
def _meta(name: str, strike: int, expiry_dte: int = 18) -> InstrumentMeta:
|
||||
expiry = _NOW.replace(hour=8, minute=0, second=0)
|
||||
expiry = expiry.replace(day=expiry.day) + (
|
||||
# add days
|
||||
__import__("datetime").timedelta(days=expiry_dte)
|
||||
)
|
||||
return InstrumentMeta(
|
||||
name=name,
|
||||
strike=Decimal(str(strike)),
|
||||
expiry=expiry,
|
||||
option_type="P",
|
||||
open_interest=Decimal("100"),
|
||||
tick_size=Decimal("0.0005"),
|
||||
min_trade_amount=Decimal("1"),
|
||||
)
|
||||
|
||||
|
||||
def _ticker(name: str, *, mark: float = 0.020, bid: float = 0.018,
|
||||
ask: float = 0.022, delta: float = -0.12) -> dict:
|
||||
return {
|
||||
"instrument_name": name,
|
||||
"bid": bid,
|
||||
"ask": ask,
|
||||
"mark_price": mark,
|
||||
"mark_iv": 60.0,
|
||||
"volume_24h": 50,
|
||||
"greeks": {
|
||||
"delta": delta,
|
||||
"gamma": 0.001,
|
||||
"theta": -0.0005,
|
||||
"vega": 0.10,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def cfg() -> object:
|
||||
from cerbero_bite.config import golden_config
|
||||
return golden_config()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def fake_ctx(cfg: object) -> MagicMock:
|
||||
"""Mock minimal RuntimeContext."""
|
||||
ctx = MagicMock()
|
||||
ctx.cfg = cfg
|
||||
ctx.db_path = ":memory:"
|
||||
return ctx
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_collector_persists_one_quote_per_instrument(
|
||||
fake_ctx: MagicMock,
|
||||
) -> None:
|
||||
metas = [_meta("ETH-21MAY26-2475-P", 2475), _meta("ETH-21MAY26-2400-P", 2400)]
|
||||
fake_ctx.deribit.options_chain = AsyncMock(return_value=metas)
|
||||
fake_ctx.deribit.get_tickers = AsyncMock(
|
||||
return_value=[_ticker(m.name) for m in metas]
|
||||
)
|
||||
persisted: list[list[OptionChainQuoteRecord]] = []
|
||||
|
||||
def _record(_conn: object, qs: list[OptionChainQuoteRecord]) -> int:
|
||||
persisted.append(qs)
|
||||
return len(qs)
|
||||
|
||||
fake_ctx.repository.record_option_chain_snapshot = _record
|
||||
|
||||
n = await collect_option_chain_snapshot(fake_ctx, asset="ETH", now=_NOW)
|
||||
assert n == 2
|
||||
assert len(persisted) == 1
|
||||
assert {q.instrument_name for q in persisted[0]} == {
|
||||
"ETH-21MAY26-2475-P", "ETH-21MAY26-2400-P",
|
||||
}
|
||||
# Tutti i quote condividono il timestamp del cron tick.
|
||||
assert all(q.timestamp == _NOW for q in persisted[0])
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_collector_handles_missing_tickers_with_null_fields(
|
||||
fake_ctx: MagicMock,
|
||||
) -> None:
|
||||
metas = [_meta("ETH-21MAY26-2475-P", 2475)]
|
||||
fake_ctx.deribit.options_chain = AsyncMock(return_value=metas)
|
||||
fake_ctx.deribit.get_tickers = AsyncMock(return_value=[]) # vuoto
|
||||
persisted: list[list[OptionChainQuoteRecord]] = []
|
||||
|
||||
def _record(_conn: object, qs: list[OptionChainQuoteRecord]) -> int:
|
||||
persisted.append(qs)
|
||||
return len(qs)
|
||||
|
||||
fake_ctx.repository.record_option_chain_snapshot = _record
|
||||
|
||||
n = await collect_option_chain_snapshot(fake_ctx, now=_NOW)
|
||||
assert n == 1
|
||||
assert persisted[0][0].mid is None # ticker mancante ⇒ campi NULL
|
||||
assert persisted[0][0].instrument_name == "ETH-21MAY26-2475-P"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_collector_returns_zero_when_chain_empty(
|
||||
fake_ctx: MagicMock,
|
||||
) -> None:
|
||||
fake_ctx.deribit.options_chain = AsyncMock(return_value=[])
|
||||
n = await collect_option_chain_snapshot(fake_ctx, now=_NOW)
|
||||
assert n == 0
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_collector_swallows_chain_fetch_failure(
|
||||
fake_ctx: MagicMock,
|
||||
) -> None:
|
||||
fake_ctx.deribit.options_chain = AsyncMock(side_effect=RuntimeError("boom"))
|
||||
n = await collect_option_chain_snapshot(fake_ctx, now=_NOW)
|
||||
assert n == 0 # best-effort: non rilancia
|
||||
Reference in New Issue
Block a user