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:
+33
-38
@@ -2,11 +2,11 @@
|
|||||||
|
|
||||||
Conto reale = USDC -> strumento ESEGUIBILE = perp LINEARE `BTC_USDC-PERPETUAL` (amount in BTC, step
|
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
|
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
|
Sicurezze: default DRY-RUN. Pre-flight ABORT se posizione preesistente. La chiusura (reduce_only,
|
||||||
BTC_USDC-PERPETUAL, amount <= 0.0002 BTC). Pre-flight: ABORT se esiste gia' una posizione. Apertura
|
sempre permessa) flatta comunque dopo l'apertura; verifica finale di FLAT (alert se no).
|
||||||
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 # DRY-RUN: nessun ordine inviato
|
||||||
uv run python scripts/live/microtest.py --live # invia il round-trip REALE
|
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]
|
PROJECT_ROOT = Path(__file__).resolve().parents[2]
|
||||||
sys.path.insert(0, str(PROJECT_ROOT))
|
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"
|
INSTRUMENT = "BTC_USDC-PERPETUAL"
|
||||||
AMOUNT = 0.0001 # base-coin (BTC) = 1 contratto minimo (~$6 a $63k)
|
AMOUNT = 0.0001 # base-coin (BTC) = 1 contratto minimo (~$6 a $63k)
|
||||||
@@ -32,12 +32,10 @@ def main():
|
|||||||
print("=" * 82)
|
print("=" * 82)
|
||||||
print(" MICRO-TEST esecuzione TP01 — round-trip 0.0001 BTC su BTC_USDC-PERPETUAL (leva ~0x)")
|
print(" MICRO-TEST esecuzione TP01 — round-trip 0.0001 BTC su BTC_USDC-PERPETUAL (leva ~0x)")
|
||||||
print("=" * 82)
|
print("=" * 82)
|
||||||
|
|
||||||
# ---- pre-flight (sola lettura) ----
|
|
||||||
try:
|
try:
|
||||||
equity = float(t.account_summary("USDC").get("equity") or 0)
|
equity = float(t.account_summary("USDC").get("equity") or 0)
|
||||||
mark = t.mark_price(INSTRUMENT)
|
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:
|
except Exception as e:
|
||||||
print(f" PRE-FLIGHT FALLITO (read): {type(e).__name__}: {e}\n -> non procedo.")
|
print(f" PRE-FLIGHT FALLITO (read): {type(e).__name__}: {e}\n -> non procedo.")
|
||||||
return
|
return
|
||||||
@@ -45,51 +43,48 @@ def main():
|
|||||||
notional = AMOUNT * mark
|
notional = AMOUNT * mark
|
||||||
print(f" conto USDC equity : ${equity:,.2f}")
|
print(f" conto USDC equity : ${equity:,.2f}")
|
||||||
print(f" mark {INSTRUMENT} : ${mark:,.1f}")
|
print(f" mark {INSTRUMENT} : ${mark:,.1f}")
|
||||||
print(f" posizione attuale : ${pos0:,.2f} notional (dev'essere 0)") # size lineare = USD notional
|
print(f" posizione attuale : ${pos0:,.2f} notional (dev'essere 0)")
|
||||||
print(f" ordine 1 (apertura): BUY {AMOUNT:.4f} BTC market (~${notional:.2f}, leva {notional/equity:.4f}x)")
|
print(f" 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" chiusura : SELL {AMOUNT:.4f} BTC market reduce_only")
|
||||||
print(f" guardrail : solo {INSTRUMENT}, cap {MAX_AMOUNT[INSTRUMENT]} BTC")
|
print(f" guardrail: solo {INSTRUMENT}, cap apertura {MAX_AMOUNT[INSTRUMENT]} BTC")
|
||||||
|
|
||||||
if abs(pos0) > 1e-9:
|
if abs(pos0) >= FLAT_USD:
|
||||||
print(f"\n ABORT: posizione preesistente ({pos0:.5f} BTC). Non la tocco. Chiudila a mano e ripeti.")
|
print(f"\n ABORT: posizione preesistente (${pos0:,.2f}). Non la tocco. Chiudila a mano e ripeti.")
|
||||||
return
|
return
|
||||||
|
|
||||||
if not live:
|
if not live:
|
||||||
print("\n DRY-RUN: nessun ordine inviato. Rilancia con --live per il round-trip reale.")
|
print("\n DRY-RUN: nessun ordine inviato. Rilancia con --live per il round-trip reale.")
|
||||||
return
|
return
|
||||||
|
|
||||||
# ---- LIVE: apertura ----
|
# ---- LIVE: apertura ----
|
||||||
print("\n >>> LIVE: invio APERTURA ...")
|
print("\n >>> LIVE: APERTURA ...")
|
||||||
open_resp = t.place_market(INSTRUMENT, "buy", AMOUNT, label="tp01-microtest-open")
|
fo = t.open(INSTRUMENT, "buy", AMOUNT, label="tp01-microtest-open")
|
||||||
if isinstance(open_resp, dict) and open_resp.get("error"):
|
if not fo.verified:
|
||||||
print(f" RIFIUTATO: {open_resp.get('error')} -> nessuna posizione. Stop.")
|
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
|
return
|
||||||
of = summarize_fill(open_resp)
|
print(f" FILL: {fo.filled:.4f} BTC @ ${fo.price:,.1f} fee {fo.fee_usdc:.6f} USDC (state={fo.state})")
|
||||||
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) ----
|
# ---- LIVE: chiusura (reduce_only) ----
|
||||||
print(" >>> LIVE: invio CHIUSURA (reduce_only) ...")
|
print(" >>> LIVE: CHIUSURA (reduce_only) ...")
|
||||||
close_resp = t.place_market(INSTRUMENT, "sell", AMOUNT, reduce_only=True, label="tp01-microtest-close")
|
fc = t.close(INSTRUMENT, label="tp01-microtest-close")
|
||||||
cf = summarize_fill(close_resp)
|
pos_end = t.position_usd(INSTRUMENT)
|
||||||
flat_ok, size_end = t.wait_until(INSTRUMENT, want_usd=0.0, tol=1e-9)
|
if fc:
|
||||||
if cf:
|
print(f" FILL: {fc.filled:.4f} BTC @ ${fc.price:,.1f} fee {fc.fee_usdc:.6f} USDC (state={fc.state})")
|
||||||
print(f" FILL chiusura: {cf['amount']:.4f} BTC @ ${cf['price']:,.1f} fee {cf['fee']:.6f} USDC")
|
print(f" posizione finale: ${pos_end:,.2f} notional")
|
||||||
print(f" posizione finale: ${size_end:,.2f} notional")
|
|
||||||
|
|
||||||
# ---- report ----
|
# ---- report ----
|
||||||
print("\n " + "-" * 62)
|
print("\n " + "-" * 62)
|
||||||
if flat_ok:
|
if abs(pos_end) < FLAT_USD:
|
||||||
print(" ✓ ROUND-TRIP COMPLETO — posizione tornata a FLAT.")
|
print(" ✓ ROUND-TRIP COMPLETO — posizione tornata a FLAT.")
|
||||||
else:
|
else:
|
||||||
print(f" ⚠️ ATTENZIONE: posizione NON flat (${size_end:,.2f}) — INTERVENTO MANUALE: chiudi a mano.")
|
print(f" ⚠️ posizione NON flat (${pos_end:,.2f}) — INTERVENTO MANUALE: chiudi a mano.")
|
||||||
if of and cf:
|
if fo.verified and fc:
|
||||||
tot_fee = of["fee"] + cf["fee"]
|
tot_fee = fo.fee_usdc + fc.fee_usdc
|
||||||
pnl = AMOUNT * (cf["price"] - of["price"]) # lineare USDC: pnl in USDC
|
pnl = AMOUNT * ((fc.price or 0) - (fo.price or 0))
|
||||||
print(f" entry ${of['price']:,.1f} -> exit ${cf['price']:,.1f} | fee totale {tot_fee:.6f} USDC | "
|
print(f" entry ${fo.price:,.1f} -> exit ${fc.price:,.1f} | fee {tot_fee:.6f} USDC | "
|
||||||
f"pnl lordo {pnl:+.4f} USDC | netto {pnl - tot_fee:+.4f} USDC")
|
f"pnl lordo {pnl:+.4f} | netto {pnl - tot_fee:+.4f} USDC")
|
||||||
print(" Validato: invio ordine reale, fill, fee reali, reconciliation, ritorno a flat.")
|
print(" Validato: invio ordine reale, fill, fee reali, reconciliation, ritorno a flat.")
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+18
-3
@@ -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>"""
|
||||||
|
|
||||||
|
|||||||
+31
-7
@@ -30,7 +30,8 @@ _CONTRACT = {
|
|||||||
"BTC_USDC-PERPETUAL": {"min": 0.0001, "step": 0.0001, "tick": 0.5, "settle": "USDC", "linear": True},
|
"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},
|
"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) -----------------------------
|
||||||
@@ -41,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)."""
|
||||||
@@ -58,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
|
||||||
@@ -141,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 [])
|
||||||
|
|||||||
+101
-48
@@ -1,73 +1,126 @@
|
|||||||
"""Esecuzione REALE su Deribit mainnet (via Cerbero MCP) — SOLO per il micro-test controllato.
|
"""Esecuzione REALE su Deribit mainnet (via Cerbero MCP) — entrata/uscita verificate.
|
||||||
|
|
||||||
Estende DeribitRead (sola lettura) coi metodi di trading MINIMI: market order, trade history (fee
|
Estende DeribitRead (sola lettura) coi metodi di trading, con la logica PROVATA dello stack pre-reset
|
||||||
reali), verifica posizione. GUARDRAIL HARD: solo BTC-PERPETUAL, notional <= MICRO_MAX_USD ($10), e
|
(Old/src/live/execution.py): entrata market verificata (state=='filled' + trade riscontrati, fill/fee
|
||||||
ogni open/close si verifica rileggendo la posizione. Nessun parametro di leva (su Deribit non e'
|
reali, filled_amount autorevole), uscita market reduce_only, disaster-bracket STOP_MARKET reduce_only.
|
||||||
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
|
GUARDRAIL: solo strumenti in ALLOWED; cap di size SOLO sulle APERTURE (MAX_AMOUNT). Le CHIUSURE si
|
||||||
altrove finche' il percorso live non e' validato + abilitato esplicitamente.
|
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 __future__ import annotations
|
||||||
|
|
||||||
import time
|
from dataclasses import dataclass
|
||||||
|
|
||||||
from src.live.deribit import DeribitRead, notional_to_amount
|
from src.live.deribit import DeribitRead, notional_to_amount, quantize_price
|
||||||
|
|
||||||
# Conto USDC -> perp LINEARE USDC: amount in base-coin (BTC), step 0.0001 (~$6 a $63k).
|
# Conto USDC -> perp LINEARE USDC (amount in base-coin). Cap micro-test: ~$13.
|
||||||
ALLOWED = {"BTC_USDC-PERPETUAL"} # solo questo strumento nel micro-test
|
ALLOWED = {"BTC_USDC-PERPETUAL", "ETH_USDC-PERPETUAL"}
|
||||||
MAX_AMOUNT = {"BTC_USDC-PERPETUAL": 0.0002} # cap hard ~$13: micro, leva ~0
|
MAX_AMOUNT = {"BTC_USDC-PERPETUAL": 0.0002, "ETH_USDC-PERPETUAL": 0.005}
|
||||||
|
FLAT_USD = 1.0 # |notional| < $1 = posizione considerata flat
|
||||||
|
|
||||||
|
|
||||||
class GuardrailError(RuntimeError):
|
class GuardrailError(RuntimeError):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
def summarize_fill(resp: dict) -> dict | None:
|
@dataclass
|
||||||
"""Riassume i trade di una risposta place_order: amount, prezzo medio ponderato, fee totale."""
|
class Fill:
|
||||||
trades = resp.get("trades", []) if isinstance(resp, dict) else []
|
"""Esito verificato di un ordine reale."""
|
||||||
if not trades:
|
instrument: str
|
||||||
return None
|
side: str
|
||||||
amt = sum(float(t.get("amount", 0) or 0) for t in trades)
|
amount: float # richiesto (base-coin)
|
||||||
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
|
filled: float # realmente fillato (order.filled_amount, autorevole)
|
||||||
fee = sum(float(t.get("fee", 0) or 0) for t in trades)
|
price: float | None # prezzo medio di fill
|
||||||
return dict(amount=amt, price=px, fee=fee, n=len(trades))
|
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):
|
class DeribitTrader(DeribitRead):
|
||||||
"""SOLA capacita' di trading consentita: market order entro i guardrail, + verifica. Niente altro."""
|
"""Trading minimo e verificato. Apre/chiude solo entro i guardrail; le chiusure sempre."""
|
||||||
|
|
||||||
def _check(self, instrument: str, amount: float) -> None:
|
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:
|
if instrument not in ALLOWED:
|
||||||
raise GuardrailError(f"strumento non consentito nel micro-test: {instrument}")
|
raise GuardrailError(f"strumento non consentito: {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"):
|
if side not in ("buy", "sell"):
|
||||||
raise GuardrailError(f"side non valido: {side}")
|
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,
|
payload = {"instrument_name": instrument, "side": side, "amount": amount,
|
||||||
"type": "market", "label": label}
|
"type": order_type, "label": label}
|
||||||
|
if price is not None:
|
||||||
|
payload["price"] = price
|
||||||
if reduce_only:
|
if reduce_only:
|
||||||
payload["reduce_only"] = True
|
payload["reduce_only"] = True
|
||||||
return self._unwrap(self._post("/mcp-deribit/tools/place_order", payload)) or {}
|
resp = self._unwrap(self._post("/mcp-deribit/tools/place_order", payload)) or {}
|
||||||
|
|
||||||
def trade_history(self, instrument: str, limit: int = 20) -> list[dict]:
|
if not isinstance(resp, dict) or resp.get("error") or resp.get("state") == "error":
|
||||||
out = self._unwrap(self._post("/mcp-deribit/tools/get_trade_history",
|
err = resp.get("error") if isinstance(resp, dict) else resp
|
||||||
{"limit": limit, "instrument_name": instrument}))
|
return Fill(instrument, side, amount, 0.0, None, 0.0, None, "error", False,
|
||||||
return out if isinstance(out, list) else (out.get("trades", []) if isinstance(out, dict) else [])
|
notes=f"place_order error: {err}")
|
||||||
|
|
||||||
def wait_until(self, instrument: str, want_usd: float, tol: float = 1.0,
|
order = resp.get("order", resp) or {}
|
||||||
polls: int = 6, sleep: float = 0.6) -> tuple[bool, float]:
|
trades = resp.get("trades", []) or []
|
||||||
"""Poll get_positions finche' la size si avvicina a want_usd (tol). Ritorna (ok, size_letta)."""
|
order_id = order.get("order_id")
|
||||||
size = self.position_usd(instrument)
|
state = order.get("order_state")
|
||||||
for _ in range(polls):
|
price_f = _avg_price(order, trades)
|
||||||
if abs(size - want_usd) <= tol:
|
fee_usdc = sum(float(t.get("fee", 0) or 0) for t in trades) # lineare USDC: fee gia' in USDC
|
||||||
return True, size
|
filled = float(order.get("filled_amount") or 0) or sum(float(t.get("amount", 0) or 0) for t in trades)
|
||||||
time.sleep(sleep)
|
|
||||||
size = self.position_usd(instrument)
|
if order_type == "market":
|
||||||
return abs(size - want_usd) <= tol, size
|
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
@@ -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
@@ -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"))
|
||||||
|
|||||||
Reference in New Issue
Block a user