fix(exec): code-review serale — guard anti-posizione-nuda sul netting + verità per-frazione

7 finder paralleli sul diff della giornata (8adf388..HEAD), fix dei confermati:

CRITICI (money-path):
- close_amount: GUARD stato-stantio sul fallback netting — il residuo
  non-reduce-only e' consentito solo fino al gap (conto reale - libri degli
  altri worker - orfani) nella direzione della chiusura (src/live/books.py =
  fonte unica, usata anche dal reconciler). Senza guard, un close su stato
  stantio (DSL scattato in outage, flatten manuale) APRIVA una posizione nuda
  a taglia piena bookata come 'chiusura verificata'. Fail-safe se il gap non
  e' calcolabile. Check polvere PRIMA di _quantize_step (che clampa al lotto
  minimo: un residuo 1e-17 diventava un ordine nudo da un lotto).
- _real_close: market_amt = filled_amount anche a merged verified=False (i
  contratti chiusi dal reduce-only non si buttano se il leg netting fallisce);
  REAL_CLOSE_PARTIAL non piu' gateato su verified (era soppresso proprio nel
  caso parziale reale).
- pairs: verita' per-FRAZIONE di gamba (gross proporzionale al fillato, orfano
  = solo il residuo — prima falsava reconciler e real_capital della parte gia'
  chiusa); REAL_OPEN_PAIR booka filled_amount; docstring applied corretta.
- open_pair unwind: chiude il FILLATO, non il richiesto (senza il cap silenzioso
  del reduce-only avrebbe mangiato quota altrui).
- place_tp_limit: quantize CONSERVATIVO (sell=floor/buy=ceil) — il rounding al
  tick piu' vicino poteva mettere il resting oltre il TP sim -> tocco genuino
  classificato phantom sistematicamente.

ROBUSTEZZA/OSSERVABILITA':
- runner: WORKER_ERROR_STREAK a 5 e poi ogni 50 poll + recovery RIPRESO +
  flag real_in_position nell'alert (prima: one-shot a n==5, poi silenzio).
- _tp_phantom: TTL 120s sul verdetto (era ~50 HTTP/h per worker a barra
  fantasma); merge notes con entrambi gli order_id (audit-trail).
- reset_flatten: _quantize_step Decimal (round float produceva amount che
  Deribit rifiuta); hourly_report: book XS01 con gambe SHORT visibili (abs).
- validate_xsec_worker: POS/LEV importati (non hardcoded); xs01_tranche:
  regression-lock ESEGUITO vs xsec_sim; reconcile su src/live/books;
  drift_monitor: rolling vettoriale + exit code 1 su warn.

