feat(live): conto USDC -> strumenti lineari; entrata/uscita da Old; dashboard LIVE separato da PAPER

Correzione post-micro-test (il conto e' USDC, non BTC/ETH):
- deribit.py: INSTRUMENT -> BTC/ETH_USDC-PERPETUAL (lineari, gli unici eseguibili sul conto USDC);
  notional_to_amount gestisce i lineari (amount in base-coin = notional/price); + quantize_price;
  trade_history (read-only) per i trade reali. build_rebalance_order passa il prezzo.
- shadow.py: sizing col prezzo; espone live_trades (trade reali eseguiti su Deribit).

Entrata/uscita verificate (logica presa da Old/src/live/execution.py):
- execution.py: open() market verificato (state=='filled' + trade, fill/fee reali, filled_amount
  autorevole), close() market reduce_only (le CHIUSURE si tentano SEMPRE, senza cap), disaster-SL
  STOP_MARKET reduce_only. Cap di size SOLO sulle aperture. Fill dataclass.
- microtest.py: usa open()/close(); safe-close se l'apertura non e' verificata.

Dashboard: sezione PAPER (backtest+forward) separata da sezione LIVE (conto reale Deribit: shadow
TP01 + Trades REALI eseguiti). Test 27/27.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Adriano Dal Pastro
2026-06-20 15:15:45 +00:00
parent c00f6016df
commit cddea50c5a
6 changed files with 238 additions and 133 deletions
+18 -3
View File
@@ -112,6 +112,15 @@ def html():
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}}
@@ -122,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>
.warn{{color:#f1c40f;font-size:12px}}
.section{{font-size:13px;font-weight:600;letter-spacing:.05em;margin:30px 0 12px;padding-bottom:7px;border-bottom:1px solid #222b36;color:#8a93a0}}
.section.live{{color:#e74c3c;border-color:#3a2329}}</style></head><body>
<h1>PythagorasGoal — Portafoglio attivo (TP01 + XS01 + VRP01)</h1>
<div class=sub>monitor PAPER + SHADOW · v{d['version']} · ultimo dato {d['last_data']} · esecuzione REALE disabilitata</div>
<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>
@@ -134,7 +146,6 @@ th{{color:#8a93a0;font-weight:500}}.y{{display:inline-block;background:#161b22;b
</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>Shadow live — TP01 su Deribit</b> (sola lettura, nessun ordine inviato):<br>{shadow_html}</div>
<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>
<h3 style="font-size:14px;color:#8a93a0">Posizioni correnti (ultima barra chiusa)</h3>
@@ -142,6 +153,10 @@ th{{color:#8a93a0;font-weight:500}}.y{{display:inline-block;background:#161b22;b
<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>
<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>"""
+31 -7
View File
@@ -30,7 +30,8 @@ _CONTRACT = {
"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},
}
INSTRUMENT = {"BTC": "BTC-PERPETUAL", "ETH": "ETH-PERPETUAL"}
# 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) -----------------------------
@@ -41,16 +42,32 @@ def _quantize_step(value: float, step: float, mn: float) -> float:
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)."""
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)."""
@@ -58,12 +75,13 @@ def target_notional_usd(target_fraction: float, weight: float, equity_usd: float
def build_rebalance_order(instrument: str, target_fraction: float, weight: float,
equity_usd: float, current_pos_usd: float) -> dict | None:
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."""
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)
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
@@ -141,3 +159,9 @@ class DeribitRead:
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 [])
+101 -48
View File
@@ -1,73 +1,126 @@
"""Esecuzione REALE su Deribit mainnet (via Cerbero MCP) — SOLO per il micro-test controllato.
"""Esecuzione REALE su Deribit mainnet (via Cerbero MCP) — entrata/uscita verificate.
Estende DeribitRead (sola lettura) coi metodi di trading MINIMI: market order, trade history (fee
reali), verifica posizione. GUARDRAIL HARD: solo BTC-PERPETUAL, notional <= MICRO_MAX_USD ($10), e
ogni open/close si verifica rileggendo la posizione. Nessun parametro di leva (su Deribit non e'
settabile per-ordine: l'esposizione la decide la SIZE dell'ordine — verificato nello stack pre-reset).
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.
⚠️ INVIA ORDINI REALI CON SOLDI VERI. Esiste solo per `scripts/live/microtest.py`. Non importare
altrove finche' il percorso live non e' validato + abilitato esplicitamente.
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
import time
from dataclasses import dataclass
from src.live.deribit import DeribitRead, notional_to_amount
from src.live.deribit import DeribitRead, notional_to_amount, quantize_price
# Conto USDC -> perp LINEARE USDC: amount in base-coin (BTC), step 0.0001 (~$6 a $63k).
ALLOWED = {"BTC_USDC-PERPETUAL"} # solo questo strumento nel micro-test
MAX_AMOUNT = {"BTC_USDC-PERPETUAL": 0.0002} # cap hard ~$13: micro, leva ~0
# Conto USDC -> perp LINEARE USDC (amount in base-coin). Cap micro-test: ~$13.
ALLOWED = {"BTC_USDC-PERPETUAL", "ETH_USDC-PERPETUAL"}
MAX_AMOUNT = {"BTC_USDC-PERPETUAL": 0.0002, "ETH_USDC-PERPETUAL": 0.005}
FLAT_USD = 1.0 # |notional| < $1 = posizione considerata flat
class GuardrailError(RuntimeError):
pass
def summarize_fill(resp: dict) -> dict | None:
"""Riassume i trade di una risposta place_order: amount, prezzo medio ponderato, fee totale."""
trades = resp.get("trades", []) if isinstance(resp, dict) else []
if not trades:
return None
amt = sum(float(t.get("amount", 0) or 0) for t in trades)
px = (sum(float(t.get("price", 0) or 0) * float(t.get("amount", 0) or 0) for t in trades) / amt) if amt else None
fee = sum(float(t.get("fee", 0) or 0) for t in trades)
return dict(amount=amt, price=px, fee=fee, n=len(trades))
@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):
"""SOLA capacita' di trading consentita: market order entro i guardrail, + verifica. Niente altro."""
"""Trading minimo e verificato. Apre/chiude solo entro i guardrail; le chiusure sempre."""
def _check(self, instrument: str, amount: float) -> None:
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 nel micro-test: {instrument}")
cap = MAX_AMOUNT[instrument]
if amount <= 0 or amount > cap:
raise GuardrailError(f"size {amount} fuori dal cap micro-test (0, {cap}]")
def place_market(self, instrument: str, side: str, amount: float,
reduce_only: bool = False, label: str = "tp01-microtest") -> dict:
"""Market order REALE entro i guardrail. side in {'buy','sell'}. NESSUNA leva passata."""
self._check(instrument, amount)
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": "market", "label": label}
"type": order_type, "label": label}
if price is not None:
payload["price"] = price
if reduce_only:
payload["reduce_only"] = True
return self._unwrap(self._post("/mcp-deribit/tools/place_order", payload)) or {}
resp = self._unwrap(self._post("/mcp-deribit/tools/place_order", payload)) or {}
def trade_history(self, instrument: str, limit: int = 20) -> list[dict]:
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 [])
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}")
def wait_until(self, instrument: str, want_usd: float, tol: float = 1.0,
polls: int = 6, sleep: float = 0.6) -> tuple[bool, float]:
"""Poll get_positions finche' la size si avvicina a want_usd (tol). Ritorna (ok, size_letta)."""
size = self.position_usd(instrument)
for _ in range(polls):
if abs(size - want_usd) <= tol:
return True, size
time.sleep(sleep)
size = self.position_usd(instrument)
return abs(size - want_usd) <= tol, size
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)
# --- 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)
+17 -2
View File
@@ -128,7 +128,7 @@ def shadow_report(offline: bool = False, equity_override: float | None = None) -
assets, orders = [], []
for a in ASSETS:
inst = INSTRUMENT[a]
order = build_rebalance_order(inst, targets[a], WEIGHT, equity, positions[a])
order = build_rebalance_order(inst, targets[a], WEIGHT, equity, positions[a], price=marks[a])
if order:
orders.append(order)
parity = None
@@ -140,11 +140,26 @@ def shadow_report(offline: bool = False, equity_override: float | None = None) -
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,
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),
)