Compare commits
3 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| bec2fb2089 | |||
| 9c48cdd884 | |||
| 9ed2ea4b13 |
@@ -63,7 +63,10 @@ Prima ondata di ricerca onesta su BTC/ETH certificati (5 track, harness condivis
|
|||||||
- **Universo Hyperliquid: ESPANDERLO NON aiuta XS01** (provato): 52-asset / top-liquidità dinamico /
|
- **Universo Hyperliquid: ESPANDERLO NON aiuta XS01** (provato): 52-asset / top-liquidità dinamico /
|
||||||
trend-multi-asset → tutti peggiori (small-cap/memecoin diluiscono il momentum relativo; il trend
|
trend-multi-asset → tutti peggiori (small-cap/memecoin diluiscono il momentum relativo; il trend
|
||||||
multi-asset è ridondante con TP01, corr 0.74). I margini su XS sono nella STRUTTURA DEL SEGNALE
|
multi-asset è ridondante con TP01, corr 0.74). I margini su XS sono nella STRUTTURA DEL SEGNALE
|
||||||
(blend + gate), non nel numero di asset. I 52 parquet certificati restano per ricerca futura.
|
(blend + gate), non nel numero di asset. I **51** parquet certificati restano per ricerca futura.
|
||||||
|
⚠️ Il test "52-asset = negativo" era in parte inquinato dal backfill sintetico (AXS 83%, ALGO/SAND
|
||||||
|
37% di barre vol=0) poi rimosso — vedi correzione estrazione 2026-06-20 sotto; resta comunque vero
|
||||||
|
che il long-tail diluisce XS01, ma il numero netto post-fix è 51.
|
||||||
- **Lead OPZIONI VRP (income short-vol) — quantificato, NON deploy** — `scripts/research/options_vrp_*.py`.
|
- **Lead OPZIONI VRP (income short-vol) — quantificato, NON deploy** — `scripts/research/options_vrp_*.py`.
|
||||||
Vendita put settimanali che incassa il volatility risk premium (IV>RV), scorrelato al trend (~0.07).
|
Vendita put settimanali che incassa il volatility risk premium (IV>RV), scorrelato al trend (~0.07).
|
||||||
Premio prezzato BS su DVOL reale (`fetch_dvol.py`) + calibrato su quote REALI cerbero-bite mainnet
|
Premio prezzato BS su DVOL reale (`fetch_dvol.py`) + calibrato su quote REALI cerbero-bite mainnet
|
||||||
@@ -169,6 +172,13 @@ df = load_data("BTC", "1h") # OK. load_data("SOL", ...) -> FileNotFoundError (
|
|||||||
nativa solo **~2.5 anni** (2024-2026; pre-2024 = backfill, vol 0). Abilita le strategie
|
nativa solo **~2.5 anni** (2024-2026; pre-2024 = backfill, vol 0). Abilita le strategie
|
||||||
CROSS-SECTIONAL (impossibili a 2 asset). NB: Cerbero col token TESTNET = farlocco; col token
|
CROSS-SECTIONAL (impossibili a 2 asset). NB: Cerbero col token TESTNET = farlocco; col token
|
||||||
**mainnet** (`.env.mainnet`) = reale, ma SEMPRE da certificare (cross-venue + liquidità).
|
**mainnet** (`.env.mainnet`) = reale, ma SEMPRE da certificare (cross-venue + liquidità).
|
||||||
|
⚠️ **CORREZIONE estrazione (2026-06-20):** il backfill NON è solo pre-2024 — cerbero MCP padda con
|
||||||
|
barre SINTETICHE (volume 0, prezzi copiati da Binance → matchano cross-venue e non sono flat) ogni
|
||||||
|
asset listato su HL **dopo** lo START. Il `flat`+cross-venue da soli non lo vedono: il rivelatore è
|
||||||
|
il **VOLUME**. `fetch_hyperliquid.py` ora (1) taglia il run iniziale a volume 0, (2) scarta chi resta
|
||||||
|
< 365g reali (es. **AXS 83% sintetico → fuori**), (3) gata i gap vol=0 interni. Universo certificato
|
||||||
|
= **51** (era 52). I **19 major di XS01 hanno 0 backfill → invariati** (strategia live non toccata).
|
||||||
|
Verificato direttamente su cerbero MCP. Diario `2026-06-20-cerbero-backfill-fix.md`.
|
||||||
|
|
||||||
## Metodologia obbligatoria per ogni nuova strategia
|
## Metodologia obbligatoria per ogni nuova strategia
|
||||||
|
|
||||||
|
|||||||
@@ -10,3 +10,6 @@ services:
|
|||||||
- "8787:8787"
|
- "8787:8787"
|
||||||
volumes:
|
volumes:
|
||||||
- ./data:/app/data:ro
|
- ./data:/app/data:ro
|
||||||
|
# token mainnet (sola lettura) per lo "Shadow live": conto/posizioni reali sulla dashboard.
|
||||||
|
# Montato a runtime (NON nell'immagine: .env.mainnet e' dockerignored). Solo letture, nessun ordine.
|
||||||
|
- ./.env.mainnet:/app/.env.mainnet:ro
|
||||||
|
|||||||
@@ -0,0 +1,86 @@
|
|||||||
|
# 2026-06-20 — Correzione estrazione cerbero MCP: il backfill sintetico (vol=0) ingannava la certificazione
|
||||||
|
|
||||||
|
## Contesto
|
||||||
|
|
||||||
|
Richiesta: "analizza cerbero MCP correggendo l'estrazione dati storici secondo le analisi fatte".
|
||||||
|
Le analisi del progetto avevano già fissato un principio — *"storia nativa Hyperliquid solo dal 2024,
|
||||||
|
pre-2024 = backfill, volume 0"* — e `fetch_hyperliquid.py` lo gestiva con un floor `START=2024-01-01`.
|
||||||
|
**Il floor non basta.**
|
||||||
|
|
||||||
|
## Il difetto
|
||||||
|
|
||||||
|
`fetch_hl` chiedeva a cerbero MCP `get_historical` dal 2024-01-01 e certificava ogni asset con tre
|
||||||
|
gate: **flat-bar** (O==H==L==C), **cross-venue** (mediana |close − Binance| < 60 bps), **recency**.
|
||||||
|
Nessuno guardava il **volume**. Risultato: gli asset listati su HL *dopo* lo START passavano come
|
||||||
|
PULITO pur essendo in gran parte **backfill sintetico**.
|
||||||
|
|
||||||
|
Ispezione del volume sui parquet (leading run di barre a volume 0):
|
||||||
|
|
||||||
|
| asset | barre | leading vol=0 | primo trade reale | % sintetico |
|
||||||
|
|---|---|---|---|---|
|
||||||
|
| **AXS** | 902 | **748** | 2026-01-18 | **82.9%** |
|
||||||
|
| ALGO | 902 | 338 | 2024-12-04 | 37.5% |
|
||||||
|
| SAND | 902 | 338 | 2024-12-04 | 37.5% |
|
||||||
|
| AR | 902 | 58 | 2024-02-28 | 6.4% |
|
||||||
|
| ETC | 902 | 11 | 2024-01-12 | 1.2% |
|
||||||
|
| BTC/ETH + 19 major | 902 | 0 | 2024-01-01 | 0% |
|
||||||
|
|
||||||
|
AXS era **certificato PULITO** (flat 0%, cross-venue 9.5 bps) pur avendo solo ~5 mesi di trading reale.
|
||||||
|
|
||||||
|
## Verifica diretta su cerbero MCP (token mainnet)
|
||||||
|
|
||||||
|
Interrogato l'endpoint `cerbero-mcp.tielogic.xyz/mcp/tools/get_historical` (bot-tag
|
||||||
|
`pythagoras-mainnet`):
|
||||||
|
|
||||||
|
- **BTC**: 902 barre, leading vol=0 = 0, volume reale dal 2024-01-01 (V=699, 2437, 5306…). Nativo. ✓
|
||||||
|
- **AXS**: 902 barre, **748 leading vol=0**, primo vol>0 = 2026-01-18. Le barre a volume 0 hanno
|
||||||
|
prezzi (O/H/L/C) che **coincidono con Binance**:
|
||||||
|
|
||||||
|
| data | cerbero close | binance close | Δ |
|
||||||
|
|---|---|---|---|
|
||||||
|
| 2024-01-01 | 9.262 | 9.26 | 2.2 bps |
|
||||||
|
| 2024-01-02 | 8.949 | 8.94 | 10.1 bps |
|
||||||
|
| 2024-01-03 | 7.937 | 7.95 | 16.4 bps |
|
||||||
|
|
||||||
|
**Diagnosi provata:** cerbero MCP riempie il periodo pre-quotazione con barre **sintetiche — volume 0,
|
||||||
|
prezzi copiati da un venue di riferimento (Binance)**. Per questo i vecchi gate venivano ingannati:
|
||||||
|
- cross-venue passa → i prezzi *sono* Binance (Δ 1–16 bps);
|
||||||
|
- flat passa → le barre non sono flat (hanno movimento di prezzo);
|
||||||
|
- ma **volume 0** → su HL quelle candele **non erano negoziabili**. È esattamente il caso v2.0.0
|
||||||
|
(edge su un book che non c'era).
|
||||||
|
|
||||||
|
## Correzione (`scripts/analysis/fetch_hyperliquid.py`)
|
||||||
|
|
||||||
|
1. **Il VOLUME è il rivelatore del backfill** → `trim_backfill()` taglia il run iniziale di barre a
|
||||||
|
volume 0; si tiene solo la **serie nativa**.
|
||||||
|
2. **Gate storia nativa** `MIN_NATIVE_DAYS=365`: dopo il taglio serve ≥ 1 anno di vita reale →
|
||||||
|
scarta chi è troppo corto (AXS, 154 barre reali → fuori).
|
||||||
|
3. **Gate vol=0 interno** `INTERIOR_VOL0_MAX=5%`: gap di liquidità oltre il taglio iniziale.
|
||||||
|
4. **cross-venue/flat ricalcolati SOLO sulle barre reali** (non più sui sintetici).
|
||||||
|
5. **I parquet degli asset scartati vengono rimossi** (disco == set certificato; niente file
|
||||||
|
contaminati a riposo).
|
||||||
|
|
||||||
|
## Risultato
|
||||||
|
|
||||||
|
- Universo certificato: **52 → 51** (AXS scartato).
|
||||||
|
- ALGO/SAND (−338 barre), AR (−58), ETC (−11) ripuliti dal backfill → ora start reale corretto.
|
||||||
|
- **I 19 major di XS01 hanno 0 backfill → invariati**: la strategia live (`XS_UNIVERSE` esplicito) NON
|
||||||
|
è toccata. Verificato: portafoglio 3-way (TP01+XS01+VRP01) gira identico, FULL Sh 1.68 / HOLD 1.67.
|
||||||
|
- Re-fetch end-to-end su cerbero reale: 51 PULITO, sweep su tutti i file → 0 backfill residuo.
|
||||||
|
|
||||||
|
## Nota su una conclusione precedente
|
||||||
|
|
||||||
|
Il diario `2026-06-19-xsec-universe-expansion.md` concludeva "cross-section dei 52 = negativo". Quella
|
||||||
|
finestra includeva i sintetici (AXS 83%, ALGO/SAND 37% di barre vol=0 con ritorni non eseguibili): la
|
||||||
|
magnitudine del risultato era **in parte un artefatto**. La conclusione qualitativa (il long-tail
|
||||||
|
diluisce XS01; i 19 major sono il sweet spot) resta valida, ma il numero netto è 51 e il test andrebbe
|
||||||
|
ri-girato sui dati puliti se si volesse riusare quell'universo.
|
||||||
|
|
||||||
|
## Lezione
|
||||||
|
|
||||||
|
`flat` + cross-venue **non bastano** a certificare un feed che fa backfill copiando un altro venue: il
|
||||||
|
backfill è plausibile sui prezzi proprio perché è copiato. Il **volume** (=liquidità reale) è il gate
|
||||||
|
che mancava. Coerente con la regola di prim'ordine v2.0.0: certificare il dato — anche il *volume*,
|
||||||
|
non solo il prezzo — prima della strategia.
|
||||||
|
|
||||||
|
File: `scripts/analysis/fetch_hyperliquid.py`. Universo: `data/raw/hl_*_1d.parquet` (51, serie native).
|
||||||
@@ -2,11 +2,22 @@
|
|||||||
|
|
||||||
Hyperliquid (via cerbero-mcp mainnet) offre ~230 perp liquidi, ma storia nativa REALE solo dal
|
Hyperliquid (via cerbero-mcp mainnet) offre ~230 perp liquidi, ma storia nativa REALE solo dal
|
||||||
2024 (pre-2024 = backfill, volume 0). Qui scarico un set liquido a 1d (2024+), e CERTIFICO ogni
|
2024 (pre-2024 = backfill, volume 0). Qui scarico un set liquido a 1d (2024+), e CERTIFICO ogni
|
||||||
asset come BTC/ETH: cross-venue vs Binance (realismo) + flat-bar (liquidita'). Scrivo SOLO i puliti
|
asset come BTC/ETH: cross-venue vs Binance (realismo) + flat-bar + VOLUME (liquidita'). Scrivo SOLO
|
||||||
in data/raw/hl_<sym>_1d.parquet (namespace dedicato, NON mischiato col Deribit BTC/ETH).
|
i puliti in data/raw/hl_<sym>_1d.parquet (namespace dedicato, NON mischiato col Deribit BTC/ETH).
|
||||||
|
|
||||||
Disciplina: Cerbero ci ha gia' bruciato (testnet) -> niente fiducia, solo certificazione.
|
Disciplina: Cerbero ci ha gia' bruciato (testnet) -> niente fiducia, solo certificazione.
|
||||||
|
|
||||||
|
CORREZIONE estrazione (2026-06-20, "analisi fatte"): il floor START=2024-01-01 NON basta. Cerbero
|
||||||
|
restituisce BACKFILL SINTETICO (volume==0, ma prezzi copiati da un venue di riferimento -> matchano
|
||||||
|
Binance e NON sono flat) per il periodo PRIMA che l'asset quotasse davvero su Hyperliquid. Cosi'
|
||||||
|
asset listati a meta'/fine 2024+ passavano cross-venue+flat ed erano certificati PULITO pur essendo
|
||||||
|
in gran parte sintetici (es. AXS 83% backfill: trading reale solo da 2026-01; ALGO/SAND 37%). E' lo
|
||||||
|
stesso errore v2.0.0 (edge su un book che non c'era). Fix: (1) il VOLUME e' il rivelatore di backfill
|
||||||
|
-> si TAGLIA il run iniziale di barre a volume 0 e si tiene solo la serie NATIVA; (2) gate su storia
|
||||||
|
nativa minima (>= MIN_NATIVE_DAYS reali) -> scarta chi e' troppo corto dopo il taglio; (3) gate su
|
||||||
|
volume-0 INTERNO (gap di liquidita') oltre il taglio iniziale; (4) cross-venue/flat ricalcolati SOLO
|
||||||
|
sulle barre reali; (5) i parquet degli asset scartati vengono RIMOSSI (disco == set certificato).
|
||||||
|
|
||||||
uv run python scripts/analysis/fetch_hyperliquid.py
|
uv run python scripts/analysis/fetch_hyperliquid.py
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@@ -17,7 +28,9 @@ sys.path.insert(0, str(PROJECT_ROOT))
|
|||||||
import numpy as np, pandas as pd, requests, ccxt
|
import numpy as np, pandas as pd, requests, ccxt
|
||||||
|
|
||||||
RAW = PROJECT_ROOT / "data" / "raw"
|
RAW = PROJECT_ROOT / "data" / "raw"
|
||||||
START = "2024-01-01"; END = pd.Timestamp.utcnow().strftime("%Y-%m-%d") # dinamico (refresh giornaliero)
|
START = "2024-01-01"; END = pd.Timestamp.now("UTC").strftime("%Y-%m-%d") # dinamico (refresh giornaliero)
|
||||||
|
MIN_NATIVE_DAYS = 365 # storia NATIVA reale minima (post-taglio backfill) per entrare nell'universo
|
||||||
|
INTERIOR_VOL0_MAX = 5.0 # % max di barre a volume 0 DOPO il taglio iniziale (gap di liquidita' interni)
|
||||||
# UNIVERSO ESTESO: alt liquidi noti su Hyperliquid (mappa Binance auto = SYM/USDT). Il gate di
|
# UNIVERSO ESTESO: alt liquidi noti su Hyperliquid (mappa Binance auto = SYM/USDT). Il gate di
|
||||||
# certificazione (cross-venue + liquidita' + flat) scarta i non-conformi. k-prefissi esclusi
|
# certificazione (cross-venue + liquidita' + flat) scarta i non-conformi. k-prefissi esclusi
|
||||||
# (scaling 1000x complica il cross-venue). MATIC morto escluso.
|
# (scaling 1000x complica il cross-venue). MATIC morto escluso.
|
||||||
@@ -62,17 +75,33 @@ def binance_daily(sym_b, start_ms, end_ms):
|
|||||||
return pd.Series(out)
|
return pd.Series(out)
|
||||||
|
|
||||||
|
|
||||||
|
def trim_backfill(df):
|
||||||
|
"""Taglia il run INIZIALE di barre a volume 0 (= backfill sintetico pre-quotazione su HL).
|
||||||
|
Ritorna (serie_nativa, n_barre_tagliate). Il volume e' il rivelatore: il backfill copia i
|
||||||
|
prezzi da un venue di riferimento (non flat, matcha Binance) ma ha volume 0."""
|
||||||
|
vol = df["volume"].to_numpy()
|
||||||
|
lead = int(np.argmax(vol > 0)) if (vol > 0).any() else len(df)
|
||||||
|
return df.iloc[lead:].reset_index(drop=True), lead
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
H=_h()
|
H=_h()
|
||||||
print("="*92); print(" FETCH + CERTIFY Hyperliquid 1d (Cerbero mainnet) — cross-venue vs Binance + liquidita'"); print("="*92)
|
print("="*100); print(" FETCH + CERTIFY Hyperliquid 1d (Cerbero mainnet) — cross-venue + flat + VOLUME (no backfill)"); print("="*100)
|
||||||
print(f" {'sym':<6}{'barre':>7}{'start':>12}{'flat%':>7}{'med_bps':>9}{'>1%':>7}{'verdetto':>12}")
|
print(f" {'sym':<6}{'reali':>6}{'bfill':>6}{'start_reale':>13}{'flat%':>7}{'vol0%':>7}{'med_bps':>9}{'>1%':>7}{'verdetto':>14}")
|
||||||
certified=[]
|
certified=[]
|
||||||
for s in SYMS:
|
for s in SYMS:
|
||||||
df=fetch_hl(s,H)
|
path = RAW/f"hl_{s.lower()}_1d.parquet"
|
||||||
if df.empty: print(f" {s:<6} vuoto"); continue
|
raw=fetch_hl(s,H)
|
||||||
|
if raw.empty:
|
||||||
|
print(f" {s:<6} vuoto"); path.unlink(missing_ok=True); continue
|
||||||
|
# --- CORREZIONE: taglia il backfill sintetico (volume 0 iniziale), tieni la serie nativa ---
|
||||||
|
df, n_bfill = trim_backfill(raw)
|
||||||
|
if df.empty:
|
||||||
|
print(f" {s:<6} tutto backfill (vol0) -> scarta"); path.unlink(missing_ok=True); continue
|
||||||
ts=pd.to_datetime(df["timestamp"],unit="ms",utc=True)
|
ts=pd.to_datetime(df["timestamp"],unit="ms",utc=True)
|
||||||
flat=((df.open==df.high)&(df.high==df.low)&(df.low==df.close)).mean()*100
|
flat=((df.open==df.high)&(df.high==df.low)&(df.low==df.close)).mean()*100
|
||||||
# cross-venue vs Binance USDT (daily close)
|
vol0=(df["volume"].to_numpy()==0).mean()*100 # gap di liquidita' INTERNI (post-taglio)
|
||||||
|
# cross-venue vs Binance USDT (daily close) — SOLO sulle barre reali
|
||||||
ref=binance_daily(BINANCE[s], int(df["timestamp"].iloc[0]), int(df["timestamp"].iloc[-1]))
|
ref=binance_daily(BINANCE[s], int(df["timestamp"].iloc[0]), int(df["timestamp"].iloc[-1]))
|
||||||
a=df.set_index("timestamp")["close"]
|
a=df.set_index("timestamp")["close"]
|
||||||
m=pd.concat([a.rename("a"),ref.rename("b")],axis=1,join="inner").dropna()
|
m=pd.concat([a.rename("a"),ref.rename("b")],axis=1,join="inner").dropna()
|
||||||
@@ -83,13 +112,20 @@ def main():
|
|||||||
# gate "delistato/migrato": l'ultima barra dev'essere recente (entro ~21g da END),
|
# gate "delistato/migrato": l'ultima barra dev'essere recente (entro ~21g da END),
|
||||||
# altrimenti l'asset tronca l'universo cross-sectional (es. MKR fermo a 2025-09, FXS 2026-01).
|
# altrimenti l'asset tronca l'universo cross-sectional (es. MKR fermo a 2025-09, FXS 2026-01).
|
||||||
recent = (pd.Timestamp(END, tz="UTC") - ts.iloc[-1]) <= pd.Timedelta("21D")
|
recent = (pd.Timestamp(END, tz="UTC") - ts.iloc[-1]) <= pd.Timedelta("21D")
|
||||||
clean = (not np.isnan(med)) and med<60 and g1<3 and flat<5 and recent
|
# gate storia NATIVA: dopo il taglio dev'esserci abbastanza vita reale (es. AXS quotato 2026-01 -> scarta)
|
||||||
v = "PULITO" if clean else "scarta"
|
native_days = (ts.iloc[-1] - ts.iloc[0]).days
|
||||||
print(f" {s:<6}{len(df):>7}{str(ts.iloc[0].date()):>12}{flat:>6.1f}%{med:>9.1f}{g1:>6.1f}%{v:>12}")
|
enough = native_days >= MIN_NATIVE_DAYS
|
||||||
|
clean = (not np.isnan(med)) and med<60 and g1<3 and flat<5 and vol0<INTERIOR_VOL0_MAX and recent and enough
|
||||||
|
if clean: v="PULITO"
|
||||||
|
elif not enough: v=f"corto<{MIN_NATIVE_DAYS}g"
|
||||||
|
else: v="scarta"
|
||||||
|
print(f" {s:<6}{len(df):>6}{n_bfill:>6}{str(ts.iloc[0].date()):>13}{flat:>6.1f}%{vol0:>6.1f}%{med:>9.1f}{g1:>6.1f}%{v:>14}")
|
||||||
if clean:
|
if clean:
|
||||||
df.to_parquet(RAW/f"hl_{s.lower()}_1d.parquet", index=False); certified.append(s)
|
df.to_parquet(path, index=False); certified.append(s)
|
||||||
|
else:
|
||||||
|
path.unlink(missing_ok=True) # disco == set certificato (niente parquet contaminati a riposo)
|
||||||
print(f"\n CERTIFICATI ({len(certified)}): {certified}")
|
print(f"\n CERTIFICATI ({len(certified)}): {certified}")
|
||||||
print(" Scritti in data/raw/hl_<sym>_1d.parquet (namespace dedicato). Universo per cross-sectional.")
|
print(" Scritti in data/raw/hl_<sym>_1d.parquet (namespace dedicato, SERIE NATIVA senza backfill).")
|
||||||
|
|
||||||
|
|
||||||
if __name__=="__main__":
|
if __name__=="__main__":
|
||||||
|
|||||||
@@ -0,0 +1,78 @@
|
|||||||
|
"""TP01 LIVE — SHADOW MODE (Deribit mainnet, SOLA LETTURA, nessun ordine inviato).
|
||||||
|
|
||||||
|
Valida l'esecuzione di TP01 a RISCHIO ZERO: gira il loop live completo contro dati/conto/posizioni
|
||||||
|
REALI del mainnet, calcola i target causali (stesso codice del backtest/paper), costruisce gli ordini
|
||||||
|
di ribilancio esatti — e li STAMPA invece di inviarli. Confronta i target col paper trader (parita').
|
||||||
|
|
||||||
|
Perche' non testnet: il testnet Cerbero/Deribit e' la causa del reset v2.0.0 (feed farlocco). La
|
||||||
|
validazione a rischio zero qui e' "shadow su mainnet reale in sola lettura"; il fill (slippage/fee)
|
||||||
|
si valida solo col micro-test mainnet a size minima, in un passo successivo.
|
||||||
|
|
||||||
|
Logica condivisa con la dashboard in src/live/shadow.py (un solo codice, niente drift).
|
||||||
|
|
||||||
|
uv run python scripts/live/live_trend.py # shadow su mainnet reale
|
||||||
|
uv run python scripts/live/live_trend.py --equity 2000 # forza la base di sizing
|
||||||
|
uv run python scripts/live/live_trend.py --no-net # offline: solo matematica + parita'
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
PROJECT_ROOT = Path(__file__).resolve().parents[2]
|
||||||
|
sys.path.insert(0, str(PROJECT_ROOT))
|
||||||
|
|
||||||
|
from src.live.deribit import notional_to_amount
|
||||||
|
from src.live.shadow import shadow_report
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
argv = sys.argv[1:]
|
||||||
|
offline = "--no-net" in argv
|
||||||
|
equity_override = float(argv[argv.index("--equity") + 1]) if "--equity" in argv else None
|
||||||
|
r = shadow_report(offline=offline, equity_override=equity_override)
|
||||||
|
|
||||||
|
print("=" * 84)
|
||||||
|
print(" TP01 LIVE — SHADOW MODE (Deribit mainnet, SOLA LETTURA — NESSUN ORDINE INVIATO)")
|
||||||
|
print("=" * 84)
|
||||||
|
real_eq = r["real_equity"]
|
||||||
|
conto = f"${real_eq:,.2f}" if real_eq else r["eq_basis"]
|
||||||
|
print(f" ultima barra 1d chiusa : {r['last_data']}")
|
||||||
|
print(f" rete : {'mainnet via Cerbero MCP' if r['online'] else 'OFFLINE / fallback close'}")
|
||||||
|
print(f" prezzi mark : " + " | ".join(f"{a['asset']} ${a['mark']:,.1f} ({a['mark_src']})" for a in r["assets"]))
|
||||||
|
print(f" conto reale : {conto}")
|
||||||
|
print(f" posizioni reali : " + ", ".join(f"{a['asset']} ${a['position_usd']:,.0f}" for a in r["assets"]) + f" ({r['pos_src']})")
|
||||||
|
print(f" base di sizing : ${r['equity']:,.2f} [{r['eq_basis']}]")
|
||||||
|
|
||||||
|
print("\n PER ASSET (target causale @ ultima barra chiusa):")
|
||||||
|
for a in r["assets"]:
|
||||||
|
state = "FLAT" if abs(a["target"]) < 1e-9 else ("LONG" if a["target"] > 0 else "SHORT")
|
||||||
|
line = (f" {a['asset']:<3} {state:<5} target {a['target']:+.3f}x -> notional ${a['target_notional']:,.0f}"
|
||||||
|
f" (pos reale ${a['position_usd']:,.0f})")
|
||||||
|
o = a["order"]
|
||||||
|
if o:
|
||||||
|
print(line + f"\n -> ORDINE: {o['side'].upper()} {o['amount']:.0f} {a['instrument']} "
|
||||||
|
f"(market{', reduce_only' if o['reduce_only'] else ''}, delta ${o['delta_notional']:,.0f})")
|
||||||
|
else:
|
||||||
|
print(line + " -> nessun ordine (gia' a target / sotto-soglia)")
|
||||||
|
|
||||||
|
print("\n PARITA' vs paper trader (target = current_target):")
|
||||||
|
if all(a["paper"] is None for a in r["assets"]):
|
||||||
|
print(" (paper non inizializzato: avvia scripts/live/paper_trend.py)")
|
||||||
|
else:
|
||||||
|
for a in r["assets"]:
|
||||||
|
print(f" {a['asset']}: paper {a['paper']:+.3f}x shadow {a['target']:+.3f}x -> {'OK' if a['parity'] else 'DIFFERISCE'}")
|
||||||
|
if not r["paper_aligned"]:
|
||||||
|
print(" NB paper non all'ultima barra -> avanzalo se i target differiscono")
|
||||||
|
|
||||||
|
print("\n VERIFICA costruttore ordini (quantizzazione step/minimo):")
|
||||||
|
for inst, samples in (("BTC-PERPETUAL", [1000, 1005, 7, 250.4]), ("ETH-PERPETUAL", [1000, 0.4, 33.7])):
|
||||||
|
got = ", ".join(f"${s}->{notional_to_amount(inst, s):.0f}" for s in samples)
|
||||||
|
print(f" {inst}: {got}")
|
||||||
|
|
||||||
|
print("\n => NESSUN ORDINE INVIATO (shadow). " +
|
||||||
|
(f"{len(r['orders'])} ordine/i costruito/i sopra." if r["orders"] else "Target flat: 0 ordini."))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
+27
-4
@@ -15,6 +15,7 @@ sys.path.insert(0, str(PROJECT_ROOT))
|
|||||||
import numpy as np, pandas as pd
|
import numpy as np, pandas as pd
|
||||||
from src.portfolio.portfolio import StrategyPortfolio, metrics, HOLDOUT
|
from src.portfolio.portfolio import StrategyPortfolio, metrics, HOLDOUT
|
||||||
from src.portfolio.sleeves import active_sleeves
|
from src.portfolio.sleeves import active_sleeves
|
||||||
|
from src.live.shadow import shadow_report
|
||||||
from src.version import APP_VERSION
|
from src.version import APP_VERSION
|
||||||
|
|
||||||
PAPER = PROJECT_ROOT / "data" / "paper_portfolio" / "state.json"
|
PAPER = PROJECT_ROOT / "data" / "paper_portfolio" / "state.json"
|
||||||
@@ -32,12 +33,16 @@ def build():
|
|||||||
step = max(1, len(eq) // 400)
|
step = max(1, len(eq) // 400)
|
||||||
spark = [(str(idx[i].date()), float(eq[i])) for i in range(0, len(eq), step)]
|
spark = [(str(idx[i].date()), float(eq[i])) for i in range(0, len(eq), step)]
|
||||||
paper = json.loads(PAPER.read_text()) if PAPER.exists() else None
|
paper = json.loads(PAPER.read_text()) if PAPER.exists() else None
|
||||||
|
try:
|
||||||
|
shadow = shadow_report() # mainnet sola lettura, best-effort
|
||||||
|
except Exception as e:
|
||||||
|
shadow = {"error": f"{type(e).__name__}: {e}"}
|
||||||
data = dict(
|
data = dict(
|
||||||
version=APP_VERSION,
|
version=APP_VERSION,
|
||||||
last_data=str(idx[-1].date()),
|
last_data=str(idx[-1].date()),
|
||||||
full=bt["full"], holdout=bt["holdout"], weights=bt["weights"],
|
full=bt["full"], holdout=bt["holdout"], weights=bt["weights"],
|
||||||
per_sleeve=bt["per_sleeve"], yearly=bt["yearly"],
|
per_sleeve=bt["per_sleeve"], yearly=bt["yearly"],
|
||||||
positions=pf.current_positions(), spark=spark, paper=paper,
|
positions=pf.current_positions(), spark=spark, paper=paper, shadow=shadow,
|
||||||
bh=None,
|
bh=None,
|
||||||
)
|
)
|
||||||
_CACHE.update(t=time.time(), data=data)
|
_CACHE.update(t=time.time(), data=data)
|
||||||
@@ -77,6 +82,23 @@ def html():
|
|||||||
f"{pp['last'][:10]}, {days}g) ret <b>{ret*100:+.2f}%</b> maxDD {pp['max_dd']*100:.1f}%")
|
f"{pp['last'][:10]}, {days}g) ret <b>{ret*100:+.2f}%</b> maxDD {pp['max_dd']*100:.1f}%")
|
||||||
else:
|
else:
|
||||||
paper_html = "non inizializzato (gira <code>paper_portfolio.py</code>)"
|
paper_html = "non inizializzato (gira <code>paper_portfolio.py</code>)"
|
||||||
|
sh = d.get("shadow")
|
||||||
|
if sh and "error" not in sh:
|
||||||
|
bits = " · ".join(
|
||||||
|
f"{a['asset']} <b>{'FLAT' if abs(a['target'])<1e-9 else 'LONG' if a['target']>0 else 'SHORT'}</b> "
|
||||||
|
f"{a['target']:+.2f}x" for a in sh["assets"])
|
||||||
|
if sh.get("online"):
|
||||||
|
eq = f"${sh['real_equity']:,.2f}" if sh.get("real_equity") else sh.get("eq_basis", "?")
|
||||||
|
pos = ", ".join(f"{a['asset']} ${a['position_usd']:,.0f}" for a in sh["assets"])
|
||||||
|
ordtxt = ("; ".join(f"{o['side'].upper()} {o['amount']:.0f} {o['instrument']}" for o in sh["orders"])
|
||||||
|
if sh.get("orders") else "nessuno (target flat / gia' a target)")
|
||||||
|
shadow_html = (f"mainnet · sola lettura · conto reale <b>{eq}</b> · pos {pos} · dato {sh['last_data']}<br>"
|
||||||
|
f"TP01 target: {bits}<br>ordini-che-invierebbe (<b>NON inviati</b>): {ordtxt}")
|
||||||
|
else:
|
||||||
|
shadow_html = (f"conto reale non leggibile dal container (token solo su host) · dato {sh['last_data']}<br>"
|
||||||
|
f"TP01 target: {bits}<br>→ per gli ordini reali: <code>uv run python scripts/live/live_trend.py</code> (host)")
|
||||||
|
else:
|
||||||
|
shadow_html = "non disponibile" + (f" — {sh['error']}" if sh and sh.get('error') else "")
|
||||||
return f"""<!doctype html><html><head><meta charset=utf-8>
|
return f"""<!doctype html><html><head><meta charset=utf-8>
|
||||||
<meta http-equiv=refresh content=300><title>PythagorasGoal — Portafoglio</title>
|
<meta http-equiv=refresh content=300><title>PythagorasGoal — Portafoglio</title>
|
||||||
<style>body{{font-family:-apple-system,Segoe UI,Roboto,sans-serif;background:#0e1116;color:#e6e6e6;margin:0;padding:24px;max-width:980px;margin:auto}}
|
<style>body{{font-family:-apple-system,Segoe UI,Roboto,sans-serif;background:#0e1116;color:#e6e6e6;margin:0;padding:24px;max-width:980px;margin:auto}}
|
||||||
@@ -88,8 +110,8 @@ table{{width:100%;border-collapse:collapse;margin:8px 0 20px}}td,th{{text-align:
|
|||||||
th{{color:#8a93a0;font-weight:500}}.y{{display:inline-block;background:#161b22;border:1px solid #222b36;border-radius:6px;padding:3px 8px;margin:2px;font-size:12px}}
|
th{{color:#8a93a0;font-weight:500}}.y{{display:inline-block;background:#161b22;border:1px solid #222b36;border-radius:6px;padding:3px 8px;margin:2px;font-size:12px}}
|
||||||
.box{{background:#161b22;border:1px solid #222b36;border-radius:10px;padding:14px 18px;margin-bottom:18px}}
|
.box{{background:#161b22;border:1px solid #222b36;border-radius:10px;padding:14px 18px;margin-bottom:18px}}
|
||||||
.warn{{color:#f1c40f;font-size:12px}}</style></head><body>
|
.warn{{color:#f1c40f;font-size:12px}}</style></head><body>
|
||||||
<h1>PythagorasGoal — Portafoglio attivo (TP01 + XS01)</h1>
|
<h1>PythagorasGoal — Portafoglio attivo (TP01 + XS01 + VRP01)</h1>
|
||||||
<div class=sub>monitor PAPER · v{d['version']} · ultimo dato {d['last_data']} · esecuzione REALE disabilitata</div>
|
<div class=sub>monitor PAPER + SHADOW · v{d['version']} · ultimo dato {d['last_data']} · esecuzione REALE disabilitata</div>
|
||||||
<div class=cards>
|
<div class=cards>
|
||||||
<div class=card><div class=k>FULL Sharpe</div><div class="v g">{f['sharpe']:.2f}</div></div>
|
<div class=card><div class=k>FULL Sharpe</div><div class="v g">{f['sharpe']:.2f}</div></div>
|
||||||
<div class=card><div class=k>HOLD-OUT Sharpe (2025-26)</div><div class="v g">{ho['sharpe']:.2f}</div></div>
|
<div class=card><div class=k>HOLD-OUT Sharpe (2025-26)</div><div class="v g">{ho['sharpe']:.2f}</div></div>
|
||||||
@@ -99,12 +121,13 @@ th{{color:#8a93a0;font-weight:500}}.y{{display:inline-block;background:#161b22;b
|
|||||||
</div>
|
</div>
|
||||||
<div class=box><div class=k style="color:#8a93a0;font-size:12px">EQUITY backtest (2019→oggi, €2k)</div>{svg_spark(d['spark'])}</div>
|
<div class=box><div class=k style="color:#8a93a0;font-size:12px">EQUITY backtest (2019→oggi, €2k)</div>{svg_spark(d['spark'])}</div>
|
||||||
<div class=box><b>Paper forward-only:</b> {paper_html}</div>
|
<div class=box><b>Paper forward-only:</b> {paper_html}</div>
|
||||||
|
<div class=box><b>Shadow live — TP01 su Deribit</b> (sola lettura, nessun ordine inviato):<br>{shadow_html}</div>
|
||||||
<h3 style="font-size:14px;color:#8a93a0">Sleeve</h3>
|
<h3 style="font-size:14px;color:#8a93a0">Sleeve</h3>
|
||||||
<table><tr><th>sleeve</th><th>peso</th><th>FULL Sh</th><th>DD</th><th>HOLD Sh</th></tr>{rows}</table>
|
<table><tr><th>sleeve</th><th>peso</th><th>FULL Sh</th><th>DD</th><th>HOLD Sh</th></tr>{rows}</table>
|
||||||
<h3 style="font-size:14px;color:#8a93a0">Posizioni correnti (ultima barra chiusa)</h3>
|
<h3 style="font-size:14px;color:#8a93a0">Posizioni correnti (ultima barra chiusa)</h3>
|
||||||
<table>{pos}</table>
|
<table>{pos}</table>
|
||||||
<div style="margin-top:10px">{yrs}</div>
|
<div style="margin-top:10px">{yrs}</div>
|
||||||
<p class=warn>⚠️ Paper/monitor. XS01 e' STAT-MODE (book a 19 gambe market-neutral, non eseguibile a €2k). Storia XS ~2.5 anni.</p>
|
<p class=warn>⚠️ Paper/monitor. XS01 e' STAT-MODE (book a 19 gambe market-neutral, non eseguibile a €2k, storia ~2.5 anni). VRP01 = lead short-vol MODELLATO (non deploy pieno). TP01 e' l'unico deployable pieno: lo "Shadow live" mostra cosa farebbe sul mainnet, ma NON invia ordini.</p>
|
||||||
</body></html>"""
|
</body></html>"""
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,139 @@
|
|||||||
|
"""Accesso Deribit MAINNET in SOLA LETTURA (via Cerbero MCP) + costruttore ordini deterministico.
|
||||||
|
|
||||||
|
Serve lo SHADOW MODE di TP01 (`scripts/live/live_trend.py`): legge prezzi / conto / posizioni REALI
|
||||||
|
dal mainnet (token `.env.mainnet`) e costruisce gli ordini di ribilancio **senza inviarli**. Qui NON
|
||||||
|
esiste alcun metodo di trading — by design: l'unica via per piazzare ordini sara' un modulo separato,
|
||||||
|
abilitato esplicitamente, dopo la validazione shadow + micro-test.
|
||||||
|
|
||||||
|
Disciplina del progetto: **testnet FUORI** (feed farlocco, causa del reset v2.0.0). Solo mainnet reale,
|
||||||
|
e in questa fase solo in lettura. I contratti sono ristretti a BTC/ETH-PERPETUAL (inverse: `amount`
|
||||||
|
in USD notional, step verificato su Deribit: BTC $10, ETH $1).
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
from decimal import Decimal
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import requests
|
||||||
|
|
||||||
|
PROJECT_ROOT = Path(__file__).resolve().parents[2]
|
||||||
|
BASE_URL = os.environ.get("CERBERO_BASE_URL", "https://cerbero-mcp.tielogic.xyz")
|
||||||
|
TIMEOUT = 15
|
||||||
|
|
||||||
|
# Inverse perp: amount = USD notional, step in USD. settle = base-coin (per get_positions/fee).
|
||||||
|
_CONTRACT = {
|
||||||
|
"BTC-PERPETUAL": {"min": 10.0, "step": 10.0, "tick": 0.5, "settle": "BTC"},
|
||||||
|
"ETH-PERPETUAL": {"min": 1.0, "step": 1.0, "tick": 0.05, "settle": "ETH"},
|
||||||
|
}
|
||||||
|
INSTRUMENT = {"BTC": "BTC-PERPETUAL", "ETH": "ETH-PERPETUAL"}
|
||||||
|
|
||||||
|
|
||||||
|
# ----------------------------- costruzione ordini (pura, testabile, NIENTE rete) -----------------------------
|
||||||
|
|
||||||
|
def _quantize_step(value: float, step: float, mn: float) -> float:
|
||||||
|
"""Arrotonda al multiplo di `step` (Decimal, niente artefatti float), clampa al minimo."""
|
||||||
|
n = round(value / step)
|
||||||
|
return float(max(n * Decimal(str(step)), Decimal(str(mn))))
|
||||||
|
|
||||||
|
|
||||||
|
def notional_to_amount(instrument: str, notional_usd: float) -> float:
|
||||||
|
"""USD notional -> `amount` Deribit (inverse: amount in USD), arrotondato allo step e clampato
|
||||||
|
al minimo. Ritorna 0.0 se |notional| < mezzo step (sotto-soglia: niente ordine)."""
|
||||||
|
spec = _CONTRACT[instrument]
|
||||||
|
step, mn = spec["step"], spec["min"]
|
||||||
|
if abs(notional_usd) < step / 2:
|
||||||
|
return 0.0
|
||||||
|
return _quantize_step(abs(notional_usd), step, mn)
|
||||||
|
|
||||||
|
|
||||||
|
def target_notional_usd(target_fraction: float, weight: float, equity_usd: float) -> float:
|
||||||
|
"""Notional bersaglio (USD) di un asset = peso nel book * frazione-di-equity TP01 * equity.
|
||||||
|
Coerente col paper trader (esposizione asset = WEIGHT * target * equity)."""
|
||||||
|
return weight * target_fraction * equity_usd
|
||||||
|
|
||||||
|
|
||||||
|
def build_rebalance_order(instrument: str, target_fraction: float, weight: float,
|
||||||
|
equity_usd: float, current_pos_usd: float) -> dict | None:
|
||||||
|
"""COSTRUISCE (non invia) l'ordine di ribilancio verso il target. Ritorna un dict-ordine o None
|
||||||
|
se sotto-soglia. Long-only TP01 -> target_notional >= 0; delta = target - posizione corrente."""
|
||||||
|
tgt = target_notional_usd(target_fraction, weight, equity_usd)
|
||||||
|
delta = tgt - current_pos_usd
|
||||||
|
amount = notional_to_amount(instrument, delta)
|
||||||
|
if amount == 0.0:
|
||||||
|
return None
|
||||||
|
is_exit = abs(tgt) < 1e-9 and abs(current_pos_usd) > 0
|
||||||
|
return dict(
|
||||||
|
instrument=instrument,
|
||||||
|
side="buy" if delta > 0 else "sell",
|
||||||
|
amount=amount,
|
||||||
|
type="market",
|
||||||
|
reduce_only=is_exit,
|
||||||
|
target_notional=round(tgt, 2),
|
||||||
|
current_notional=round(current_pos_usd, 2),
|
||||||
|
delta_notional=round(delta, 2),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# ----------------------------- lettura mainnet (Cerbero MCP) — SOLA LETTURA -----------------------------
|
||||||
|
|
||||||
|
def _load_mainnet_token() -> tuple[str, str]:
|
||||||
|
"""Legge CERBERO_TOKEN (mainnet) + bot-tag da .env.mainnet. Il token NON viene mai stampato."""
|
||||||
|
env: dict[str, str] = {}
|
||||||
|
for ln in (PROJECT_ROOT / ".env.mainnet").read_text().splitlines():
|
||||||
|
ln = ln.strip()
|
||||||
|
if ln and not ln.startswith("#") and "=" in ln:
|
||||||
|
k, v = ln.split("=", 1)
|
||||||
|
env[k] = v.strip()
|
||||||
|
if "CERBERO_TOKEN" not in env:
|
||||||
|
raise RuntimeError("CERBERO_TOKEN assente in .env.mainnet")
|
||||||
|
return env["CERBERO_TOKEN"], env.get("CERBERO_BOT_TAG", "pythagoras-shadow")
|
||||||
|
|
||||||
|
|
||||||
|
class DeribitRead:
|
||||||
|
"""Accesso Deribit mainnet in SOLA LETTURA via Cerbero MCP. Nessun metodo di trading (by design)."""
|
||||||
|
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self._token, self._tag = _load_mainnet_token()
|
||||||
|
|
||||||
|
def _post(self, path: str, payload: dict) -> dict | list:
|
||||||
|
r = requests.post(
|
||||||
|
f"{BASE_URL}{path}",
|
||||||
|
headers={"Authorization": f"Bearer {self._token}", "X-Bot-Tag": self._tag,
|
||||||
|
"Content-Type": "application/json"},
|
||||||
|
json=payload, timeout=TIMEOUT,
|
||||||
|
)
|
||||||
|
r.raise_for_status()
|
||||||
|
return r.json()
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _unwrap(resp: dict | list) -> dict | list:
|
||||||
|
return resp.get("result", resp) if isinstance(resp, dict) else resp
|
||||||
|
|
||||||
|
def ticker(self, instrument: str) -> dict:
|
||||||
|
return self._unwrap(self._post("/mcp-deribit/tools/get_ticker", {"instrument": instrument})) or {}
|
||||||
|
|
||||||
|
def mark_price(self, instrument: str) -> float:
|
||||||
|
t = self.ticker(instrument)
|
||||||
|
for k in ("mark_price", "index_price", "last_price", "last"):
|
||||||
|
v = t.get(k)
|
||||||
|
if v:
|
||||||
|
return float(v)
|
||||||
|
raise ValueError(f"prezzo assente nel ticker {instrument}: chiavi={list(t)[:8]}")
|
||||||
|
|
||||||
|
def account_summary(self, currency: str) -> dict:
|
||||||
|
return self._unwrap(self._post("/mcp-deribit/tools/get_account_summary", {"currency": currency})) or {}
|
||||||
|
|
||||||
|
def positions(self, currency: str) -> list[dict]:
|
||||||
|
out = self._unwrap(self._post("/mcp-deribit/tools/get_positions", {"currency": currency}))
|
||||||
|
if isinstance(out, list):
|
||||||
|
return out
|
||||||
|
return out.get("positions", []) if isinstance(out, dict) else []
|
||||||
|
|
||||||
|
def position_usd(self, instrument: str) -> float:
|
||||||
|
"""Size netta (USD notional, segno = direzione) della posizione su `instrument`. 0 se flat."""
|
||||||
|
cur = _CONTRACT[instrument]["settle"]
|
||||||
|
for p in self.positions(cur):
|
||||||
|
if p.get("instrument_name") == instrument or p.get("instrument") == instrument:
|
||||||
|
return float(p.get("size") or p.get("size_currency") or 0.0)
|
||||||
|
return 0.0
|
||||||
@@ -0,0 +1,120 @@
|
|||||||
|
"""Stato SHADOW di TP01 (Deribit mainnet, SOLA LETTURA): target causali + conto/posizioni REALI +
|
||||||
|
ordini di ribilancio COSTRUITI (mai inviati). Modulo condiviso da `scripts/live/live_trend.py` (CLI)
|
||||||
|
e dalla dashboard, cosi' i due non divergono. Robusto ai fallimenti di rete: degrada a offline/flat
|
||||||
|
senza sollevare eccezioni (la dashboard non deve crashare se il mainnet non risponde)."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pandas as pd
|
||||||
|
|
||||||
|
from src.backtest.harness import load
|
||||||
|
from src.live.deribit import INSTRUMENT, DeribitRead, build_rebalance_order
|
||||||
|
from src.strategies.trend_portfolio import CANONICAL, TrendPortfolio, resample_1d
|
||||||
|
|
||||||
|
PROJECT_ROOT = Path(__file__).resolve().parents[2]
|
||||||
|
ASSETS = ["BTC", "ETH"]
|
||||||
|
WEIGHT = 0.5
|
||||||
|
FALLBACK_CAPITAL = 2000.0
|
||||||
|
PAPER_STATE = PROJECT_ROOT / "data" / "paper_trend" / "state.json"
|
||||||
|
|
||||||
|
|
||||||
|
def _safe_client() -> DeribitRead | None:
|
||||||
|
try:
|
||||||
|
return DeribitRead()
|
||||||
|
except Exception:
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _marks(client, dfs):
|
||||||
|
marks, src = {}, {}
|
||||||
|
for a in ASSETS:
|
||||||
|
if client is None:
|
||||||
|
marks[a], src[a] = float(dfs[a]["close"].iloc[-1]), "close certificata"
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
marks[a], src[a] = client.mark_price(INSTRUMENT[a]), "mainnet"
|
||||||
|
except Exception as e:
|
||||||
|
marks[a], src[a] = float(dfs[a]["close"].iloc[-1]), f"fallback close ({type(e).__name__})"
|
||||||
|
return marks, src
|
||||||
|
|
||||||
|
|
||||||
|
def _positions(client):
|
||||||
|
if client is None:
|
||||||
|
return {a: 0.0 for a in ASSETS}, "offline -> assunto flat"
|
||||||
|
pos, note = {}, "mainnet"
|
||||||
|
for a in ASSETS:
|
||||||
|
try:
|
||||||
|
pos[a] = client.position_usd(INSTRUMENT[a])
|
||||||
|
except Exception as e:
|
||||||
|
pos[a], note = 0.0, f"read fallito ({type(e).__name__}) -> assunto flat"
|
||||||
|
return pos, note
|
||||||
|
|
||||||
|
|
||||||
|
def _equity(client, marks):
|
||||||
|
if client is None:
|
||||||
|
return None, "offline"
|
||||||
|
try:
|
||||||
|
eq = float(client.account_summary("USDC").get("equity") or 0)
|
||||||
|
if eq > 1:
|
||||||
|
return eq, "mainnet USDC"
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
tot, any_ok = 0.0, False
|
||||||
|
for a in ASSETS:
|
||||||
|
try:
|
||||||
|
eq = float(client.account_summary(a).get("equity") or 0)
|
||||||
|
tot += eq * marks[a]
|
||||||
|
any_ok = True
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
if any_ok and tot > 1:
|
||||||
|
return tot, "mainnet coin-margined"
|
||||||
|
return None, "conto flat / non finanziato"
|
||||||
|
|
||||||
|
|
||||||
|
def shadow_report(offline: bool = False, equity_override: float | None = None) -> dict:
|
||||||
|
"""Calcola lo stato shadow completo. NON invia nulla. Ritorna un dict serializzabile."""
|
||||||
|
dfs = {a: resample_1d(load(a, "1h")) for a in ASSETS}
|
||||||
|
tp = TrendPortfolio(**CANONICAL)
|
||||||
|
targets = {a: tp.current_target(dfs[a]) for a in ASSETS}
|
||||||
|
last_ts = min(int(dfs[a]["timestamp"].iloc[-1]) for a in ASSETS)
|
||||||
|
|
||||||
|
client = None if offline else _safe_client()
|
||||||
|
marks, marks_src = _marks(client, dfs)
|
||||||
|
positions, pos_src = _positions(client)
|
||||||
|
real_eq, eq_src = _equity(client, marks)
|
||||||
|
|
||||||
|
paper = json.loads(PAPER_STATE.read_text()) if PAPER_STATE.exists() else None
|
||||||
|
paper_cap = float(paper["capital"]) if paper else FALLBACK_CAPITAL
|
||||||
|
paper_pos = paper.get("positions") if paper else None
|
||||||
|
paper_ts = int(paper["last_ts"]) if paper else 0
|
||||||
|
|
||||||
|
equity = equity_override if equity_override is not None else (real_eq if real_eq else paper_cap)
|
||||||
|
eq_basis = ("override" if equity_override is not None
|
||||||
|
else eq_src if real_eq else "paper capital (ipotetico: conto non finanziato)")
|
||||||
|
|
||||||
|
assets, orders = [], []
|
||||||
|
for a in ASSETS:
|
||||||
|
inst = INSTRUMENT[a]
|
||||||
|
order = build_rebalance_order(inst, targets[a], WEIGHT, equity, positions[a])
|
||||||
|
if order:
|
||||||
|
orders.append(order)
|
||||||
|
parity = None
|
||||||
|
if paper_pos is not None:
|
||||||
|
parity = abs(float(paper_pos.get(a, 0.0)) - targets[a]) < 1e-9
|
||||||
|
assets.append(dict(
|
||||||
|
asset=a, instrument=inst, target=targets[a],
|
||||||
|
target_notional=WEIGHT * targets[a] * equity,
|
||||||
|
position_usd=positions[a], mark=marks[a], mark_src=marks_src[a],
|
||||||
|
order=order, paper=(float(paper_pos.get(a, 0.0)) if paper_pos else None), parity=parity,
|
||||||
|
))
|
||||||
|
return dict(
|
||||||
|
last_data=str(pd.Timestamp(last_ts, unit="ms", tz="UTC").date()),
|
||||||
|
online=(client is not None and marks_src.get("BTC") == "mainnet"),
|
||||||
|
real_equity=real_eq, equity=equity, eq_basis=eq_basis,
|
||||||
|
pos_src=pos_src, assets=assets, orders=orders,
|
||||||
|
flat=all(abs(targets[a]) < 1e-9 for a in ASSETS),
|
||||||
|
paper_aligned=(paper_ts == last_ts),
|
||||||
|
)
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
"""Test deterministici dello SHADOW MODE di TP01 (src/live/deribit.py).
|
||||||
|
|
||||||
|
Coprono la logica a rischio zero che NON tocca la rete: quantizzazione notional->contratti, sizing
|
||||||
|
target, costruzione ordine di ribilancio (buy/sell/exit/None), e PARITA' col backtest (il target
|
||||||
|
live = ultimo target della serie causale). Il fill reale (slippage/fee) NON e' qui: si valida solo
|
||||||
|
col micro-test mainnet.
|
||||||
|
"""
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
PROJECT_ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
sys.path.insert(0, str(PROJECT_ROOT))
|
||||||
|
|
||||||
|
from src.live.deribit import (build_rebalance_order, notional_to_amount, target_notional_usd)
|
||||||
|
from src.strategies.trend_portfolio import CANONICAL, TrendPortfolio, resample_1d
|
||||||
|
|
||||||
|
|
||||||
|
def test_notional_to_amount_step_and_min():
|
||||||
|
# BTC step/min $10
|
||||||
|
assert notional_to_amount("BTC-PERPETUAL", 1000) == 1000
|
||||||
|
assert notional_to_amount("BTC-PERPETUAL", 1006) == 1010 # round allo step
|
||||||
|
assert notional_to_amount("BTC-PERPETUAL", 7) == 10 # clamp al minimo (>= mezzo step)
|
||||||
|
assert notional_to_amount("BTC-PERPETUAL", 3) == 0.0 # < mezzo step -> niente ordine
|
||||||
|
# ETH step/min $1
|
||||||
|
assert notional_to_amount("ETH-PERPETUAL", 33.7) == 34
|
||||||
|
assert notional_to_amount("ETH-PERPETUAL", 0.4) == 0.0
|
||||||
|
# usa il valore assoluto (il segno lo decide il delta a monte)
|
||||||
|
assert notional_to_amount("BTC-PERPETUAL", -1000) == 1000
|
||||||
|
|
||||||
|
|
||||||
|
def test_no_float_artifacts():
|
||||||
|
# _quantize_step usa Decimal: nessun 0.07200000000000001 & co.
|
||||||
|
v = notional_to_amount("ETH-PERPETUAL", 72.0)
|
||||||
|
assert v == 72 and float(v).is_integer()
|
||||||
|
|
||||||
|
|
||||||
|
def test_target_notional_5050_weight():
|
||||||
|
# 50/50 book: notional asset = 0.5 * frazione * equity
|
||||||
|
assert target_notional_usd(1.0, 0.5, 2000) == 1000
|
||||||
|
assert target_notional_usd(2.0, 0.5, 2000) == 2000 # leva-cap 2x -> piena equity sull'asset
|
||||||
|
assert target_notional_usd(0.0, 0.5, 2000) == 0.0
|
||||||
|
|
||||||
|
|
||||||
|
def test_build_order_entry():
|
||||||
|
o = build_rebalance_order("BTC-PERPETUAL", target_fraction=1.0, weight=0.5,
|
||||||
|
equity_usd=2000, current_pos_usd=0.0)
|
||||||
|
assert o["side"] == "buy" and o["amount"] == 1000 and o["reduce_only"] is False
|
||||||
|
assert o["target_notional"] == 1000 and o["delta_notional"] == 1000
|
||||||
|
|
||||||
|
|
||||||
|
def test_build_order_exit_is_reduce_only():
|
||||||
|
o = build_rebalance_order("ETH-PERPETUAL", target_fraction=0.0, weight=0.5,
|
||||||
|
equity_usd=2000, current_pos_usd=1000.0)
|
||||||
|
assert o["side"] == "sell" and o["reduce_only"] is True and o["amount"] == 1000
|
||||||
|
|
||||||
|
|
||||||
|
def test_build_order_already_at_target_is_none():
|
||||||
|
o = build_rebalance_order("BTC-PERPETUAL", 1.0, 0.5, 2000, current_pos_usd=1000.0)
|
||||||
|
assert o is None # delta 0 -> nessun ordine
|
||||||
|
|
||||||
|
|
||||||
|
def test_build_order_subthreshold_is_none():
|
||||||
|
# delta $3 su BTC (< mezzo step $5) -> niente ordine
|
||||||
|
o = build_rebalance_order("BTC-PERPETUAL", 0.5015, 0.5, 2000, current_pos_usd=498.5)
|
||||||
|
assert o is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_partial_rebalance_direction():
|
||||||
|
# target $1000, ho $600 -> compro $400; ho $1400 -> vendo $400
|
||||||
|
up = build_rebalance_order("BTC-PERPETUAL", 1.0, 0.5, 2000, 600.0)
|
||||||
|
dn = build_rebalance_order("BTC-PERPETUAL", 1.0, 0.5, 2000, 1400.0)
|
||||||
|
assert up["side"] == "buy" and up["amount"] == 400
|
||||||
|
assert dn["side"] == "sell" and dn["amount"] == 400 and dn["reduce_only"] is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_parity_live_target_equals_backtest():
|
||||||
|
# il target live (current_target) DEVE essere l'ultimo della serie causale del backtest
|
||||||
|
from src.backtest.harness import load
|
||||||
|
tp = TrendPortfolio(**CANONICAL)
|
||||||
|
df = resample_1d(load("BTC", "1h"))
|
||||||
|
assert tp.current_target(df) == tp.target_series(df)[-1]
|
||||||
Reference in New Issue
Block a user