Test: +4 guard/dust, fixture filled_amount -> 114 passed.
Deferiti (TODO): resting esposti al netting, lifecycle orphan_legs, finestra
trade-history TP_PHANTOM, validazione feed a monte, dedup minori.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Adriano Dal Pastro
2026-06-11 21:36:30 +00:00
parent 3f1feb1a6f
commit 82c05f6f81
15 changed files with 321 additions and 96 deletions
+6 -2
View File
@@ -55,7 +55,9 @@ def drift_rows():
rows = []
for name, r in family_returns().items():
for win in WINDOWS:
roll = (1 + r).rolling(win).apply(np.prod, raw=True) - 1
# vettoriale (log1p+rolling sum) invece di apply(np.prod): identico
# numericamente, ~100x piu' veloce del callback Python per-finestra
roll = np.expm1(np.log1p(r).rolling(win).sum())
roll = roll.dropna()
if len(roll) < 100:
continue
@@ -99,4 +101,6 @@ def main():
if __name__ == "__main__":
main()
# exit code 1 su warn: utilizzabile da cron/script come canale d'allarme
# (coerente con reconcile_account; prima il bool era calcolato e buttato via)
sys.exit(1 if main() else 0)
+6 -53
View File
@@ -20,7 +20,6 @@ Nessun ordine, nessuna modifica di stato: SOLO lettura.
"""
from __future__ import annotations
import json
import sys
import time
from pathlib import Path
@@ -30,63 +29,17 @@ sys.path.insert(0, str(PROJECT_ROOT))
from src.live.cerbero_client import CerberoClient
from src.live.execution import contract_spec
from src.live.books import real_books, account_net # fonte UNICA dei libri (usata
# anche dal guard del netting)
PAPER = PROJECT_ROOT / "data" / "portfolio_paper"
RECHECK_SLEEP = 10 # anti-race: secondi fra i due passaggi
TOL_STEPS = 1.5 # tolleranza = 1.5 × step contratto
def _inst(asset: str) -> str:
return f"{asset}_USDC-PERPETUAL"
def expected_books() -> tuple[dict[str, float], dict[str, float]]:
"""(atteso per strumento dai libri, quota orfana registrata per strumento).
Amount firmato in base-coin: buy=+, sell=-."""
books: dict[str, float] = {}
orphans: dict[str, float] = {}
for sp in sorted(PAPER.glob("*/status.json")):
st = json.loads(sp.read_text())
wid = sp.parent.name
parts = wid.split("__")
if st.get("real_in_position"):
if "real_amount_a" in st and st.get("real_amount_a"):
# pairs: asset da worker_id (…__ETH_BTC__1h)
a, b = parts[1].split("_")
for asset, side, amt in ((a, st["real_side_a"], st["real_amount_a"]),
(b, st["real_side_b"], st["real_amount_b"])):
sgn = 1 if side == "buy" else -1
books[_inst(asset)] = books.get(_inst(asset), 0.0) + sgn * amt
elif st.get("real_amount"):
# single-leg: fade/DIP01/SH01
sgn = 1 if st.get("real_side") == "buy" else -1
books[_inst(parts[1])] = books.get(_inst(parts[1]), 0.0) + sgn * st["real_amount"]
for o in st.get("orphan_legs", []):
# gamba che il libro ha chiuso ma il conto ha ancora (entry_side = verso
# in cui la posizione e' rimasta aperta sul conto)
sgn = 1 if o.get("entry_side") == "buy" else -1
orphans[o["instrument"]] = orphans.get(o["instrument"], 0.0) + sgn * float(o["amount"])
return books, orphans
def account_positions(client: CerberoClient) -> dict[str, float]:
"""Posizioni reali per strumento, amount firmato in base-coin."""
out: dict[str, float] = {}
for p in client.get_positions(currency="USDC") or []:
inst = p.get("instrument")
size = float(p.get("size") or 0)
mark = float(p.get("mark_price") or 0)
if not inst or not size or not mark:
continue
amt = size / mark
out[inst] = amt if p.get("direction") == "long" else -amt
return out
def compute_drift() -> list[dict]:
client = CerberoClient()
books, orphans = expected_books()
acct = account_positions(client)
def compute_drift(client: CerberoClient | None = None) -> list[dict]:
client = client or CerberoClient()
books, orphans = real_books()
acct = account_net(client)
rows = []
for inst in sorted(set(books) | set(orphans) | set(acct)):
exp = books.get(inst, 0.0) + orphans.get(inst, 0.0)
+5 -1
View File
@@ -44,7 +44,11 @@ def main():
step = contract_spec(inst)["step"]
entry_side = "buy" if p["direction"] == "long" else "sell"
units = size_usd / mark if mark else 0
amount = round(units / step) * step
# _quantize_step (Decimal): round(units/step)*step in float binario
# produce artefatti (0.07200000000000001) che Deribit rifiuta con
# 'Invalid params' — il bug e' documentato in execution.py
from src.live.execution import _quantize_step
amount = _quantize_step(units, step, contract_spec(inst)["min"]) if units >= step / 2 else 0.0
if amount <= 0:
print(f" {inst}: residuo {size_usd:.2f} USD sotto mezzo step, ok")
continue
+5 -2
View File
@@ -58,8 +58,11 @@ def main():
print(f" ESITO: {'OK (replay == backtest)' if ok1 else 'DIFF -> INDAGARE'}")
# [2] K=3 (tranching live): parita' con l'unione delle fasi 0,4,8 (gate
# xs01_tranche_gate) — capitale comune, PnL/K per trade in ordine di exit
# xs01_tranche_gate) — capitale comune, PnL/K per trade in ordine di exit.
# POS/LEV importati dal modulo canonico, NON hardcoded: una costante stantia
# qui farebbe passare la validazione contro un sistema diverso (code-review)
from scripts.analysis.xs01_tranche_research import xsec_trades
from scripts.strategies.XS01_cross_sectional import POS, LEV
K = 3
w3 = _replay(M, dfs, {"lb": LB, "hold": HOLD, "tranches": K})
step = HOLD // K
@@ -67,7 +70,7 @@ def main():
key=lambda t: t[1])
cap = 1000.0
for _, _, net in allt:
cap = max(cap + cap * 0.15 * 3.0 * net / K, 10.0)
cap = max(cap + cap * POS * LEV * net / K, 10.0)
cap_ok3 = abs(w3.capital - cap) / cap < 0.02
trd_ok3 = abs(w3.total_trades - len(allt)) <= max(2, len(allt) * 0.02)
print(f"\n [K=3] {'':<6}{'cap':>14}{'trades':>8}")
+22
View File
@@ -102,6 +102,27 @@ def combined_metrics(branches, ts, yrs_span):
sharpe=sharpe, dd=float(((pk - eq) / pk).max() * 100))
def regression_lock(M=None):
"""xsec_trades(phase=0) DEVE riprodurre xsec_sim (n trade e ret totale):
la copia e' load-bearing (la usano gate e validate_xsec_worker) — senza
lock eseguito un fix all'engine canonico non si propagherebbe e la
validazione live certificherebbe un engine stantio (code-review 2026-06-11)."""
from scripts.strategies.XS01_cross_sectional import xsec_sim
if M is None:
M = aligned_panel()
ts = pd.to_datetime(M.index, unit="ms", utc=True)
tr = xsec_trades(phase=0, M=M)
eq = equity_from(tr, ts)
ref = xsec_sim()
n_ok = len(tr) == ref["trades"]
ret = (eq.iloc[-1] / 1000 - 1) * 100 if len(eq) else 0.0
ret_ok = abs(ret - ref["ret"]) < 1e-6 * max(1.0, abs(ref["ret"]))
if not (n_ok and ret_ok):
raise AssertionError(f"REGRESSION-LOCK FALLITO: trades {len(tr)} vs {ref['trades']}, "
f"ret {ret:.6f} vs {ref['ret']:.6f}")
print(f" regression-lock OK: {len(tr)} trade, ret {ret:+.2f}% == xsec_sim")
def run():
M = aligned_panel()
ts = pd.to_datetime(M.index, unit="ms", utc=True)
@@ -109,6 +130,7 @@ def run():
print("=" * 96)
print(" XS01 phase-tranching — sensibilita' di fase + ensemble K=2/3 | griglia pre-registrata")
print("=" * 96)
regression_lock(M)
for tag, split in (("FULL", 0.0), ("OOS", 1 - OOS_FRAC)):
yrs_span = (ts[-1] - ts[max(int(n * split), LB)]).days / 365.25 or 1
rows = []