Compare commits
9 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 4650aa71a2 | |||
| bc9e322d0d | |||
| a3d6b97db6 | |||
| cddea50c5a | |||
| c00f6016df | |||
| 715f197cf2 | |||
| 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 /
|
||||
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
|
||||
(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`.
|
||||
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
|
||||
@@ -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
|
||||
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à).
|
||||
⚠️ **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
|
||||
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"_nota": "Config esecuzione LIVE di TP01. execution_enabled=true + --execute -> ordini REALI. ARMATO 2026-06-20.",
|
||||
"execution_enabled": true,
|
||||
"max_notional_per_asset_usd": 300,
|
||||
"min_order_usd": 5,
|
||||
"disaster_sl_pct": 0.30
|
||||
}
|
||||
@@ -10,3 +10,6 @@ services:
|
||||
- "8787:8787"
|
||||
volumes:
|
||||
- ./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
|
||||
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
|
||||
in data/raw/hl_<sym>_1d.parquet (namespace dedicato, NON mischiato col Deribit BTC/ETH).
|
||||
asset come BTC/ETH: cross-venue vs Binance (realismo) + flat-bar + VOLUME (liquidita'). Scrivo SOLO
|
||||
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.
|
||||
|
||||
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
|
||||
"""
|
||||
from __future__ import annotations
|
||||
@@ -17,7 +28,9 @@ sys.path.insert(0, str(PROJECT_ROOT))
|
||||
import numpy as np, pandas as pd, requests, ccxt
|
||||
|
||||
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
|
||||
# certificazione (cross-venue + liquidita' + flat) scarta i non-conformi. k-prefissi esclusi
|
||||
# (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)
|
||||
|
||||
|
||||
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():
|
||||
H=_h()
|
||||
print("="*92); print(" FETCH + CERTIFY Hyperliquid 1d (Cerbero mainnet) — cross-venue vs Binance + liquidita'"); print("="*92)
|
||||
print(f" {'sym':<6}{'barre':>7}{'start':>12}{'flat%':>7}{'med_bps':>9}{'>1%':>7}{'verdetto':>12}")
|
||||
print("="*100); print(" FETCH + CERTIFY Hyperliquid 1d (Cerbero mainnet) — cross-venue + flat + VOLUME (no backfill)"); print("="*100)
|
||||
print(f" {'sym':<6}{'reali':>6}{'bfill':>6}{'start_reale':>13}{'flat%':>7}{'vol0%':>7}{'med_bps':>9}{'>1%':>7}{'verdetto':>14}")
|
||||
certified=[]
|
||||
for s in SYMS:
|
||||
df=fetch_hl(s,H)
|
||||
if df.empty: print(f" {s:<6} vuoto"); continue
|
||||
path = RAW/f"hl_{s.lower()}_1d.parquet"
|
||||
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)
|
||||
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]))
|
||||
a=df.set_index("timestamp")["close"]
|
||||
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),
|
||||
# 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")
|
||||
clean = (not np.isnan(med)) and med<60 and g1<3 and flat<5 and recent
|
||||
v = "PULITO" if clean else "scarta"
|
||||
print(f" {s:<6}{len(df):>7}{str(ts.iloc[0].date()):>12}{flat:>6.1f}%{med:>9.1f}{g1:>6.1f}%{v:>12}")
|
||||
# gate storia NATIVA: dopo il taglio dev'esserci abbastanza vita reale (es. AXS quotato 2026-01 -> scarta)
|
||||
native_days = (ts.iloc[-1] - ts.iloc[0]).days
|
||||
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:
|
||||
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(" 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__":
|
||||
|
||||
@@ -9,5 +9,6 @@ mkdir -p logs
|
||||
uv run python scripts/analysis/fetch_hyperliquid.py # 52 alt Hyperliquid (certify)
|
||||
uv run python scripts/research/fetch_dvol.py # DVOL (per ricerca opzioni)
|
||||
uv run python scripts/live/paper_portfolio.py # avanza paper TP01+XS01
|
||||
uv run python scripts/live/live_execute.py --execute # TP01 LIVE su Deribit (gated da config/live.json)
|
||||
echo "===== done $(date -u '+%H:%M:%SZ') ====="
|
||||
} >> logs/cron_daily.log 2>&1
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
"""TP01 LIVE EXECUTE — loop di esecuzione GATED su Deribit mainnet (USDC linear).
|
||||
|
||||
Porta il conto reale al target di TP01 (causale, dati certificati): per ogni asset calcola il notional
|
||||
bersaglio = min(0.5 * frazione * equity, max_notional), e apre/riduce/chiude per raggiungerlo.
|
||||
|
||||
DOPPIO GATE DI SICUREZZA (entrambi necessari per inviare ordini reali):
|
||||
1. config/live.json -> "execution_enabled": true (master switch, default false)
|
||||
2. flag CLI --execute
|
||||
Senza entrambi e' un DRY-RUN (stampa il piano, NON invia). Reconciliation dopo ogni ordine; log in
|
||||
data/live/executions.jsonl. TP01 oggi e' FLAT -> target 0 -> nessuna azione finche' il segnale non gira.
|
||||
|
||||
uv run python scripts/live/live_execute.py # DRY-RUN (piano, nessun ordine)
|
||||
uv run python scripts/live/live_execute.py --execute # esegue SOLO se execution_enabled=true
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pandas as pd
|
||||
|
||||
PROJECT_ROOT = Path(__file__).resolve().parents[2]
|
||||
sys.path.insert(0, str(PROJECT_ROOT))
|
||||
|
||||
from src.live.deribit import INSTRUMENT
|
||||
from src.live.execution import DeribitTrader
|
||||
from src.live.shadow import ASSETS, WEIGHT, shadow_report
|
||||
|
||||
CONFIG = PROJECT_ROOT / "config" / "live.json"
|
||||
LOG_DIR = PROJECT_ROOT / "data" / "live"
|
||||
LOG = LOG_DIR / "executions.jsonl"
|
||||
|
||||
|
||||
def load_config() -> dict:
|
||||
cfg = json.loads(CONFIG.read_text()) if CONFIG.exists() else {}
|
||||
cfg.setdefault("execution_enabled", False)
|
||||
cfg.setdefault("max_notional_per_asset_usd", 300.0)
|
||||
cfg.setdefault("min_order_usd", 5.0)
|
||||
return cfg
|
||||
|
||||
|
||||
def log_event(rec: dict):
|
||||
LOG_DIR.mkdir(parents=True, exist_ok=True)
|
||||
with open(LOG, "a") as f:
|
||||
f.write(json.dumps(rec) + "\n")
|
||||
|
||||
|
||||
def main():
|
||||
cfg = load_config()
|
||||
want_execute = "--execute" in sys.argv[1:]
|
||||
enabled = bool(cfg["execution_enabled"])
|
||||
do_execute = want_execute and enabled
|
||||
max_notional = float(cfg["max_notional_per_asset_usd"])
|
||||
min_order = float(cfg["min_order_usd"])
|
||||
|
||||
r = shadow_report() # targets causali + conto/posizioni reali (online)
|
||||
equity = r["equity"]
|
||||
|
||||
print("=" * 84)
|
||||
print(" TP01 LIVE EXECUTE — Deribit mainnet (USDC linear)")
|
||||
print("=" * 84)
|
||||
mode = ("ESECUZIONE REALE" if do_execute else
|
||||
("ARMATO ma manca --execute" if enabled else "DRY-RUN (execution_enabled=false)"))
|
||||
print(f" modo : {mode}")
|
||||
print(f" gate : execution_enabled={enabled} | --execute={want_execute}")
|
||||
print(f" conto reale : ${r['real_equity']:,.2f}" if r["real_equity"] else f" conto: {r['eq_basis']}")
|
||||
print(f" sizing base : ${equity:,.2f} | cap/asset ${max_notional:.0f} | min ordine ${min_order:.0f}")
|
||||
print(f" ultima barra : {r['last_data']}\n")
|
||||
|
||||
if not r["online"]:
|
||||
print(" conto non leggibile (offline) -> stop, non eseguo a cieco.")
|
||||
return
|
||||
|
||||
trader = DeribitTrader() if do_execute else None
|
||||
actions = []
|
||||
for a in r["assets"]:
|
||||
asset = a["asset"]; frac = a["target"]; mark = a["mark"]; cur = a["position_usd"]
|
||||
tgt = min(WEIGHT * frac * equity, max_notional) if frac > 0 else 0.0
|
||||
delta = tgt - cur
|
||||
if abs(delta) < min_order:
|
||||
act = "HOLD (a target)"
|
||||
elif tgt < 1.0 and cur > 1.0:
|
||||
act = f"CLOSE ${cur:,.0f}"
|
||||
elif delta > 0:
|
||||
act = f"BUY ${delta:,.0f}"
|
||||
else:
|
||||
act = f"REDUCE ${-delta:,.0f}"
|
||||
print(f" {asset:<3} target {frac:+.3f}x -> ${tgt:,.0f} | pos ${cur:,.0f} | delta ${delta:+,.0f} -> {act}")
|
||||
|
||||
if do_execute and not act.startswith("HOLD"):
|
||||
fills = trader.rebalance_to(INSTRUMENT[asset], tgt, mark, min_usd=min_order)
|
||||
newpos = trader.position_usd(INSTRUMENT[asset])
|
||||
for f in fills:
|
||||
print(f" -> {f.side.upper()} {f.filled:.4f} @ ${f.price:,.1f} fee {f.fee_usdc:.5f} "
|
||||
f"({'OK' if f.verified else 'NON VERIFICATO: ' + f.notes})")
|
||||
log_event(dict(ts_utc=str(pd.Timestamp(r['last_data'])), asset=asset, action=act,
|
||||
side=f.side, filled=f.filled, price=f.price, fee=f.fee_usdc,
|
||||
verified=f.verified, notes=f.notes, pos_after=newpos))
|
||||
print(f" reconcile: pos ${newpos:,.0f}")
|
||||
actions.append(act)
|
||||
|
||||
print()
|
||||
if not do_execute:
|
||||
print(" => DRY-RUN: nessun ordine inviato." +
|
||||
("" if enabled else " Per armare: config/live.json execution_enabled=true + --execute."))
|
||||
elif all(x.startswith("HOLD") for x in actions):
|
||||
print(" => Nessuna azione: conto gia' al target di TP01 (oggi flat).")
|
||||
else:
|
||||
print(" => Esecuzione completata (vedi data/live/executions.jsonl).")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
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()
|
||||
@@ -0,0 +1,92 @@
|
||||
"""MICRO-TEST esecuzione su Deribit mainnet — round-trip minimo su BTC_USDC-PERPETUAL, apri+chiudi.
|
||||
|
||||
Conto reale = USDC -> strumento ESEGUIBILE = perp LINEARE `BTC_USDC-PERPETUAL` (amount in BTC, step
|
||||
0.0001 ~ $6). Valida il percorso ordine->fill->reconciliation->chiusura con soldi VERI a size MINIMA
|
||||
(~0x leva, decoupled dal segnale): test della plumbing, non della strategia. Usa open()/close()
|
||||
verificati di src/live/execution.py (logica entrata/uscita presa da Old).
|
||||
|
||||
Sicurezze: default DRY-RUN. Pre-flight ABORT se posizione preesistente. La chiusura (reduce_only,
|
||||
sempre permessa) flatta comunque dopo l'apertura; verifica finale di FLAT (alert se no).
|
||||
|
||||
uv run python scripts/live/microtest.py # DRY-RUN: nessun ordine inviato
|
||||
uv run python scripts/live/microtest.py --live # invia il round-trip REALE
|
||||
"""
|
||||
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.execution import FLAT_USD, MAX_AMOUNT, DeribitTrader
|
||||
|
||||
INSTRUMENT = "BTC_USDC-PERPETUAL"
|
||||
AMOUNT = 0.0001 # base-coin (BTC) = 1 contratto minimo (~$6 a $63k)
|
||||
|
||||
|
||||
def main():
|
||||
live = "--live" in sys.argv[1:]
|
||||
t = DeribitTrader()
|
||||
|
||||
print("=" * 82)
|
||||
print(" MICRO-TEST esecuzione TP01 — round-trip 0.0001 BTC su BTC_USDC-PERPETUAL (leva ~0x)")
|
||||
print("=" * 82)
|
||||
try:
|
||||
equity = float(t.account_summary("USDC").get("equity") or 0)
|
||||
mark = t.mark_price(INSTRUMENT)
|
||||
pos0 = t.position_usd(INSTRUMENT)
|
||||
except Exception as e:
|
||||
print(f" PRE-FLIGHT FALLITO (read): {type(e).__name__}: {e}\n -> non procedo.")
|
||||
return
|
||||
|
||||
notional = AMOUNT * mark
|
||||
print(f" conto USDC equity : ${equity:,.2f}")
|
||||
print(f" mark {INSTRUMENT} : ${mark:,.1f}")
|
||||
print(f" posizione attuale : ${pos0:,.2f} notional (dev'essere 0)")
|
||||
print(f" apertura : BUY {AMOUNT:.4f} BTC market (~${notional:.2f}, leva {notional/equity:.4f}x)")
|
||||
print(f" chiusura : SELL {AMOUNT:.4f} BTC market reduce_only")
|
||||
print(f" guardrail: solo {INSTRUMENT}, cap apertura {MAX_AMOUNT[INSTRUMENT]} BTC")
|
||||
|
||||
if abs(pos0) >= FLAT_USD:
|
||||
print(f"\n ABORT: posizione preesistente (${pos0:,.2f}). Non la tocco. Chiudila a mano e ripeti.")
|
||||
return
|
||||
if not live:
|
||||
print("\n DRY-RUN: nessun ordine inviato. Rilancia con --live per il round-trip reale.")
|
||||
return
|
||||
|
||||
# ---- LIVE: apertura ----
|
||||
print("\n >>> LIVE: APERTURA ...")
|
||||
fo = t.open(INSTRUMENT, "buy", AMOUNT, label="tp01-microtest-open")
|
||||
if not fo.verified:
|
||||
print(f" apertura NON verificata: {fo.notes}")
|
||||
# safety: assicura comunque il flat
|
||||
fc = t.close(INSTRUMENT, label="tp01-microtest-safeclose")
|
||||
print(f" safe-close: {'eseguita' if fc else 'gia flat'}; posizione ${t.position_usd(INSTRUMENT):,.2f}")
|
||||
return
|
||||
print(f" FILL: {fo.filled:.4f} BTC @ ${fo.price:,.1f} fee {fo.fee_usdc:.6f} USDC (state={fo.state})")
|
||||
|
||||
# ---- LIVE: chiusura (reduce_only) ----
|
||||
print(" >>> LIVE: CHIUSURA (reduce_only) ...")
|
||||
fc = t.close(INSTRUMENT, label="tp01-microtest-close")
|
||||
pos_end = t.position_usd(INSTRUMENT)
|
||||
if fc:
|
||||
print(f" FILL: {fc.filled:.4f} BTC @ ${fc.price:,.1f} fee {fc.fee_usdc:.6f} USDC (state={fc.state})")
|
||||
print(f" posizione finale: ${pos_end:,.2f} notional")
|
||||
|
||||
# ---- report ----
|
||||
print("\n " + "-" * 62)
|
||||
if abs(pos_end) < FLAT_USD:
|
||||
print(" ✓ ROUND-TRIP COMPLETO — posizione tornata a FLAT.")
|
||||
else:
|
||||
print(f" ⚠️ posizione NON flat (${pos_end:,.2f}) — INTERVENTO MANUALE: chiudi a mano.")
|
||||
if fo.verified and fc:
|
||||
tot_fee = fo.fee_usdc + fc.fee_usdc
|
||||
pnl = AMOUNT * ((fc.price or 0) - (fo.price or 0))
|
||||
print(f" entry ${fo.price:,.1f} -> exit ${fc.price:,.1f} | fee {tot_fee:.6f} USDC | "
|
||||
f"pnl lordo {pnl:+.4f} | netto {pnl - tot_fee:+.4f} USDC")
|
||||
print(" Validato: invio ordine reale, fill, fee reali, reconciliation, ritorno a flat.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+59
-5
@@ -15,6 +15,7 @@ sys.path.insert(0, str(PROJECT_ROOT))
|
||||
import numpy as np, pandas as pd
|
||||
from src.portfolio.portfolio import StrategyPortfolio, metrics, HOLDOUT
|
||||
from src.portfolio.sleeves import active_sleeves
|
||||
from src.live.shadow import shadow_report, tp01_trades
|
||||
from src.version import APP_VERSION
|
||||
|
||||
PAPER = PROJECT_ROOT / "data" / "paper_portfolio" / "state.json"
|
||||
@@ -32,12 +33,20 @@ def build():
|
||||
step = max(1, len(eq) // 400)
|
||||
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
|
||||
try:
|
||||
shadow = shadow_report() # mainnet sola lettura, best-effort
|
||||
except Exception as e:
|
||||
shadow = {"error": f"{type(e).__name__}: {e}"}
|
||||
try:
|
||||
trades = tp01_trades(limit=15) # entry/exit TP01 dal segnale causale
|
||||
except Exception:
|
||||
trades = []
|
||||
data = dict(
|
||||
version=APP_VERSION,
|
||||
last_data=str(idx[-1].date()),
|
||||
full=bt["full"], holdout=bt["holdout"], weights=bt["weights"],
|
||||
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, trades=trades,
|
||||
bh=None,
|
||||
)
|
||||
_CACHE.update(t=time.time(), data=data)
|
||||
@@ -77,6 +86,41 @@ def html():
|
||||
f"{pp['last'][:10]}, {days}g) ret <b>{ret*100:+.2f}%</b> maxDD {pp['max_dd']*100:.1f}%")
|
||||
else:
|
||||
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 "")
|
||||
trows = ""
|
||||
for t in d.get("trades", []):
|
||||
cls = "g" if t["action"] == "ENTRY" else "r"
|
||||
trows += (f"<tr><td>{t['date']}</td><td>{t['asset']}</td>"
|
||||
f"<td class={cls}>{t['action']}</td>"
|
||||
f"<td>{t['from_pos']:+.2f} → {t['to_pos']:+.2f}x</td>"
|
||||
f"<td>${t['price']:,.0f}</td></tr>")
|
||||
if not trows:
|
||||
trows = "<tr><td colspan=5 style='color:#8a93a0'>nessun trade ancora (TP01 flat / in cash)</td></tr>"
|
||||
live_trows = ""
|
||||
for x in ((sh.get("live_trades") if sh and "error" not in sh else None) or []):
|
||||
dcls = "g" if x["direction"] == "BUY" else "r"
|
||||
when = str(pd.Timestamp(x["ts"], unit="ms", tz="UTC"))[:16] if x["ts"] else "—"
|
||||
sym = x["instrument"].replace("_USDC-PERPETUAL", "").replace("-PERPETUAL", "")
|
||||
live_trows += (f"<tr><td>{when}</td><td>{sym}</td><td class={dcls}>{x['direction']}</td>"
|
||||
f"<td>{x['amount']:.4f}</td><td>${x['price']:,.1f}</td><td>{x['fee']:.5f}</td></tr>")
|
||||
if not live_trows:
|
||||
live_trows = "<tr><td colspan=6 style='color:#8a93a0'>nessun trade reale eseguito (o conto non leggibile dal container)</td></tr>"
|
||||
return f"""<!doctype html><html><head><meta charset=utf-8>
|
||||
<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}}
|
||||
@@ -87,9 +131,12 @@ h1{{font-size:20px;margin:0 0 2px}}.sub{{color:#8a93a0;font-size:13px;margin-bot
|
||||
table{{width:100%;border-collapse:collapse;margin:8px 0 20px}}td,th{{text-align:left;padding:7px 10px;border-bottom:1px solid #222b36;font-size:14px}}
|
||||
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}}
|
||||
.warn{{color:#f1c40f;font-size:12px}}</style></head><body>
|
||||
<h1>PythagorasGoal — Portafoglio attivo (TP01 + XS01)</h1>
|
||||
<div class=sub>monitor PAPER · v{d['version']} · ultimo dato {d['last_data']} · esecuzione REALE disabilitata</div>
|
||||
.warn{{color:#f1c40f;font-size:12px}}
|
||||
.section{{font-size:15px;font-weight:700;letter-spacing:.06em;text-transform:uppercase;margin:34px 0 14px;padding:10px 14px;border-radius:9px;background:#12181f;border-left:5px solid #2ecc71;color:#d7dee6}}
|
||||
.section.live{{border-left-color:#e74c3c;background:#1c1316;color:#f0c4c4}}</style></head><body>
|
||||
<h1>PythagorasGoal — Portafoglio attivo (TP01 + XS01 + VRP01)</h1>
|
||||
<div class=sub>monitor · v{d['version']} · ultimo dato {d['last_data']} · esecuzione REALE non attiva (solo micro-test)</div>
|
||||
<div class="section">PAPER — simulato (backtest + forward virtuale)</div>
|
||||
<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>HOLD-OUT Sharpe (2025-26)</div><div class="v g">{ho['sharpe']:.2f}</div></div>
|
||||
@@ -103,8 +150,14 @@ th{{color:#8a93a0;font-weight:500}}.y{{display:inline-block;background:#161b22;b
|
||||
<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>
|
||||
<table>{pos}</table>
|
||||
<h3 style="font-size:14px;color:#8a93a0">Trades TP01 — entry/exit (segnale causale, ultimi 15)</h3>
|
||||
<table><tr><th>data</th><th>asset</th><th>azione</th><th>posizione</th><th>prezzo</th></tr>{trows}</table>
|
||||
<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>
|
||||
<div class="section live">LIVE — Deribit mainnet (conto reale, sola lettura)</div>
|
||||
<div class=box><b>Shadow TP01</b> (cosa farebbe ORA sul conto reale, nessun ordine inviato):<br>{shadow_html}</div>
|
||||
<h3 style="font-size:14px;color:#8a93a0">Trades REALI eseguiti su Deribit</h3>
|
||||
<table><tr><th>data/ora UTC</th><th>strum.</th><th>dir</th><th>amount</th><th>prezzo</th><th>fee USDC</th></tr>{live_trows}</table>
|
||||
<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>"""
|
||||
|
||||
|
||||
@@ -121,6 +174,7 @@ class H(BaseHTTPRequestHandler):
|
||||
body = f"<pre>errore: {type(e).__name__}: {e}</pre>".encode()
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "text/html; charset=utf-8")
|
||||
self.send_header("Cache-Control", "no-cache, no-store, must-revalidate")
|
||||
self.end_headers(); self.wfile.write(body)
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
"""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 (BTC/ETH).
|
||||
# Linear USDC perp: amount = base-coin (BTC/ETH), step in base-coin, settle = USDC (margine USDC).
|
||||
# NB il conto reale e' USDC -> gli strumenti ESEGUIBILI sono i LINEARI _USDC-PERPETUAL.
|
||||
_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"},
|
||||
"BTC_USDC-PERPETUAL": {"min": 0.0001, "step": 0.0001, "tick": 0.5, "settle": "USDC", "linear": True},
|
||||
"ETH_USDC-PERPETUAL": {"min": 0.001, "step": 0.001, "tick": 0.05, "settle": "USDC", "linear": True},
|
||||
}
|
||||
# Il conto reale e' USDC -> mappiamo gli asset sui perp LINEARI USDC (gli unici eseguibili qui).
|
||||
INSTRUMENT = {"BTC": "BTC_USDC-PERPETUAL", "ETH": "ETH_USDC-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, price: float | None = None) -> float:
|
||||
"""USD notional -> `amount` Deribit, arrotondato allo step e clampato al minimo. Ritorna 0.0 se
|
||||
sotto mezzo step. INVERSE: amount in USD (price ignorato). LINEAR USDC: amount in base-coin
|
||||
(units = notional/price -> serve il `price`; senza price ritorna 0.0)."""
|
||||
spec = _CONTRACT[instrument]
|
||||
step, mn = spec["step"], spec["min"]
|
||||
if spec.get("linear"):
|
||||
if not price:
|
||||
return 0.0
|
||||
units = abs(notional_usd) / price
|
||||
if units < step / 2:
|
||||
return 0.0
|
||||
return _quantize_step(units, step, mn)
|
||||
if abs(notional_usd) < step / 2:
|
||||
return 0.0
|
||||
return _quantize_step(abs(notional_usd), step, mn)
|
||||
|
||||
|
||||
def quantize_price(instrument: str, price: float) -> float:
|
||||
"""Arrotonda il prezzo al tick dello strumento (per gli ordini stop/limit)."""
|
||||
tick = _CONTRACT[instrument].get("tick")
|
||||
if not tick or price <= 0:
|
||||
return price
|
||||
return float(round(price / tick) * Decimal(str(tick)))
|
||||
|
||||
|
||||
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, price: float | None = None) -> 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.
|
||||
`price` (mark) serve a convertire il notional in base-coin per gli strumenti LINEARI USDC."""
|
||||
tgt = target_notional_usd(target_fraction, weight, equity_usd)
|
||||
delta = tgt - current_pos_usd
|
||||
amount = notional_to_amount(instrument, delta, price=price)
|
||||
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
|
||||
|
||||
def trade_history(self, instrument: str, limit: int = 20) -> list[dict]:
|
||||
"""Trade REALMENTE eseguiti sul conto per `instrument` (fonte autorevole fee/fill)."""
|
||||
out = self._unwrap(self._post("/mcp-deribit/tools/get_trade_history",
|
||||
{"limit": limit, "instrument_name": instrument}))
|
||||
return out if isinstance(out, list) else (out.get("trades", []) if isinstance(out, dict) else [])
|
||||
@@ -0,0 +1,151 @@
|
||||
"""Esecuzione REALE su Deribit mainnet (via Cerbero MCP) — entrata/uscita verificate.
|
||||
|
||||
Estende DeribitRead (sola lettura) coi metodi di trading, con la logica PROVATA dello stack pre-reset
|
||||
(Old/src/live/execution.py): entrata market verificata (state=='filled' + trade riscontrati, fill/fee
|
||||
reali, filled_amount autorevole), uscita market reduce_only, disaster-bracket STOP_MARKET reduce_only.
|
||||
|
||||
GUARDRAIL: solo strumenti in ALLOWED; cap di size SOLO sulle APERTURE (MAX_AMOUNT). Le CHIUSURE si
|
||||
tentano SEMPRE senza cap (principio di sicurezza di Old: si deve poter uscire da qualunque posizione).
|
||||
Nessun parametro di leva (Deribit non la accetta per-ordine: l'esposizione la decide la SIZE).
|
||||
|
||||
⚠️ INVIA ORDINI REALI CON SOLDI VERI. Finestra d'uso attuale: micro-test (scripts/live/microtest.py).
|
||||
Il deploy pieno di TP01 resta gated finche' il percorso live non e' abilitato esplicitamente.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
from src.live.deribit import DeribitRead, notional_to_amount, quantize_price
|
||||
|
||||
# Conto USDC -> perp LINEARE USDC (amount in base-coin). MAX_AMOUNT = TETTO HARD anti-fat-finger
|
||||
# (~$630/$430 su un conto ~$600): backstop sopra il sizing di TP01, non il sizing operativo (quello
|
||||
# lo decide config/live.json max_notional_per_asset_usd). Il micro-test invia comunque size fissa minima.
|
||||
ALLOWED = {"BTC_USDC-PERPETUAL", "ETH_USDC-PERPETUAL"}
|
||||
MAX_AMOUNT = {"BTC_USDC-PERPETUAL": 0.01, "ETH_USDC-PERPETUAL": 0.25}
|
||||
FLAT_USD = 1.0 # |notional| < $1 = posizione considerata flat
|
||||
|
||||
|
||||
class GuardrailError(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
@dataclass
|
||||
class Fill:
|
||||
"""Esito verificato di un ordine reale."""
|
||||
instrument: str
|
||||
side: str
|
||||
amount: float # richiesto (base-coin)
|
||||
filled: float # realmente fillato (order.filled_amount, autorevole)
|
||||
price: float | None # prezzo medio di fill
|
||||
fee_usdc: float # fee reale (lineare USDC: gia' in USDC)
|
||||
order_id: str | None
|
||||
state: str | None
|
||||
verified: bool
|
||||
notes: str = ""
|
||||
|
||||
|
||||
def _avg_price(order: dict, trades: list[dict]) -> float | None:
|
||||
tr = [t for t in trades if t.get("price") and t.get("amount")]
|
||||
if tr:
|
||||
amt = sum(float(t["amount"]) for t in tr)
|
||||
return (sum(float(t["price"]) * float(t["amount"]) for t in tr) / amt) if amt else None
|
||||
return float(order.get("average_price") or 0) or None
|
||||
|
||||
|
||||
class DeribitTrader(DeribitRead):
|
||||
"""Trading minimo e verificato. Apre/chiude solo entro i guardrail; le chiusure sempre."""
|
||||
|
||||
def _submit(self, instrument: str, side: str, amount: float, *, reduce_only: bool,
|
||||
label: str, order_type: str = "market", price: float | None = None) -> Fill:
|
||||
if instrument not in ALLOWED:
|
||||
raise GuardrailError(f"strumento non consentito: {instrument}")
|
||||
if side not in ("buy", "sell"):
|
||||
raise GuardrailError(f"side non valido: {side}")
|
||||
if not reduce_only: # cap SOLO sulle aperture; le chiusure si tentano sempre
|
||||
cap = MAX_AMOUNT.get(instrument, 0.0)
|
||||
if amount <= 0 or amount > cap:
|
||||
raise GuardrailError(f"size {amount} fuori dal cap apertura (0, {cap}]")
|
||||
if amount <= 0:
|
||||
return Fill(instrument, side, amount, 0.0, None, 0.0, None, None, False, "amount<=0")
|
||||
|
||||
payload = {"instrument_name": instrument, "side": side, "amount": amount,
|
||||
"type": order_type, "label": label}
|
||||
if price is not None:
|
||||
payload["price"] = price
|
||||
if reduce_only:
|
||||
payload["reduce_only"] = True
|
||||
resp = self._unwrap(self._post("/mcp-deribit/tools/place_order", payload)) or {}
|
||||
|
||||
if not isinstance(resp, dict) or resp.get("error") or resp.get("state") == "error":
|
||||
err = resp.get("error") if isinstance(resp, dict) else resp
|
||||
return Fill(instrument, side, amount, 0.0, None, 0.0, None, "error", False,
|
||||
notes=f"place_order error: {err}")
|
||||
|
||||
order = resp.get("order", resp) or {}
|
||||
trades = resp.get("trades", []) or []
|
||||
order_id = order.get("order_id")
|
||||
state = order.get("order_state")
|
||||
price_f = _avg_price(order, trades)
|
||||
fee_usdc = sum(float(t.get("fee", 0) or 0) for t in trades) # lineare USDC: fee gia' in USDC
|
||||
filled = float(order.get("filled_amount") or 0) or sum(float(t.get("amount", 0) or 0) for t in trades)
|
||||
|
||||
if order_type == "market":
|
||||
verified = (state == "filled") and bool(trades)
|
||||
elif order_type == "stop_market":
|
||||
verified = state in ("untriggered", "open", "filled")
|
||||
else:
|
||||
verified = state in ("open", "filled")
|
||||
notes = "" if verified else f"non verificato (state={state}, trades={len(trades)})"
|
||||
if verified and order_type == "market" and filled < amount - 1e-12:
|
||||
notes = f"FILL PARZIALE: {filled} su {amount}"
|
||||
return Fill(instrument, side, amount, filled, price_f, fee_usdc, order_id, state, verified, notes)
|
||||
|
||||
# --- ENTRATA ---
|
||||
def open(self, instrument: str, side: str, amount: float, label: str = "tp01-open") -> Fill:
|
||||
"""Apre a market (NON reduce_only), entro il cap. Verifica il fill reale."""
|
||||
return self._submit(instrument, side, amount, reduce_only=False, label=label)
|
||||
|
||||
# --- USCITA (sempre permessa) ---
|
||||
def close(self, instrument: str, label: str = "tp01-close") -> Fill | None:
|
||||
"""Chiude la posizione a market reduce_only. Legge la size reale (USD notional), la converte
|
||||
in base-coin col mark, e flatta. None se gia' flat. Senza cap: si esce sempre."""
|
||||
pos_usd = self.position_usd(instrument)
|
||||
if abs(pos_usd) < FLAT_USD:
|
||||
return None
|
||||
mark = self.mark_price(instrument)
|
||||
amount = notional_to_amount(instrument, abs(pos_usd), price=mark)
|
||||
side = "sell" if pos_usd > 0 else "buy"
|
||||
return self._submit(instrument, side, amount, reduce_only=True, label=label)
|
||||
|
||||
# --- RIBILANCIO al target (long-only TP01): apre / riduce / chiude ---
|
||||
def rebalance_to(self, instrument: str, target_notional_usd: float, mark: float,
|
||||
min_usd: float = 5.0) -> list[Fill]:
|
||||
"""Porta la posizione su `instrument` al target (USD notional). Long-only: target>=0.
|
||||
- delta < min_usd -> niente (gia' a target);
|
||||
- target ~0 & posizione -> close() (uscita piena, reduce_only);
|
||||
- delta > 0 -> open buy (aumenta);
|
||||
- delta < 0 (resta long) -> sell reduce_only del delta (riduce).
|
||||
Ritorna i Fill eseguiti."""
|
||||
cur = self.position_usd(instrument)
|
||||
delta = target_notional_usd - cur
|
||||
if abs(delta) < min_usd:
|
||||
return []
|
||||
if target_notional_usd < FLAT_USD and cur > FLAT_USD:
|
||||
f = self.close(instrument, label="tp01-exit")
|
||||
return [f] if f else []
|
||||
amount = notional_to_amount(instrument, abs(delta), price=mark)
|
||||
if amount <= 0:
|
||||
return []
|
||||
if delta > 0:
|
||||
return [self.open(instrument, "buy", amount, label="tp01-buy")]
|
||||
return [self._submit(instrument, "sell", amount, reduce_only=True, label="tp01-reduce")]
|
||||
|
||||
# --- DISASTER BRACKET (assicurazione on-book per outage; da Old) ---
|
||||
def place_disaster_sl(self, instrument: str, side_held: str, amount: float,
|
||||
stop_price: float, label: str = "disaster-sl") -> Fill:
|
||||
"""STOP_MARKET reduce_only LONTANO (~-30%): in operativita' normale non scatta (l'exit della
|
||||
strategia esce prima) -> 0 costo Sharpe; copre gli outage del runner. Trigger sul mark."""
|
||||
opp = "sell" if side_held == "buy" else "buy"
|
||||
return self._submit(instrument, opp, amount, reduce_only=True, label=label,
|
||||
order_type="stop_market", price=quantize_price(instrument, stop_price))
|
||||
# trade_history e' ereditato da DeribitRead (read-only)
|
||||
@@ -0,0 +1,165 @@
|
||||
"""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 numpy as np
|
||||
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 tp01_trades(limit: int = 15) -> list[dict]:
|
||||
"""Lista dei TRADE di TP01 = cambi di posizione (ENTRY long / EXIT flat) dedotti dal segnale
|
||||
causale `target_series` sui dati certificati. Account-independent (gira anche offline nel
|
||||
container). Si ricalcola a ogni render -> include sia lo storico sia i trade forward man mano
|
||||
che arrivano. Ritorna gli ultimi `limit` (piu' recenti primi)."""
|
||||
tp = TrendPortfolio(**CANONICAL)
|
||||
out: list[dict] = []
|
||||
for a in ASSETS:
|
||||
df = resample_1d(load(a, "1h"))
|
||||
c = df["close"].to_numpy(dtype=float)
|
||||
dt = pd.to_datetime(df["datetime"]).to_numpy()
|
||||
tgt = tp.target_series(df)
|
||||
prev = 0.0
|
||||
for i in range(len(tgt)):
|
||||
if np.sign(tgt[i]) != np.sign(prev):
|
||||
out.append(dict(
|
||||
ts=int(pd.Timestamp(dt[i]).value // 10**6),
|
||||
date=str(pd.Timestamp(dt[i]).date()),
|
||||
asset=a,
|
||||
action="ENTRY" if tgt[i] != 0 else "EXIT",
|
||||
from_pos=round(float(prev), 3),
|
||||
to_pos=round(float(tgt[i]), 3),
|
||||
price=round(float(c[i]), 1),
|
||||
))
|
||||
prev = tgt[i]
|
||||
out.sort(key=lambda r: r["ts"], reverse=True)
|
||||
return out[:limit]
|
||||
|
||||
|
||||
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], price=marks[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,
|
||||
))
|
||||
live_trades = []
|
||||
if client is not None:
|
||||
for a in ASSETS:
|
||||
try:
|
||||
for tr in client.trade_history(INSTRUMENT[a], limit=8):
|
||||
live_trades.append(dict(
|
||||
ts=int(tr.get("timestamp") or 0), instrument=INSTRUMENT[a],
|
||||
direction=(tr.get("direction") or "").upper(),
|
||||
amount=float(tr.get("amount") or 0), price=float(tr.get("price") or 0),
|
||||
fee=float(tr.get("fee") or 0)))
|
||||
except Exception:
|
||||
pass
|
||||
live_trades.sort(key=lambda r: r["ts"], reverse=True)
|
||||
live_trades = live_trades[:12]
|
||||
|
||||
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, live_trades=live_trades,
|
||||
flat=all(abs(targets[a]) < 1e-9 for a in ASSETS),
|
||||
paper_aligned=(paper_ts == last_ts),
|
||||
)
|
||||
@@ -0,0 +1,84 @@
|
||||
"""Test deterministici dello SHADOW/esecuzione TP01 (src/live/deribit.py).
|
||||
|
||||
Coprono la logica a rischio zero che NON tocca la rete: quantizzazione notional->contratti (INVERSE
|
||||
e LINEARE USDC), sizing target, costruzione ordine di ribilancio (buy/sell/exit/None), e PARITA' col
|
||||
backtest. Il conto reale e' USDC -> il path principale e' il LINEARE BTC_USDC-PERPETUAL. 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
|
||||
|
||||
LIN = "BTC_USDC-PERPETUAL" # lineare USDC: amount in BTC, step 0.0001 (path reale del conto)
|
||||
PX = 64000.0
|
||||
|
||||
|
||||
def test_notional_linear_usdc():
|
||||
# amount in base-coin = notional/price, quantizzato a 0.0001, clamp al minimo
|
||||
assert notional_to_amount(LIN, 6.4, price=PX) == 0.0001 # 6.4/64000 = 0.0001
|
||||
assert notional_to_amount(LIN, 12.8, price=PX) == 0.0002
|
||||
assert notional_to_amount(LIN, 3.0, price=PX) == 0.0 # < mezzo step ($3.2) -> niente
|
||||
assert notional_to_amount(LIN, 100, price=None) == 0.0 # lineare senza prezzo -> 0
|
||||
assert notional_to_amount(LIN, -6.4, price=PX) == 0.0001 # usa il valore assoluto
|
||||
|
||||
|
||||
def test_notional_inverse_still_supported():
|
||||
# l'helper regge ancora gli inverse (amount in USD), senza prezzo
|
||||
assert notional_to_amount("BTC-PERPETUAL", 1000) == 1000
|
||||
assert notional_to_amount("BTC-PERPETUAL", 7) == 10 # clamp al minimo
|
||||
assert notional_to_amount("BTC-PERPETUAL", 3) == 0.0
|
||||
|
||||
|
||||
def test_no_float_artifacts():
|
||||
v = notional_to_amount(LIN, 0.0001 * PX * 72, price=PX) # 72 step esatti
|
||||
assert v == 0.0072 and abs(v - 0.0072) < 1e-12
|
||||
|
||||
|
||||
def test_target_notional_5050_weight():
|
||||
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_linear():
|
||||
o = build_rebalance_order(LIN, target_fraction=1.0, weight=0.5,
|
||||
equity_usd=2000, current_pos_usd=0.0, price=PX)
|
||||
assert o["side"] == "buy" and o["reduce_only"] is False
|
||||
assert o["target_notional"] == 1000 and o["delta_notional"] == 1000
|
||||
assert abs(o["amount"] - 0.0156) < 1e-9 # 1000/64000=0.015625 -> 0.0156
|
||||
|
||||
|
||||
def test_build_order_exit_is_reduce_only():
|
||||
o = build_rebalance_order(LIN, target_fraction=0.0, weight=0.5,
|
||||
equity_usd=2000, current_pos_usd=1000.0, price=PX)
|
||||
assert o["side"] == "sell" and o["reduce_only"] is True and o["amount"] > 0
|
||||
|
||||
|
||||
def test_build_order_already_at_target_is_none():
|
||||
o = build_rebalance_order(LIN, 1.0, 0.5, 2000, current_pos_usd=1000.0, price=PX)
|
||||
assert o is None # delta 0 -> nessun ordine
|
||||
|
||||
|
||||
def test_build_order_subthreshold_is_none():
|
||||
# delta $2 (< mezzo step in notional, $3.2 a 64k) -> niente ordine
|
||||
o = build_rebalance_order(LIN, 1.0, 0.5, 2000, current_pos_usd=998.0, price=PX)
|
||||
assert o is None
|
||||
|
||||
|
||||
def test_partial_rebalance_direction():
|
||||
up = build_rebalance_order(LIN, 1.0, 0.5, 2000, 600.0, price=PX) # compra il delta
|
||||
dn = build_rebalance_order(LIN, 1.0, 0.5, 2000, 1400.0, price=PX) # vende il delta
|
||||
assert up["side"] == "buy" and up["delta_notional"] == 400
|
||||
assert dn["side"] == "sell" and dn["delta_notional"] == -400 and dn["reduce_only"] is False
|
||||
|
||||
|
||||
def test_parity_live_target_equals_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