feat(exec): gate TP_PHANTOM — il tocco TP va confermato dal book reale, non dal feed
Il feed testnet stampa wick che 'toccano' il TP intrabar senza che il prezzo abbia mai scambiato al livello: il sim bookava +4% fantasma a bars_held=0 e _real_close chiudeva A MERCATO una posizione col resting TP a zero fill (-fee/spread a giro, 14 giri l'11-06). Ora StrategyWorker._tp_phantom sopprime l'exit take_profit quando: tocco sim + resting LIMIT zero-fill + prezzo corrente che non ha raggiunto il livello (il limit sul book reale e' l'oracolo del tocco). Zero parametri (verita' d'esecuzione, non filtro di strategia); SL close-confirm e max_bars restano attivi nello stesso tick; fill parziale/prezzo oltre il livello/worker non eseguito/errore rete -> comportamento storico. Log TP_PHANTOM dedup per barra + alert Telegram una tantum. 5 test nuovi (104 passed). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
@@ -451,6 +451,18 @@ queste fade, ma va confermato col paper trader live prima di rischiare capitale
|
|||||||
di parità della stessa tornata (v1.1.3): TR01 fee×leva + forming-bar TR01/Pairs + WARN
|
di parità della stessa tornata (v1.1.3): TR01 fee×leva + forming-bar TR01/Pairs + WARN
|
||||||
`PANEL_SHORT` su TSM01/ROT02; `hourly_report` ora mostra i multi-asset (sezione MULTI-ASSET).
|
`PANEL_SHORT` su TSM01/ROT02; `hourly_report` ora mostra i multi-asset (sezione MULTI-ASSET).
|
||||||
Diario `docs/diary/2026-06-07-sweep-fixes.md`.
|
Diario `docs/diary/2026-06-07-sweep-fixes.md`.
|
||||||
|
- **TP_PHANTOM — il tocco TP va confermato dal book reale (v1.1.23, 2026-06-11).** Il feed
|
||||||
|
testnet stampa wick anomali che (a) generano segnali fade su ETH e (b) "toccano" il TP
|
||||||
|
intrabar della stessa barra: il sim bookava +4% fantasma a bars_held=0 e `_real_close`
|
||||||
|
chiudeva A MERCATO una posizione il cui resting TP non aveva mai fillato (−fee/spread a
|
||||||
|
giro, 14 giri l'11-06, report Telegram 26/0 vs reale 11/15 — fix conteggio in v1.1.22).
|
||||||
|
Gate in `StrategyWorker._tp_phantom` (zero parametri, verita' d'esecuzione, NON un filtro
|
||||||
|
di strategia): tocco sim + **resting LIMIT a zero fill** + prezzo corrente che non ha
|
||||||
|
raggiunto il livello → exit SOPPRESSA (il limit sul book reale e' l'oracolo: se il prezzo
|
||||||
|
avesse scambiato li', avrebbe fillato); SL close-confirm e max_bars restano attivi.
|
||||||
|
Fill (anche parziale) o prezzo oltre il livello o worker non eseguito → comportamento
|
||||||
|
storico. Fail-open su errori di rete. Log `TP_PHANTOM` dedup per barra + alert Telegram.
|
||||||
|
Test `tests/portfolio/test_tp_phantom.py`.
|
||||||
- **TP reale = LIMIT reduce-only AL LIVELLO (2026-06-04).** Misurati +235 bps di slippage medio sulle uscite take-profit market-on-poll (sim esce al livello intrabar, il reale chiudeva al poll post-rimbalzo: sim +11.85 vs reale +0.62 USD sui primi 7 close). Fix: a ogni `REAL_OPEN` il worker piazza un **limit reduce-only al TP** (`ExecutionClient.place_tp_limit`, prezzo quantizzato al tick, SOLA quota del worker) → `REAL_TP_RESTING`; a ogni chiusura sim `_real_close` **cancella il resting → riconcilia i fill (anche parziali) via `get_trade_history` per order_id → market reduce-only solo del residuo** → ledger su prezzo combinato. `real_tp_order_id` persistito in `status.json` (resume-safe). Lo **SL resta market-on-poll** (deliberato: i trigger Deribit generano un nuovo order_id al trigger → fill non verificabile per order_id; e sul SL il rimbalzo lavora a favore). Fill da resting = fee **maker ~0%**. Smoke: `live_shadow_smoke.py` (2 scenari, testnet). Diario `docs/diary/2026-06-04-shadow-divergence.md`.
|
- **TP reale = LIMIT reduce-only AL LIVELLO (2026-06-04).** Misurati +235 bps di slippage medio sulle uscite take-profit market-on-poll (sim esce al livello intrabar, il reale chiudeva al poll post-rimbalzo: sim +11.85 vs reale +0.62 USD sui primi 7 close). Fix: a ogni `REAL_OPEN` il worker piazza un **limit reduce-only al TP** (`ExecutionClient.place_tp_limit`, prezzo quantizzato al tick, SOLA quota del worker) → `REAL_TP_RESTING`; a ogni chiusura sim `_real_close` **cancella il resting → riconcilia i fill (anche parziali) via `get_trade_history` per order_id → market reduce-only solo del residuo** → ledger su prezzo combinato. `real_tp_order_id` persistito in `status.json` (resume-safe). Lo **SL resta market-on-poll** (deliberato: i trigger Deribit generano un nuovo order_id al trigger → fill non verificabile per order_id; e sul SL il rimbalzo lavora a favore). Fill da resting = fee **maker ~0%**. Smoke: `live_shadow_smoke.py` (2 scenari, testnet). Diario `docs/diary/2026-06-04-shadow-divergence.md`.
|
||||||
- **position_size per-famiglia (2026-06-07).** `portfolios.yml` accetta `position_size_family`
|
- **position_size per-famiglia (2026-06-07).** `portfolios.yml` accetta `position_size_family`
|
||||||
(chiave = `weighting.family_of`); plumbing `runner.pos_for_spec`. **PAIRS a 0.20** (esposizione
|
(chiave = `weighting.family_of`); plumbing `runner.pos_for_spec`. **PAIRS a 0.20** (esposizione
|
||||||
|
|||||||
+6
-5
@@ -71,11 +71,12 @@
|
|||||||
z-score estremo) e (b) "toccano" il TP intrabar della stessa barra → il sim booka
|
z-score estremo) e (b) "toccano" il TP intrabar della stessa barra → il sim booka
|
||||||
+4% fantasma a bars_held=0, il reale apre+chiude pagando solo fee/spread (~−0.17€
|
+4% fantasma a bars_held=0, il reale apre+chiude pagando solo fee/spread (~−0.17€
|
||||||
a giro, 14 giri oggi ≈ −2.3€). Il real-truth ledger contabilizza GIUSTO (per questo
|
a giro, 14 giri oggi ≈ −2.3€). Il real-truth ledger contabilizza GIUSTO (per questo
|
||||||
esiste) e il report orario ora conta i win dal flag reale. NON aggiungere filtri
|
esiste) e il report orario ora conta i win dal flag reale. MITIGATO in v1.1.23:
|
||||||
anti-spike ai segnali (= fit su un artefatto del testnet, divergenza dal backtest);
|
gate `TP_PHANTOM` (il tocco TP deve essere confermato dal fill del resting sul book
|
||||||
su feed mainnet il fenomeno non esiste. Osservare la frequenza: se il churn cresce,
|
reale, o dal prezzo oltre il livello) → niente più chiusure a mercato su wick
|
||||||
valutare un gate di QUALITÀ FEED a monte (validazione barre nel data layer, non
|
fantasma. Resta l'ENTRY spike-driven (il segnale stesso nasce dal wick): NON
|
||||||
nella strategia).
|
filtrarlo nei segnali (= fit su artefatto testnet); osservare la frequenza dei log
|
||||||
|
TP_PHANTOM — se cresce, valutare un gate di QUALITÀ FEED nel data layer.
|
||||||
|
|
||||||
- [ ] **FADE in coda storica (2026-06-11)**: il rolling 120g equal-weight delle 6 fade è al
|
- [ ] **FADE in coda storica (2026-06-11)**: il rolling 120g equal-weight delle 6 fade è al
|
||||||
**2° percentile** della propria storia (−1.0% vs p5 +0.4%); il PORT06 complessivo resta
|
**2° percentile** della propria storia (−1.0% vs p5 +0.4%); il PORT06 complessivo resta
|
||||||
|
|||||||
@@ -71,6 +71,8 @@ class StrategyWorker:
|
|||||||
self.real_dsl_order_id = "" # STOP_MARKET disaster bracket on-book (persistito)
|
self.real_dsl_order_id = "" # STOP_MARKET disaster bracket on-book (persistito)
|
||||||
self.real_trades = 0
|
self.real_trades = 0
|
||||||
self.real_first_notified = False # alert Telegram "esecuzione viva" una tantum
|
self.real_first_notified = False # alert Telegram "esecuzione viva" una tantum
|
||||||
|
self._tp_phantom_ts = 0 # dedup log TP_PHANTOM per barra (non persistito)
|
||||||
|
self._tp_phantom_notified = False # alert Telegram una tantum per processo
|
||||||
|
|
||||||
self.worker_id = f"{strategy.name}__{asset}__{tf}"
|
self.worker_id = f"{strategy.name}__{asset}__{tf}"
|
||||||
self.work_dir = data_dir / self.worker_id
|
self.work_dir = data_dir / self.worker_id
|
||||||
@@ -448,6 +450,41 @@ class StrategyWorker:
|
|||||||
# applied: fill reali presenti (parts) o chiusura comunque verificata
|
# applied: fill reali presenti (parts) o chiusura comunque verificata
|
||||||
return real_pnl, bool(parts) or verified
|
return real_pnl, bool(parts) or verified
|
||||||
|
|
||||||
|
def _tp_phantom(self, current_price: float, current_ts: int) -> bool:
|
||||||
|
"""TP "toccato" solo nel feed? Il LIMIT resting sul book REALE e' l'oracolo:
|
||||||
|
se il prezzo avesse davvero scambiato al livello si sarebbe fillato (almeno
|
||||||
|
in parte). Tocco sim + resting a zero fill + prezzo corrente che NON ha
|
||||||
|
raggiunto il TP = spike-print del feed (testnet, 2026-06-11: 14 giri fantasma
|
||||||
|
su ETH, sim +4% l'uno, reale −fee/spread l'uno) → exit SOPPRESSA, la posizione
|
||||||
|
continua il suo ciclo normale (SL close-confirm e max_bars restano attivi).
|
||||||
|
Zero parametri: e' un check di verita' d'esecuzione, non un filtro di
|
||||||
|
strategia; sui worker senza esecuzione reale ritorna False (parita' storica).
|
||||||
|
Fail-open: se la query fill fallisce (rete) si chiude come prima."""
|
||||||
|
if not (self.execution_enabled and self.real_in_position
|
||||||
|
and self.real_tp_order_id and self.tp):
|
||||||
|
return False
|
||||||
|
# prezzo gia' oltre il livello → tocco genuino anche senza fill (gap fra poll)
|
||||||
|
if (self.direction == 1 and current_price >= self.tp) or \
|
||||||
|
(self.direction == -1 and current_price <= self.tp):
|
||||||
|
return False
|
||||||
|
try:
|
||||||
|
tp_amt, _, _ = self.executor.resting_fills(self.exec_instrument,
|
||||||
|
self.real_tp_order_id)
|
||||||
|
except Exception:
|
||||||
|
return False
|
||||||
|
if tp_amt > 0:
|
||||||
|
return False
|
||||||
|
if current_ts != self._tp_phantom_ts:
|
||||||
|
self._tp_phantom_ts = current_ts
|
||||||
|
data = {"tp": self.tp, "price": current_price, "direction": self.direction,
|
||||||
|
"tp_order_id": self.real_tp_order_id,
|
||||||
|
"note": "wick solo nel feed (resting zero-fill, prezzo lontano dal livello) -> exit soppressa"}
|
||||||
|
self._log("TP_PHANTOM", data)
|
||||||
|
if not self._tp_phantom_notified:
|
||||||
|
self._tp_phantom_notified = True
|
||||||
|
self._notify("TP_PHANTOM", data)
|
||||||
|
return True
|
||||||
|
|
||||||
def _close_position(self, current_price: float, reason: str):
|
def _close_position(self, current_price: float, reason: str):
|
||||||
if not self.in_position:
|
if not self.in_position:
|
||||||
return
|
return
|
||||||
@@ -549,14 +586,14 @@ class StrategyWorker:
|
|||||||
if not np.isfinite(buf):
|
if not np.isfinite(buf):
|
||||||
buf = 0.0
|
buf = 0.0
|
||||||
if self.direction == 1:
|
if self.direction == 1:
|
||||||
if bar_high >= self.tp:
|
if bar_high >= self.tp and not self._tp_phantom(current_price, current_ts):
|
||||||
self._close_position(self.tp, "take_profit")
|
self._close_position(self.tp, "take_profit")
|
||||||
elif confirm_close < self.sl - buf:
|
elif confirm_close < self.sl - buf:
|
||||||
self._close_position(current_price, "stop_loss")
|
self._close_position(current_price, "stop_loss")
|
||||||
elif self.max_bars and self.bars_held >= self.max_bars:
|
elif self.max_bars and self.bars_held >= self.max_bars:
|
||||||
self._close_position(current_price, "time_limit")
|
self._close_position(current_price, "time_limit")
|
||||||
else:
|
else:
|
||||||
if bar_low <= self.tp:
|
if bar_low <= self.tp and not self._tp_phantom(current_price, current_ts):
|
||||||
self._close_position(self.tp, "take_profit")
|
self._close_position(self.tp, "take_profit")
|
||||||
elif confirm_close > self.sl + buf:
|
elif confirm_close > self.sl + buf:
|
||||||
self._close_position(current_price, "stop_loss")
|
self._close_position(current_price, "stop_loss")
|
||||||
@@ -568,14 +605,14 @@ class StrategyWorker:
|
|||||||
if self.direction == 1:
|
if self.direction == 1:
|
||||||
if bar_low <= self.sl:
|
if bar_low <= self.sl:
|
||||||
self._close_position(self.sl, "stop_loss")
|
self._close_position(self.sl, "stop_loss")
|
||||||
elif bar_high >= self.tp:
|
elif bar_high >= self.tp and not self._tp_phantom(current_price, current_ts):
|
||||||
self._close_position(self.tp, "take_profit")
|
self._close_position(self.tp, "take_profit")
|
||||||
elif self.max_bars and self.bars_held >= self.max_bars:
|
elif self.max_bars and self.bars_held >= self.max_bars:
|
||||||
self._close_position(current_price, "time_limit")
|
self._close_position(current_price, "time_limit")
|
||||||
else:
|
else:
|
||||||
if bar_high >= self.sl:
|
if bar_high >= self.sl:
|
||||||
self._close_position(self.sl, "stop_loss")
|
self._close_position(self.sl, "stop_loss")
|
||||||
elif bar_low <= self.tp:
|
elif bar_low <= self.tp and not self._tp_phantom(current_price, current_ts):
|
||||||
self._close_position(self.tp, "take_profit")
|
self._close_position(self.tp, "take_profit")
|
||||||
elif self.max_bars and self.bars_held >= self.max_bars:
|
elif self.max_bars and self.bars_held >= self.max_bars:
|
||||||
self._close_position(current_price, "time_limit")
|
self._close_position(current_price, "time_limit")
|
||||||
|
|||||||
@@ -0,0 +1,104 @@
|
|||||||
|
"""TP_PHANTOM (2026-06-11): il tocco TP che esiste solo nel feed (spike-print testnet)
|
||||||
|
NON deve chiudere — il LIMIT resting sul book reale e' l'oracolo: zero fill + prezzo
|
||||||
|
lontano dal livello = wick fantasma -> exit soppressa. Con fill reale (anche parziale),
|
||||||
|
o prezzo realmente oltre il livello, o worker senza esecuzione -> comportamento storico."""
|
||||||
|
import pandas as pd
|
||||||
|
|
||||||
|
from src.live.strategy_worker import StrategyWorker
|
||||||
|
from src.live.strategy_loader import load_strategy
|
||||||
|
|
||||||
|
|
||||||
|
def _df(last_high, last_low, n=120, price=100.0):
|
||||||
|
c = [price] * n
|
||||||
|
h = [price] * n
|
||||||
|
l = [price] * n
|
||||||
|
h[-1] = last_high
|
||||||
|
l[-1] = last_low
|
||||||
|
ts = (pd.date_range("2024-01-01", periods=n, freq="1h", tz="UTC").astype("int64") // 10**6)
|
||||||
|
return pd.DataFrame({"timestamp": ts, "open": c, "high": h, "low": l, "close": c, "volume": 1.0})
|
||||||
|
|
||||||
|
|
||||||
|
class _FakeExecutor:
|
||||||
|
"""Solo cio' che serve al gate + alla _real_close di un eventuale exit."""
|
||||||
|
def __init__(self, tp_filled_amount=0.0):
|
||||||
|
self.tp_filled_amount = tp_filled_amount
|
||||||
|
self.verify_polls = 1
|
||||||
|
self.verify_sleep = 0.0
|
||||||
|
|
||||||
|
def resting_fills(self, instrument, order_id):
|
||||||
|
return self.tp_filled_amount, 102.0 if self.tp_filled_amount else None, 0.0
|
||||||
|
|
||||||
|
def cancel_order(self, order_id):
|
||||||
|
return {"state": "cancelled"}
|
||||||
|
|
||||||
|
def close_amount(self, instrument, side, amount, label=""):
|
||||||
|
class F:
|
||||||
|
verified = True
|
||||||
|
amount = 0.01
|
||||||
|
fill_price = 100.0
|
||||||
|
fee_usd = 0.01
|
||||||
|
order_id = "X"
|
||||||
|
return F()
|
||||||
|
|
||||||
|
|
||||||
|
def _long_worker(tmp, executor=None):
|
||||||
|
w = StrategyWorker(strategy=load_strategy("MR01_bollinger_fade"), asset="BTC", tf="1h",
|
||||||
|
capital=1000.0, data_dir=tmp,
|
||||||
|
executor=executor,
|
||||||
|
exec_instrument="BTC_USDC-PERPETUAL" if executor else None)
|
||||||
|
w._notify = lambda *a, **k: None
|
||||||
|
w.in_position = True
|
||||||
|
w.direction = 1
|
||||||
|
w.entry_price = 100.0
|
||||||
|
w.tp = 102.0
|
||||||
|
w.sl = 98.0
|
||||||
|
w.max_bars = 24
|
||||||
|
w.bars_held = 1
|
||||||
|
w.last_bar_ts = 0
|
||||||
|
if executor:
|
||||||
|
w.real_in_position = True
|
||||||
|
w.real_side = "buy"
|
||||||
|
w.real_amount = 0.01
|
||||||
|
w.real_entry_price = 100.0
|
||||||
|
w.real_entry_notional = 1.0
|
||||||
|
w.real_tp_order_id = "TP-1"
|
||||||
|
return w
|
||||||
|
|
||||||
|
|
||||||
|
def test_phantom_touch_suppressed(tmp_path):
|
||||||
|
# wick a 102.5 nel feed, resting zero-fill, close 100 lontano dal TP -> NON chiude
|
||||||
|
w = _long_worker(tmp_path, executor=_FakeExecutor(tp_filled_amount=0.0))
|
||||||
|
w.tick(_df(last_high=102.5, last_low=99.5))
|
||||||
|
assert w.in_position
|
||||||
|
assert w.real_in_position
|
||||||
|
|
||||||
|
|
||||||
|
def test_real_fill_closes(tmp_path):
|
||||||
|
# stesso wick ma il resting HA fillato -> tocco reale -> chiude
|
||||||
|
w = _long_worker(tmp_path, executor=_FakeExecutor(tp_filled_amount=0.01))
|
||||||
|
w.tick(_df(last_high=102.5, last_low=99.5))
|
||||||
|
assert not w.in_position
|
||||||
|
|
||||||
|
|
||||||
|
def test_price_beyond_tp_closes_without_fill(tmp_path):
|
||||||
|
# close corrente OLTRE il TP (gap fra poll): tocco genuino anche a zero fill
|
||||||
|
w = _long_worker(tmp_path, executor=_FakeExecutor(tp_filled_amount=0.0))
|
||||||
|
df = _df(last_high=103.0, last_low=99.5)
|
||||||
|
df.loc[df.index[-1], "close"] = 102.6
|
||||||
|
w.tick(df)
|
||||||
|
assert not w.in_position
|
||||||
|
|
||||||
|
|
||||||
|
def test_no_executor_keeps_legacy_behavior(tmp_path):
|
||||||
|
# worker senza esecuzione reale: il gate non si applica (parita' storica)
|
||||||
|
w = _long_worker(tmp_path, executor=None)
|
||||||
|
w.tick(_df(last_high=102.5, last_low=99.5))
|
||||||
|
assert not w.in_position
|
||||||
|
|
||||||
|
|
||||||
|
def test_phantom_does_not_block_other_exits(tmp_path):
|
||||||
|
# tocco TP fantasma E max_bars raggiunto nello stesso tick -> esce a time_limit
|
||||||
|
w = _long_worker(tmp_path, executor=_FakeExecutor(tp_filled_amount=0.0))
|
||||||
|
w.bars_held = 24
|
||||||
|
w.tick(_df(last_high=102.5, last_low=99.5))
|
||||||
|
assert not w.in_position
|
||||||
Reference in New Issue
Block a user