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
+33 -38
View File
@@ -2,11 +2,11 @@
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.
(~0x leva, decoupled dal segnale): test della plumbing, non della strategia. Usa open()/close()
verificati di src/live/execution.py (logica entrata/uscita presa da Old).
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).
Sicurezze: default DRY-RUN. Pre-flight ABORT se posizione preesistente. La chiusura (reduce_only,
sempre permessa) flatta comunque dopo l'apertura; verifica finale di 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
@@ -19,7 +19,7 @@ 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
from src.live.execution import FLAT_USD, MAX_AMOUNT, DeribitTrader
INSTRUMENT = "BTC_USDC-PERPETUAL"
AMOUNT = 0.0001 # base-coin (BTC) = 1 contratto minimo (~$6 a $63k)
@@ -32,12 +32,10 @@ def main():
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
pos0 = t.position_usd(INSTRUMENT)
except Exception as e:
print(f" PRE-FLIGHT FALLITO (read): {type(e).__name__}: {e}\n -> non procedo.")
return
@@ -45,51 +43,48 @@ def main():
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")
print(f" posizione attuale : ${pos0:,.2f} notional (dev'essere 0)")
print(f" apertura : BUY {AMOUNT:.4f} BTC market (~${notional:.2f}, leva {notional/equity:.4f}x)")
print(f" chiusura : SELL {AMOUNT:.4f} BTC market reduce_only")
print(f" guardrail: solo {INSTRUMENT}, cap apertura {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.")
if abs(pos0) >= FLAT_USD:
print(f"\n ABORT: posizione preesistente (${pos0:,.2f}). 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.")
print("\n >>> LIVE: APERTURA ...")
fo = t.open(INSTRUMENT, "buy", AMOUNT, label="tp01-microtest-open")
if not fo.verified:
print(f" apertura NON verificata: {fo.notes}")
# safety: assicura comunque il flat
fc = t.close(INSTRUMENT, label="tp01-microtest-safeclose")
print(f" safe-close: {'eseguita' if fc else 'gia flat'}; posizione ${t.position_usd(INSTRUMENT):,.2f}")
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'})")
print(f" FILL: {fo.filled:.4f} BTC @ ${fo.price:,.1f} fee {fo.fee_usdc:.6f} USDC (state={fo.state})")
# ---- 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")
print(" >>> LIVE: CHIUSURA (reduce_only) ...")
fc = t.close(INSTRUMENT, label="tp01-microtest-close")
pos_end = t.position_usd(INSTRUMENT)
if fc:
print(f" FILL: {fc.filled:.4f} BTC @ ${fc.price:,.1f} fee {fc.fee_usdc:.6f} USDC (state={fc.state})")
print(f" posizione finale: ${pos_end:,.2f} notional")
# ---- report ----
print("\n " + "-" * 62)
if flat_ok:
if abs(pos_end) < FLAT_USD:
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(f" ⚠️ posizione NON flat (${pos_end:,.2f}) — INTERVENTO MANUALE: chiudi a mano.")
if fo.verified and fc:
tot_fee = fo.fee_usdc + fc.fee_usdc
pnl = AMOUNT * ((fc.price or 0) - (fo.price or 0))
print(f" entry ${fo.price:,.1f} -> exit ${fc.price:,.1f} | fee {tot_fee:.6f} USDC | "
f"pnl lordo {pnl:+.4f} | netto {pnl - tot_fee:+.4f} USDC")
print(" Validato: invio ordine reale, fill, fee reali, reconciliation, ritorno a flat.")