2 Commits

Author SHA1 Message Date
Adriano Dal Pastro cddea50c5a 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>
2026-06-20 15:15:45 +00:00
Adriano Dal Pastro c00f6016df 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>
2026-06-20 15:06:53 +00:00
6 changed files with 327 additions and 48 deletions
+92
View File
@@ -0,0 +1,92 @@
"""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. Usa open()/close()
verificati di src/live/execution.py (logica entrata/uscita presa da Old).
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
"""
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 FLAT_USD, MAX_AMOUNT, DeribitTrader
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)
try:
equity = float(t.account_summary("USDC").get("equity") or 0)
mark = t.mark_price(INSTRUMENT)
pos0 = t.position_usd(INSTRUMENT)
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)")
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) >= 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: 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
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: 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 abs(pos_end) < FLAT_USD:
print(" ✓ ROUND-TRIP COMPLETO — posizione tornata a FLAT.")
else:
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.")
if __name__ == "__main__":
main()
+18 -3
View File
@@ -112,6 +112,15 @@ def html():
f"<td>${t['price']:,.0f}</td></tr>") f"<td>${t['price']:,.0f}</td></tr>")
if not trows: if not trows:
trows = "<tr><td colspan=5 style='color:#8a93a0'>nessun trade ancora (TP01 flat / in cash)</td></tr>" trows = "<tr><td colspan=5 style='color:#8a93a0'>nessun trade ancora (TP01 flat / in cash)</td></tr>"
live_trows = ""
for x in ((sh.get("live_trades") if sh and "error" not in sh else None) or []):
dcls = "g" if x["direction"] == "BUY" else "r"
when = str(pd.Timestamp(x["ts"], unit="ms", tz="UTC"))[:16] if x["ts"] else ""
sym = x["instrument"].replace("_USDC-PERPETUAL", "").replace("-PERPETUAL", "")
live_trows += (f"<tr><td>{when}</td><td>{sym}</td><td class={dcls}>{x['direction']}</td>"
f"<td>{x['amount']:.4f}</td><td>${x['price']:,.1f}</td><td>{x['fee']:.5f}</td></tr>")
if not live_trows:
live_trows = "<tr><td colspan=6 style='color:#8a93a0'>nessun trade reale eseguito (o conto non leggibile dal container)</td></tr>"
return f"""<!doctype html><html><head><meta charset=utf-8> return f"""<!doctype html><html><head><meta charset=utf-8>
<meta http-equiv=refresh content=300><title>PythagorasGoal — Portafoglio</title> <meta http-equiv=refresh content=300><title>PythagorasGoal — Portafoglio</title>
<style>body{{font-family:-apple-system,Segoe UI,Roboto,sans-serif;background:#0e1116;color:#e6e6e6;margin:0;padding:24px;max-width:980px;margin:auto}} <style>body{{font-family:-apple-system,Segoe UI,Roboto,sans-serif;background:#0e1116;color:#e6e6e6;margin:0;padding:24px;max-width:980px;margin:auto}}
@@ -122,9 +131,12 @@ h1{{font-size:20px;margin:0 0 2px}}.sub{{color:#8a93a0;font-size:13px;margin-bot
table{{width:100%;border-collapse:collapse;margin:8px 0 20px}}td,th{{text-align:left;padding:7px 10px;border-bottom:1px solid #222b36;font-size:14px}} table{{width:100%;border-collapse:collapse;margin:8px 0 20px}}td,th{{text-align:left;padding:7px 10px;border-bottom:1px solid #222b36;font-size:14px}}
th{{color:#8a93a0;font-weight:500}}.y{{display:inline-block;background:#161b22;border:1px solid #222b36;border-radius:6px;padding:3px 8px;margin:2px;font-size:12px}} th{{color:#8a93a0;font-weight:500}}.y{{display:inline-block;background:#161b22;border:1px solid #222b36;border-radius:6px;padding:3px 8px;margin:2px;font-size:12px}}
.box{{background:#161b22;border:1px solid #222b36;border-radius:10px;padding:14px 18px;margin-bottom:18px}} .box{{background:#161b22;border:1px solid #222b36;border-radius:10px;padding:14px 18px;margin-bottom:18px}}
.warn{{color:#f1c40f;font-size:12px}}</style></head><body> .warn{{color:#f1c40f;font-size:12px}}
.section{{font-size:13px;font-weight:600;letter-spacing:.05em;margin:30px 0 12px;padding-bottom:7px;border-bottom:1px solid #222b36;color:#8a93a0}}
.section.live{{color:#e74c3c;border-color:#3a2329}}</style></head><body>
<h1>PythagorasGoal — Portafoglio attivo (TP01 + XS01 + VRP01)</h1> <h1>PythagorasGoal — Portafoglio attivo (TP01 + XS01 + VRP01)</h1>
<div class=sub>monitor PAPER + SHADOW · v{d['version']} · ultimo dato {d['last_data']} · esecuzione REALE disabilitata</div> <div class=sub>monitor · v{d['version']} · ultimo dato {d['last_data']} · esecuzione REALE non attiva (solo micro-test)</div>
<div class="section">PAPER — simulato (backtest + forward virtuale)</div>
<div class=cards> <div class=cards>
<div class=card><div class=k>FULL Sharpe</div><div class="v g">{f['sharpe']:.2f}</div></div> <div class=card><div class=k>FULL Sharpe</div><div class="v g">{f['sharpe']:.2f}</div></div>
<div class=card><div class=k>HOLD-OUT Sharpe (2025-26)</div><div class="v g">{ho['sharpe']:.2f}</div></div> <div class=card><div class=k>HOLD-OUT Sharpe (2025-26)</div><div class="v g">{ho['sharpe']:.2f}</div></div>
@@ -134,7 +146,6 @@ th{{color:#8a93a0;font-weight:500}}.y{{display:inline-block;background:#161b22;b
</div> </div>
<div class=box><div class=k style="color:#8a93a0;font-size:12px">EQUITY backtest (2019→oggi, €2k)</div>{svg_spark(d['spark'])}</div> <div class=box><div class=k style="color:#8a93a0;font-size:12px">EQUITY backtest (2019→oggi, €2k)</div>{svg_spark(d['spark'])}</div>
<div class=box><b>Paper forward-only:</b> {paper_html}</div> <div class=box><b>Paper forward-only:</b> {paper_html}</div>
<div class=box><b>Shadow live — TP01 su Deribit</b> (sola lettura, nessun ordine inviato):<br>{shadow_html}</div>
<h3 style="font-size:14px;color:#8a93a0">Sleeve</h3> <h3 style="font-size:14px;color:#8a93a0">Sleeve</h3>
<table><tr><th>sleeve</th><th>peso</th><th>FULL Sh</th><th>DD</th><th>HOLD Sh</th></tr>{rows}</table> <table><tr><th>sleeve</th><th>peso</th><th>FULL Sh</th><th>DD</th><th>HOLD Sh</th></tr>{rows}</table>
<h3 style="font-size:14px;color:#8a93a0">Posizioni correnti (ultima barra chiusa)</h3> <h3 style="font-size:14px;color:#8a93a0">Posizioni correnti (ultima barra chiusa)</h3>
@@ -142,6 +153,10 @@ th{{color:#8a93a0;font-weight:500}}.y{{display:inline-block;background:#161b22;b
<h3 style="font-size:14px;color:#8a93a0">Trades TP01 — entry/exit (segnale causale, ultimi 15)</h3> <h3 style="font-size:14px;color:#8a93a0">Trades TP01 — entry/exit (segnale causale, ultimi 15)</h3>
<table><tr><th>data</th><th>asset</th><th>azione</th><th>posizione</th><th>prezzo</th></tr>{trows}</table> <table><tr><th>data</th><th>asset</th><th>azione</th><th>posizione</th><th>prezzo</th></tr>{trows}</table>
<div style="margin-top:10px">{yrs}</div> <div style="margin-top:10px">{yrs}</div>
<div class="section live">LIVE — Deribit mainnet (conto reale, sola lettura)</div>
<div class=box><b>Shadow TP01</b> (cosa farebbe ORA sul conto reale, nessun ordine inviato):<br>{shadow_html}</div>
<h3 style="font-size:14px;color:#8a93a0">Trades REALI eseguiti su Deribit</h3>
<table><tr><th>data/ora UTC</th><th>strum.</th><th>dir</th><th>amount</th><th>prezzo</th><th>fee USDC</th></tr>{live_trows}</table>
<p class=warn>⚠️ Paper/monitor. XS01 e' STAT-MODE (book a 19 gambe market-neutral, non eseguibile a €2k, storia ~2.5 anni). VRP01 = lead short-vol MODELLATO (non deploy pieno). TP01 e' l'unico deployable pieno: lo "Shadow live" mostra cosa farebbe sul mainnet, ma NON invia ordini.</p> <p class=warn>⚠️ Paper/monitor. XS01 e' STAT-MODE (book a 19 gambe market-neutral, non eseguibile a €2k, storia ~2.5 anni). VRP01 = lead short-vol MODELLATO (non deploy pieno). TP01 e' l'unico deployable pieno: lo "Shadow live" mostra cosa farebbe sul mainnet, ma NON invia ordini.</p>
</body></html>""" </body></html>"""
+36 -8
View File
@@ -21,12 +21,17 @@ PROJECT_ROOT = Path(__file__).resolve().parents[2]
BASE_URL = os.environ.get("CERBERO_BASE_URL", "https://cerbero-mcp.tielogic.xyz") BASE_URL = os.environ.get("CERBERO_BASE_URL", "https://cerbero-mcp.tielogic.xyz")
TIMEOUT = 15 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 = { _CONTRACT = {
"BTC-PERPETUAL": {"min": 10.0, "step": 10.0, "tick": 0.5, "settle": "BTC"}, "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"}, "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"} # Il conto reale e' USDC -> mappiamo gli asset sui perp LINEARI USDC (gli unici eseguibili qui).
INSTRUMENT = {"BTC": "BTC_USDC-PERPETUAL", "ETH": "ETH_USDC-PERPETUAL"}
# ----------------------------- costruzione ordini (pura, testabile, NIENTE rete) ----------------------------- # ----------------------------- costruzione ordini (pura, testabile, NIENTE rete) -----------------------------
@@ -37,16 +42,32 @@ def _quantize_step(value: float, step: float, mn: float) -> float:
return float(max(n * Decimal(str(step)), Decimal(str(mn)))) return float(max(n * Decimal(str(step)), Decimal(str(mn))))
def notional_to_amount(instrument: str, notional_usd: float) -> float: def notional_to_amount(instrument: str, notional_usd: float, price: float | None = None) -> float:
"""USD notional -> `amount` Deribit (inverse: amount in USD), arrotondato allo step e clampato """USD notional -> `amount` Deribit, arrotondato allo step e clampato al minimo. Ritorna 0.0 se
al minimo. Ritorna 0.0 se |notional| < mezzo step (sotto-soglia: niente ordine).""" sotto mezzo step. INVERSE: amount in USD (price ignorato). LINEAR USDC: amount in base-coin
(units = notional/price -> serve il `price`; senza price ritorna 0.0)."""
spec = _CONTRACT[instrument] spec = _CONTRACT[instrument]
step, mn = spec["step"], spec["min"] step, mn = spec["step"], spec["min"]
if spec.get("linear"):
if not price:
return 0.0
units = abs(notional_usd) / price
if units < step / 2:
return 0.0
return _quantize_step(units, step, mn)
if abs(notional_usd) < step / 2: if abs(notional_usd) < step / 2:
return 0.0 return 0.0
return _quantize_step(abs(notional_usd), step, mn) return _quantize_step(abs(notional_usd), step, mn)
def quantize_price(instrument: str, price: float) -> float:
"""Arrotonda il prezzo al tick dello strumento (per gli ordini stop/limit)."""
tick = _CONTRACT[instrument].get("tick")
if not tick or price <= 0:
return price
return float(round(price / tick) * Decimal(str(tick)))
def target_notional_usd(target_fraction: float, weight: float, equity_usd: float) -> float: def target_notional_usd(target_fraction: float, weight: float, equity_usd: float) -> float:
"""Notional bersaglio (USD) di un asset = peso nel book * frazione-di-equity TP01 * equity. """Notional bersaglio (USD) di un asset = peso nel book * frazione-di-equity TP01 * equity.
Coerente col paper trader (esposizione asset = WEIGHT * target * equity).""" Coerente col paper trader (esposizione asset = WEIGHT * target * equity)."""
@@ -54,12 +75,13 @@ def target_notional_usd(target_fraction: float, weight: float, equity_usd: float
def build_rebalance_order(instrument: str, target_fraction: float, weight: float, def build_rebalance_order(instrument: str, target_fraction: float, weight: float,
equity_usd: float, current_pos_usd: float) -> dict | None: equity_usd: float, current_pos_usd: float, price: float | None = None) -> dict | None:
"""COSTRUISCE (non invia) l'ordine di ribilancio verso il target. Ritorna un dict-ordine o None """COSTRUISCE (non invia) l'ordine di ribilancio verso il target. Ritorna un dict-ordine o None
se sotto-soglia. Long-only TP01 -> target_notional >= 0; delta = target - posizione corrente.""" se sotto-soglia. Long-only TP01 -> target_notional >= 0; delta = target - posizione corrente.
`price` (mark) serve a convertire il notional in base-coin per gli strumenti LINEARI USDC."""
tgt = target_notional_usd(target_fraction, weight, equity_usd) tgt = target_notional_usd(target_fraction, weight, equity_usd)
delta = tgt - current_pos_usd delta = tgt - current_pos_usd
amount = notional_to_amount(instrument, delta) amount = notional_to_amount(instrument, delta, price=price)
if amount == 0.0: if amount == 0.0:
return None return None
is_exit = abs(tgt) < 1e-9 and abs(current_pos_usd) > 0 is_exit = abs(tgt) < 1e-9 and abs(current_pos_usd) > 0
@@ -137,3 +159,9 @@ class DeribitRead:
if p.get("instrument_name") == instrument or p.get("instrument") == instrument: if p.get("instrument_name") == instrument or p.get("instrument") == instrument:
return float(p.get("size") or p.get("size_currency") or 0.0) return float(p.get("size") or p.get("size_currency") or 0.0)
return 0.0 return 0.0
def trade_history(self, instrument: str, limit: int = 20) -> list[dict]:
"""Trade REALMENTE eseguiti sul conto per `instrument` (fonte autorevole fee/fill)."""
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 [])
+126
View File
@@ -0,0 +1,126 @@
"""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). Cap micro-test: ~$13.
ALLOWED = {"BTC_USDC-PERPETUAL", "ETH_USDC-PERPETUAL"}
MAX_AMOUNT = {"BTC_USDC-PERPETUAL": 0.0002, "ETH_USDC-PERPETUAL": 0.005}
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)
# --- 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)
+17 -2
View File
@@ -128,7 +128,7 @@ def shadow_report(offline: bool = False, equity_override: float | None = None) -
assets, orders = [], [] assets, orders = [], []
for a in ASSETS: for a in ASSETS:
inst = INSTRUMENT[a] inst = INSTRUMENT[a]
order = build_rebalance_order(inst, targets[a], WEIGHT, equity, positions[a]) order = build_rebalance_order(inst, targets[a], WEIGHT, equity, positions[a], price=marks[a])
if order: if order:
orders.append(order) orders.append(order)
parity = None parity = None
@@ -140,11 +140,26 @@ def shadow_report(offline: bool = False, equity_override: float | None = None) -
position_usd=positions[a], mark=marks[a], mark_src=marks_src[a], position_usd=positions[a], mark=marks[a], mark_src=marks_src[a],
order=order, paper=(float(paper_pos.get(a, 0.0)) if paper_pos else None), parity=parity, order=order, paper=(float(paper_pos.get(a, 0.0)) if paper_pos else None), parity=parity,
)) ))
live_trades = []
if client is not None:
for a in ASSETS:
try:
for tr in client.trade_history(INSTRUMENT[a], limit=8):
live_trades.append(dict(
ts=int(tr.get("timestamp") or 0), instrument=INSTRUMENT[a],
direction=(tr.get("direction") or "").upper(),
amount=float(tr.get("amount") or 0), price=float(tr.get("price") or 0),
fee=float(tr.get("fee") or 0)))
except Exception:
pass
live_trades.sort(key=lambda r: r["ts"], reverse=True)
live_trades = live_trades[:12]
return dict( return dict(
last_data=str(pd.Timestamp(last_ts, unit="ms", tz="UTC").date()), last_data=str(pd.Timestamp(last_ts, unit="ms", tz="UTC").date()),
online=(client is not None and marks_src.get("BTC") == "mainnet"), online=(client is not None and marks_src.get("BTC") == "mainnet"),
real_equity=real_eq, equity=equity, eq_basis=eq_basis, real_equity=real_eq, equity=equity, eq_basis=eq_basis,
pos_src=pos_src, assets=assets, orders=orders, pos_src=pos_src, assets=assets, orders=orders, live_trades=live_trades,
flat=all(abs(targets[a]) < 1e-9 for a in ASSETS), flat=all(abs(targets[a]) < 1e-9 for a in ASSETS),
paper_aligned=(paper_ts == last_ts), paper_aligned=(paper_ts == last_ts),
) )
+38 -35
View File
@@ -1,9 +1,9 @@
"""Test deterministici dello SHADOW MODE di TP01 (src/live/deribit.py). """Test deterministici dello SHADOW/esecuzione TP01 (src/live/deribit.py).
Coprono la logica a rischio zero che NON tocca la rete: quantizzazione notional->contratti, sizing Coprono la logica a rischio zero che NON tocca la rete: quantizzazione notional->contratti (INVERSE
target, costruzione ordine di ribilancio (buy/sell/exit/None), e PARITA' col backtest (il target e LINEARE USDC), sizing target, costruzione ordine di ribilancio (buy/sell/exit/None), e PARITA' col
live = ultimo target della serie causale). Il fill reale (slippage/fee) NON e' qui: si valida solo backtest. Il conto reale e' USDC -> il path principale e' il LINEARE BTC_USDC-PERPETUAL. Il fill reale
col micro-test mainnet. (slippage/fee) NON e' qui: si valida solo col micro-test mainnet.
""" """
import sys import sys
from pathlib import Path from pathlib import Path
@@ -14,67 +14,70 @@ sys.path.insert(0, str(PROJECT_ROOT))
from src.live.deribit import (build_rebalance_order, notional_to_amount, target_notional_usd) from src.live.deribit import (build_rebalance_order, notional_to_amount, target_notional_usd)
from src.strategies.trend_portfolio import CANONICAL, TrendPortfolio, resample_1d from src.strategies.trend_portfolio import CANONICAL, TrendPortfolio, resample_1d
LIN = "BTC_USDC-PERPETUAL" # lineare USDC: amount in BTC, step 0.0001 (path reale del conto)
PX = 64000.0
def test_notional_to_amount_step_and_min():
# BTC step/min $10 def test_notional_linear_usdc():
# amount in base-coin = notional/price, quantizzato a 0.0001, clamp al minimo
assert notional_to_amount(LIN, 6.4, price=PX) == 0.0001 # 6.4/64000 = 0.0001
assert notional_to_amount(LIN, 12.8, price=PX) == 0.0002
assert notional_to_amount(LIN, 3.0, price=PX) == 0.0 # < mezzo step ($3.2) -> niente
assert notional_to_amount(LIN, 100, price=None) == 0.0 # lineare senza prezzo -> 0
assert notional_to_amount(LIN, -6.4, price=PX) == 0.0001 # usa il valore assoluto
def test_notional_inverse_still_supported():
# l'helper regge ancora gli inverse (amount in USD), senza prezzo
assert notional_to_amount("BTC-PERPETUAL", 1000) == 1000 assert notional_to_amount("BTC-PERPETUAL", 1000) == 1000
assert notional_to_amount("BTC-PERPETUAL", 1006) == 1010 # round allo step assert notional_to_amount("BTC-PERPETUAL", 7) == 10 # clamp al minimo
assert notional_to_amount("BTC-PERPETUAL", 7) == 10 # clamp al minimo (>= mezzo step) assert notional_to_amount("BTC-PERPETUAL", 3) == 0.0
assert notional_to_amount("BTC-PERPETUAL", 3) == 0.0 # < mezzo step -> niente ordine
# ETH step/min $1
assert notional_to_amount("ETH-PERPETUAL", 33.7) == 34
assert notional_to_amount("ETH-PERPETUAL", 0.4) == 0.0
# usa il valore assoluto (il segno lo decide il delta a monte)
assert notional_to_amount("BTC-PERPETUAL", -1000) == 1000
def test_no_float_artifacts(): def test_no_float_artifacts():
# _quantize_step usa Decimal: nessun 0.07200000000000001 & co. v = notional_to_amount(LIN, 0.0001 * PX * 72, price=PX) # 72 step esatti
v = notional_to_amount("ETH-PERPETUAL", 72.0) assert v == 0.0072 and abs(v - 0.0072) < 1e-12
assert v == 72 and float(v).is_integer()
def test_target_notional_5050_weight(): def test_target_notional_5050_weight():
# 50/50 book: notional asset = 0.5 * frazione * equity
assert target_notional_usd(1.0, 0.5, 2000) == 1000 assert target_notional_usd(1.0, 0.5, 2000) == 1000
assert target_notional_usd(2.0, 0.5, 2000) == 2000 # leva-cap 2x -> piena equity sull'asset assert target_notional_usd(2.0, 0.5, 2000) == 2000 # leva-cap 2x -> piena equity sull'asset
assert target_notional_usd(0.0, 0.5, 2000) == 0.0 assert target_notional_usd(0.0, 0.5, 2000) == 0.0
def test_build_order_entry(): def test_build_order_entry_linear():
o = build_rebalance_order("BTC-PERPETUAL", target_fraction=1.0, weight=0.5, o = build_rebalance_order(LIN, target_fraction=1.0, weight=0.5,
equity_usd=2000, current_pos_usd=0.0) equity_usd=2000, current_pos_usd=0.0, price=PX)
assert o["side"] == "buy" and o["amount"] == 1000 and o["reduce_only"] is False assert o["side"] == "buy" and o["reduce_only"] is False
assert o["target_notional"] == 1000 and o["delta_notional"] == 1000 assert o["target_notional"] == 1000 and o["delta_notional"] == 1000
assert abs(o["amount"] - 0.0156) < 1e-9 # 1000/64000=0.015625 -> 0.0156
def test_build_order_exit_is_reduce_only(): def test_build_order_exit_is_reduce_only():
o = build_rebalance_order("ETH-PERPETUAL", target_fraction=0.0, weight=0.5, o = build_rebalance_order(LIN, target_fraction=0.0, weight=0.5,
equity_usd=2000, current_pos_usd=1000.0) equity_usd=2000, current_pos_usd=1000.0, price=PX)
assert o["side"] == "sell" and o["reduce_only"] is True and o["amount"] == 1000 assert o["side"] == "sell" and o["reduce_only"] is True and o["amount"] > 0
def test_build_order_already_at_target_is_none(): def test_build_order_already_at_target_is_none():
o = build_rebalance_order("BTC-PERPETUAL", 1.0, 0.5, 2000, current_pos_usd=1000.0) o = build_rebalance_order(LIN, 1.0, 0.5, 2000, current_pos_usd=1000.0, price=PX)
assert o is None # delta 0 -> nessun ordine assert o is None # delta 0 -> nessun ordine
def test_build_order_subthreshold_is_none(): def test_build_order_subthreshold_is_none():
# delta $3 su BTC (< mezzo step $5) -> niente ordine # delta $2 (< mezzo step in notional, $3.2 a 64k) -> niente ordine
o = build_rebalance_order("BTC-PERPETUAL", 0.5015, 0.5, 2000, current_pos_usd=498.5) o = build_rebalance_order(LIN, 1.0, 0.5, 2000, current_pos_usd=998.0, price=PX)
assert o is None assert o is None
def test_partial_rebalance_direction(): def test_partial_rebalance_direction():
# target $1000, ho $600 -> compro $400; ho $1400 -> vendo $400 up = build_rebalance_order(LIN, 1.0, 0.5, 2000, 600.0, price=PX) # compra il delta
up = build_rebalance_order("BTC-PERPETUAL", 1.0, 0.5, 2000, 600.0) dn = build_rebalance_order(LIN, 1.0, 0.5, 2000, 1400.0, price=PX) # vende il delta
dn = build_rebalance_order("BTC-PERPETUAL", 1.0, 0.5, 2000, 1400.0) assert up["side"] == "buy" and up["delta_notional"] == 400
assert up["side"] == "buy" and up["amount"] == 400 assert dn["side"] == "sell" and dn["delta_notional"] == -400 and dn["reduce_only"] is False
assert dn["side"] == "sell" and dn["amount"] == 400 and dn["reduce_only"] is False
def test_parity_live_target_equals_backtest(): def test_parity_live_target_equals_backtest():
# il target live (current_target) DEVE essere l'ultimo della serie causale del backtest
from src.backtest.harness import load from src.backtest.harness import load
tp = TrendPortfolio(**CANONICAL) tp = TrendPortfolio(**CANONICAL)
df = resample_1d(load("BTC", "1h")) df = resample_1d(load("BTC", "1h"))