feat(live): micro-test esecuzione REALE su Deribit mainnet (USDC linear) — round-trip validato
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) <noreply@anthropic.com>
This commit is contained in:
+5
-1
@@ -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"}
|
||||
|
||||
|
||||
@@ -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
|
||||
Reference in New Issue
Block a user