bc9e322d0d
scripts/live/live_execute.py porta il conto reale al target di TP01 (min(0.5*frazione*equity, cap/asset)): apre/riduce/chiude via DeribitTrader.rebalance_to(). DOPPIO GATE: config/live.json execution_enabled=true (master, default false) E flag --execute; senza entrambi e' dry-run. Reconciliation post-ordine + log in data/live/executions.jsonl. TP01 flat -> 0 azioni. - execution.py: rebalance_to() (open/reduce/close al target); MAX_AMOUNT alzato a tetto hard anti-fat-finger (~$630/$430 su conto ~$600), il sizing operativo lo decide config max_notional. - config/live.json: master switch + cap/asset $300 + min ordine $5 + disaster_sl_pct. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
152 lines
7.8 KiB
Python
152 lines
7.8 KiB
Python
"""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)
|