feat(reconcile): guard STALE_REAL_POSITION — rileva posizioni reali non gestite
Caso MR02_BTC 1h (2026-06-13): ritirato dallo swap a 15m mentre short reale -> short nudo (TP perso nel netting), reconciler cieco perche' lo status fermo contava ancora come libro. compute_stale_real_positions: worker con real_in_position e status.json fermo >15min = non gestito -> alert STALE_REAL_POSITION. Discriminante = staleness (venue-agnostico: cattura ritirati-da-swap/crashati). Gira dal cron host :40 (no rebuild). 3 test nuovi, suite 132 passed. Orfano chiuso a mano (testnet, +0.85 netto). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
@@ -20,6 +20,7 @@ Nessun ordine, nessuna modifica di stato: SOLO lettura.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
@@ -35,6 +36,8 @@ from src.live.books import real_books, account_net, expected_resting, PAPER
|
||||
|
||||
RECHECK_SLEEP = 10 # anti-race: secondi fra i due passaggi
|
||||
TOL_STEPS = 1.5 # tolleranza = 1.5 × step contratto
|
||||
STALE_REAL_MIN = 15 # un worker vivo aggiorna status.json ~ogni poll (60s);
|
||||
# real_in_position con mtime oltre questo = NON gestito
|
||||
|
||||
|
||||
def compute_drift(client: CerberoClient | None = None) -> list[dict]:
|
||||
@@ -111,10 +114,36 @@ def compute_resting_drift(client: CerberoClient | None = None) -> list[dict]:
|
||||
return rows
|
||||
|
||||
|
||||
def compute_stale_real_positions(max_age_min: int = STALE_REAL_MIN) -> list[dict]:
|
||||
"""Worker che dichiarano una posizione REALE ma il cui status.json e' fermo da
|
||||
oltre max_age_min minuti = posizione NON gestita da nessun runner (caso
|
||||
MR02_BTC 1h del 2026-06-12: ritirato dallo swap a 15m mentre short reale, con
|
||||
TP perso nel netting -> short nudo su disaster-SL). Il drift di compute_drift
|
||||
NON lo vede: lo status fermo conta ancora come 'libro' -> conto == libri.
|
||||
Discriminante robusto e venue-agnostico: la STALENESS (un worker vivo scrive
|
||||
a ogni poll), cattura ritirati-da-swap, crashati, worker rimossi dal config."""
|
||||
now = time.time()
|
||||
out: list[dict] = []
|
||||
for sp in sorted(PAPER.glob("*/status.json")):
|
||||
try:
|
||||
st = json.loads(sp.read_text())
|
||||
except Exception:
|
||||
continue
|
||||
if not st.get("real_in_position"):
|
||||
continue
|
||||
age_min = (now - sp.stat().st_mtime) / 60.0
|
||||
if age_min > max_age_min:
|
||||
out.append(dict(worker=sp.parent.name, age_min=round(age_min, 1),
|
||||
real_amount=st.get("real_amount") or st.get("real_amount_a"),
|
||||
real_side=st.get("real_side") or st.get("real_side_a", "")))
|
||||
return out
|
||||
|
||||
|
||||
def main():
|
||||
client = CerberoClient()
|
||||
rows = compute_drift(client)
|
||||
resting = compute_resting_drift(client)
|
||||
stale = compute_stale_real_positions()
|
||||
bad = [r for r in rows if not r["ok"]]
|
||||
bad_rest = [r for r in resting if r["status"] != "OK"]
|
||||
if bad or bad_rest:
|
||||
@@ -141,8 +170,25 @@ def main():
|
||||
if not resting:
|
||||
print("(nessun ordine resting atteso ne' in book)")
|
||||
|
||||
print("\nESITO:", "OK — conto allineato ai libri" if not (bad or bad_rest)
|
||||
else f"⚠️ DRIFT PERSISTENTE (pos={len(bad)} resting={len(bad_rest)})")
|
||||
print(f"\n{'worker stantio (pos. reale non gestita)':<45}{'amount':>10}{'eta_min':>9}")
|
||||
for r in stale:
|
||||
print(f"{r['worker']:<45}{(r['real_amount'] or 0):>10}{r['age_min']:>9.0f} ⚠️ STALE_REAL")
|
||||
if not stale:
|
||||
print("(nessuna posizione reale stantia)")
|
||||
|
||||
print("\nESITO:", "OK — conto allineato ai libri" if not (bad or bad_rest or stale)
|
||||
else f"⚠️ ANOMALIE (drift_pos={len(bad)} resting={len(bad_rest)} stale={len(stale)})")
|
||||
|
||||
if stale and "--telegram" in sys.argv:
|
||||
from src.live.telegram_notifier import notify_event
|
||||
notify_event("STALE_REAL_POSITION", {
|
||||
"worker": [{k: r.get(k) for k in ("worker", "real_amount", "real_side",
|
||||
"age_min")} for r in stale],
|
||||
"note": ("posizione REALE con status.json fermo da >%d min = worker non "
|
||||
"gestito (ritirato da uno swap di timeframe / crashato): la "
|
||||
"posizione e' nuda sul conto, flattare a mano. Caso MR02_BTC 1h "
|
||||
"del 2026-06-12." % STALE_REAL_MIN)})
|
||||
print("[telegram] alert STALE_REAL_POSITION inviato")
|
||||
|
||||
if (bad or bad_rest) and "--telegram" in sys.argv:
|
||||
from src.live.telegram_notifier import notify_event
|
||||
@@ -163,7 +209,7 @@ def main():
|
||||
"(caso MR02_BTC 2026-06-12); MISSING = atteso ma non in book; "
|
||||
"STALE = in book senza libro corrispondente")})
|
||||
print("[telegram] alert RESTING_DRIFT inviato")
|
||||
return bool(bad or bad_rest)
|
||||
return bool(bad or bad_rest or stale)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
Reference in New Issue
Block a user