21e865ffb0
Espone la GUI Streamlit su https://cerbero-bite.tielogic.xyz tramite il Traefik già attivo sull'host (label allineate al pattern di cerbero-mcp, TLS via Let's Encrypt, websocket pass-through). Aggiunge: - nuova tab `📚 Strategia` con stato live dei gate §2 confrontati con l'ultimo tick di market_snapshots, pannello P/L parametrico affiancato Conservativa vs Aggressiva, tabella di sensibilità win-rate → APR e rendering del documento canonico esteso. - doc `13-strategia-spiegata.md` che lega ogni regola §2-§9 al campo di market_snapshots che la alimenta, con sezioni §4-bis (P/L atteso realistico, win-rate empirico, drawdown, Sharpe) e §4-ter (confronto fra i due profili e quando passare dall'uno all'altro). - `strategy.conservativa.yaml` (golden config v1.0.0 esplicita) e `strategy.aggressiva.yaml` (cap_per_trade 4×, max_concurrent 2×, max_contracts 4×, deroga §11 documentata) con config_hash validi. - nel compose: servizio dedicato `cerbero-bite-gui` (Streamlit su 0.0.0.0:8765, healthcheck su /_stcore/health, label Traefik), env condivisi via anchor YAML `x-bite-env`, `--environment mainnet` passato a `start` per allineare il boot check al token del .env (era testnet vs mainnet → kill switch armato all'avvio). - Dockerfile installa anche l'extra `gui` (streamlit) e copia `docs/` + i due nuovi profili nell'immagine; `.dockerignore` non esclude più `docs/` (causa del primo build silenzioso). Fix bonus: `_try_load` nella pagina ritornava `LoadedConfig` ma la GUI leggeva `.sizing.*` direttamente — l'`except: pass` mascherava l'AttributeError facendo cadere sui default conservativi sia nel pannello P/L sia nello stato gate (stesso pattern presente nella Calibrazione). Ora ritorna `.config`. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
649 lines
21 KiB
Python
649 lines
21 KiB
Python
"""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()
|