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
+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)