From c00f6016df14c296c06e2f8fdaa65e6fa7255c58 Mon Sep 17 00:00:00 2001 From: Adriano Dal Pastro Date: Sat, 20 Jun 2026 15:06:53 +0000 Subject: [PATCH] =?UTF-8?q?feat(live):=20micro-test=20esecuzione=20REALE?= =?UTF-8?q?=20su=20Deribit=20mainnet=20(USDC=20linear)=20=E2=80=94=20round?= =?UTF-8?q?-trip=20validato?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Primo ordine reale post-reset, a rischio ~0 ($6 notional, leva 0.011x). Scoperto che il conto e' USDC -> strumento eseguibile = perp LINEARE BTC_USDC-PERPETUAL (l'inverse BTC-PERPETUAL fallisce 'not_enough_funds'). Round-trip BUY/SELL reduce_only verificato: fill reali, fee reali (0.0064 USDC), posizione tornata a FLAT, costo totale $0.0071. - src/live/execution.py : DeribitTrader (estende DeribitRead) con market order + verifica posizione, GUARDRAIL hard (solo BTC_USDC-PERPETUAL, amount <= 0.0002 BTC). Niente leva per-ordine (Deribit non la accetta: l'esposizione la decide la SIZE). - scripts/live/microtest.py : runner round-trip, default DRY-RUN, --live per inviare. Pre-flight ABORT se posizione preesistente; chiusura reduce_only; verifica ritorno a FLAT. - src/live/deribit.py : aggiunti spec contratto LINEARI USDC (BTC/ETH_USDC-PERPETUAL). Co-Authored-By: Claude Opus 4.8 (1M context) --- scripts/live/microtest.py | 97 +++++++++++++++++++++++++++++++++++++++ src/live/deribit.py | 6 ++- src/live/execution.py | 73 +++++++++++++++++++++++++++++ 3 files changed, 175 insertions(+), 1 deletion(-) create mode 100644 scripts/live/microtest.py create mode 100644 src/live/execution.py diff --git a/scripts/live/microtest.py b/scripts/live/microtest.py new file mode 100644 index 0000000..6523009 --- /dev/null +++ b/scripts/live/microtest.py @@ -0,0 +1,97 @@ +"""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. + +Sicurezze: default DRY-RUN (NON invia). Guardrail hard in src/live/execution.py (solo +BTC_USDC-PERPETUAL, amount <= 0.0002 BTC). Pre-flight: ABORT se esiste gia' una posizione. Apertura +verificata; chiusura reduce_only; a fine test verifica il ritorno a 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 MAX_AMOUNT, DeribitTrader, summarize_fill + +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) + + # ---- pre-flight (sola lettura) ---- + try: + equity = float(t.account_summary("USDC").get("equity") or 0) + mark = t.mark_price(INSTRUMENT) + pos0 = t.position_usd(INSTRUMENT) # per i lineari = size in BTC + 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)") # size lineare = USD notional + print(f" ordine 1 (apertura): BUY {AMOUNT:.4f} BTC market (~${notional:.2f}, leva {notional/equity:.4f}x)") + print(f" ordine 2 (chiusura): SELL {AMOUNT:.4f} BTC market reduce_only") + print(f" guardrail : solo {INSTRUMENT}, cap {MAX_AMOUNT[INSTRUMENT]} BTC") + + if abs(pos0) > 1e-9: + print(f"\n ABORT: posizione preesistente ({pos0:.5f} BTC). 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: invio APERTURA ...") + open_resp = t.place_market(INSTRUMENT, "buy", AMOUNT, label="tp01-microtest-open") + if isinstance(open_resp, dict) and open_resp.get("error"): + print(f" RIFIUTATO: {open_resp.get('error')} -> nessuna posizione. Stop.") + return + of = summarize_fill(open_resp) + ok_open, size_after = t.wait_until(INSTRUMENT, want_usd=notional, tol=max(1.0, notional * 0.5)) + if of: + print(f" FILL apertura: {of['amount']:.4f} BTC @ ${of['price']:,.1f} fee {of['fee']:.6f} USDC") + print(f" posizione dopo apertura: ${size_after:,.2f} notional ({'OK' if ok_open else f'ATTESO ~${notional:.2f} — VERIFICA'})") + + # ---- LIVE: chiusura (reduce_only) ---- + print(" >>> LIVE: invio CHIUSURA (reduce_only) ...") + close_resp = t.place_market(INSTRUMENT, "sell", AMOUNT, reduce_only=True, label="tp01-microtest-close") + cf = summarize_fill(close_resp) + flat_ok, size_end = t.wait_until(INSTRUMENT, want_usd=0.0, tol=1e-9) + if cf: + print(f" FILL chiusura: {cf['amount']:.4f} BTC @ ${cf['price']:,.1f} fee {cf['fee']:.6f} USDC") + print(f" posizione finale: ${size_end:,.2f} notional") + + # ---- report ---- + print("\n " + "-" * 62) + if flat_ok: + print(" ✓ ROUND-TRIP COMPLETO — posizione tornata a FLAT.") + else: + print(f" ⚠️ ATTENZIONE: posizione NON flat (${size_end:,.2f}) — INTERVENTO MANUALE: chiudi a mano.") + if of and cf: + tot_fee = of["fee"] + cf["fee"] + pnl = AMOUNT * (cf["price"] - of["price"]) # lineare USDC: pnl in USDC + print(f" entry ${of['price']:,.1f} -> exit ${cf['price']:,.1f} | fee totale {tot_fee:.6f} USDC | " + f"pnl lordo {pnl:+.4f} USDC | netto {pnl - tot_fee:+.4f} USDC") + print(" Validato: invio ordine reale, fill, fee reali, reconciliation, ritorno a flat.") + + +if __name__ == "__main__": + main() diff --git a/src/live/deribit.py b/src/live/deribit.py index 39c6414..2c32cd2 100644 --- a/src/live/deribit.py +++ b/src/live/deribit.py @@ -21,10 +21,14 @@ PROJECT_ROOT = Path(__file__).resolve().parents[2] BASE_URL = os.environ.get("CERBERO_BASE_URL", "https://cerbero-mcp.tielogic.xyz") TIMEOUT = 15 -# Inverse perp: amount = USD notional, step in USD. settle = base-coin (per get_positions/fee). +# 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}, } INSTRUMENT = {"BTC": "BTC-PERPETUAL", "ETH": "ETH-PERPETUAL"} diff --git a/src/live/execution.py b/src/live/execution.py new file mode 100644 index 0000000..05c823a --- /dev/null +++ b/src/live/execution.py @@ -0,0 +1,73 @@ +"""Esecuzione REALE su Deribit mainnet (via Cerbero MCP) — SOLO per il micro-test controllato. + +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). + +⚠️ 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. +""" +from __future__ import annotations + +import time + +from src.live.deribit import DeribitRead, notional_to_amount + +# 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 + + +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)) + + +class DeribitTrader(DeribitRead): + """SOLA capacita' di trading consentita: market order entro i guardrail, + verifica. Niente altro.""" + + def _check(self, instrument: str, amount: float) -> None: + 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) + if side not in ("buy", "sell"): + raise GuardrailError(f"side non valido: {side}") + payload = {"instrument_name": instrument, "side": side, "amount": amount, + "type": "market", "label": label} + if reduce_only: + payload["reduce_only"] = True + return 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 []) + + 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