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:
@@ -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()
|
||||
Reference in New Issue
Block a user