""" Causal Historical Replay Backtester =================================== Replays multi-timeframe OHLCV and historical funding rates bar-by-bar with strict zero-lookahead slicing (bar[i] observes ONLY candles/funding <= bar[i].timestamp), next-bar-open fills, pessimistic SL-first intra-bar resolution, taker fees, slippage, and 8-hour funding rate cashflows. """ from __future__ import annotations from bisect import bisect_right import math from typing import Any, Callable from engine.hl_whale_tracker import HyperliquidWhaleTracker from engine.l2_microstructure import L2OrderbookTracker from engine.signal_engine import SignalEngine from exchanges.base import BaseExchange HOURS_PER_YEAR = 8760 EIGHT_HOURS_MS = 8 * 3_600_000 def _aggregate_higher_tf(candles_1h: list[dict], group_hours: int) -> list[dict]: """Causally aggregate completed/current 1h candles up to t_now into group_hours bars.""" if not candles_1h: return [] bucket_ms = group_hours * 3_600_000 grouped: list[dict] = [] cur_bucket: int | None = None cur_bar: dict[str, Any] | None = None for c in candles_1h: ts = int(c["timestamp"]) b_id = ts // bucket_ms if cur_bucket != b_id or cur_bar is None: if cur_bar is not None: grouped.append(cur_bar) cur_bucket = b_id cur_bar = { "timestamp": b_id * bucket_ms, "open": float(c["open"]), "high": float(c["high"]), "low": float(c["low"]), "close": float(c["close"]), "volume": float(c.get("volume", 0.0)), } if c.get("taker_buy_volume") is not None: cur_bar["taker_buy_volume"] = float(c["taker_buy_volume"]) else: cur_bar["high"] = max(cur_bar["high"], float(c["high"])) cur_bar["low"] = min(cur_bar["low"], float(c["low"])) cur_bar["close"] = float(c["close"]) cur_bar["volume"] += float(c.get("volume", 0.0)) if c.get("taker_buy_volume") is not None: cur_bar["taker_buy_volume"] = cur_bar.get("taker_buy_volume", 0.0) + float(c["taker_buy_volume"]) if cur_bar is not None: grouped.append(cur_bar) return grouped def _causal_slice_by_ts(candles: list[dict] | None, ts_list: list[int] | None, max_ts: int) -> list[dict]: """Return prefix slice of sorted candles with timestamp <= max_ts.""" if not candles or not ts_list: return [] idx = bisect_right(ts_list, max_ts) return candles[:idx] def _causal_slice_higher_tf( htf_candles: list[dict] | None, htf_timestamps: list[int] | None, bars_1h_prefix: list[dict], t_now: int, group_hours: int, ) -> list[dict]: """ Causally slice pre-supplied higher-TF candles (4h/1d) without lookahead: include only completed HTF candles whose close <= t_now + 1h, then synthesize the active in-progress HTF candle from 1h bars up to t_now. """ tf_ms = group_hours * 3_600_000 max_completed_open_ts = t_now + 3_600_000 - tf_ms completed = _causal_slice_by_ts(htf_candles, htf_timestamps, max_completed_open_ts) if not completed: return _aggregate_higher_tf(bars_1h_prefix, group_hours) last_completed_end = int(completed[-1]["timestamp"]) + tf_ms tail_1h = [b for b in bars_1h_prefix if int(b["timestamp"]) >= last_completed_end] if tail_1h: return list(completed) + _aggregate_higher_tf(tail_1h, group_hours) return list(completed) class CausalBacktester: """ Deterministic event-driven backtester verifying quantitative edge without lookahead. """ def __init__( self, initial_capital_usd: float = 10_000.0, position_size_pct: float = 0.25, leverage: float = 1.0, taker_fee_bps: float = 5.5, slippage_bps: float = 3.0, tp1_weight: float = 0.5, warmup_bars: int = 30, ) -> None: self.initial_capital_usd = float(initial_capital_usd) self.position_size_pct = max(0.01, min(1.0, float(position_size_pct))) self.leverage = max(1.0, float(leverage)) self.taker_fee_bps = max(0.0, float(taker_fee_bps)) self.slippage_bps = max(0.0, float(slippage_bps)) self.tp1_weight = max(0.0, min(1.0, float(tp1_weight))) self.warmup_bars = max(5, int(warmup_bars)) self._engine = SignalEngine( l2_tracker=L2OrderbookTracker(), hl_tracker=HyperliquidWhaleTracker(), ) @staticmethod def _latest_funding_rate(funding_sorted: list[dict], funding_ts: list[int], max_ts: int) -> float: if not funding_sorted or not funding_ts: return 0.0 idx = bisect_right(funding_ts, max_ts) - 1 if idx < 0: return 0.0 return float(funding_sorted[idx].get("funding_rate", 0.0) or 0.0) def _build_causal_raw( self, symbol: str, bars_1h_prefix: list[dict], t_now: int, candles_by_tf: dict[str, list[dict]], tf_timestamps: dict[str, list[int]], funding_sorted: list[dict], funding_ts: list[int], oi_history: list[dict] | None = None, oi_timestamps: list[int] | None = None, tape_entry: dict | None = None, ) -> dict[str, Any]: close_px = float(bars_1h_prefix[-1]["close"]) ohlcv_4h = _causal_slice_higher_tf( candles_by_tf.get("4h"), tf_timestamps.get("4h"), bars_1h_prefix, t_now, 4 ) ohlcv_1d = _causal_slice_higher_tf( candles_by_tf.get("1d"), tf_timestamps.get("1d"), bars_1h_prefix, t_now, 24 ) ohlcv_15m = _causal_slice_by_ts(candles_by_tf.get("15m"), tf_timestamps.get("15m"), t_now + 3_600_000 - 900_000) ohlcv_5m = _causal_slice_by_ts(candles_by_tf.get("5m"), tf_timestamps.get("5m"), t_now + 3_600_000 - 300_000) ohlcv_1m = _causal_slice_by_ts(candles_by_tf.get("1m"), tf_timestamps.get("1m"), t_now + 3_600_000 - 60_000) fr_val = self._latest_funding_rate(funding_sorted, funding_ts, t_now) ohlcv_bundle: dict[str, list[dict]] = { "1h": list(bars_1h_prefix), "4h": ohlcv_4h, "1d": ohlcv_1d, } if ohlcv_15m: ohlcv_bundle["15m"] = ohlcv_15m if ohlcv_5m: ohlcv_bundle["5m"] = ohlcv_5m if ohlcv_1m: ohlcv_bundle["1m"] = ohlcv_1m open_interest_data: dict[str, Any] | None = None if oi_history: if oi_timestamps is None: oi_timestamps = [int(x.get("timestamp") or x.get("time") or 0) for x in oi_history] idx = bisect_right(oi_timestamps, t_now) causal_oi = oi_history[:idx] if causal_oi: tail_oi = causal_oi[-64:] series = [ float(x.get("open_interest") if x.get("open_interest") is not None else x.get("sumOpenInterest", 0.0) or 0.0) for x in tail_oi ] curr_item = tail_oi[-1] curr_oi = series[-1] prev_oi = series[-2] if len(series) >= 2 else None oi_15m, oi_1h, oi_4h = BaseExchange._compute_oi_horizons(series) raw_val = curr_item.get("open_interest_value") if curr_item.get("open_interest_value") is not None else curr_item.get("sumOpenInterestValue") oi_val = float(raw_val) if raw_val is not None else None open_interest_data = { "open_interest": curr_oi, "prev_open_interest": prev_oi, "oi_change_pct": oi_15m, "oi_change_1h_pct": oi_1h, "oi_change_4h_pct": oi_4h, "open_interest_value": oi_val, "oi_horizon": "15m", } replayed_trades: list[dict] = [] replayed_liqs: list[dict] = [] hl_payload: dict | None = None if tape_entry and isinstance(tape_entry, dict): raw_slice = tape_entry.get("raw_replay_slice") or {} top_t = raw_slice.get("top_trades") or [] for item in top_t: p = float(item.get("p", close_px) or close_px) q = float(item.get("q", 1.0) or 1.0) s = "SELL" if item.get("s") == "S" else "BUY" replayed_trades.append({"price": p, "qty": q, "side": s, "time": t_now}) replayed_liqs = list(raw_slice.get("liquidations", [])) if raw_slice.get("hl_whale_bias"): hl_payload = { "mark_price": close_px, "trades": replayed_trades[:10], "funding_rate": fr_val, } return { "symbol": symbol, "has_spot": True, "replay_now_ts": (t_now + 3_600_000) / 1000.0, "binance": { "mark_price_data": {"mark_price": close_px, "index_price": close_px, "basis_pct": 0.0}, "funding_rate_data": {"funding_rate": fr_val, "next_funding_time": t_now + EIGHT_HOURS_MS}, "open_interest_data": open_interest_data, "ls_ratio_data": None, "trades": replayed_trades, "liquidations": replayed_liqs, "spot_trades": [], "ohlcv": ohlcv_bundle, "orderbook": { "bids": [[close_px * 0.9997, max(1000.0, 50_000.0 / max(close_px, 1e-9))]], "asks": [[close_px * 1.0003, max(1000.0, 50_000.0 / max(close_px, 1e-9))]], }, }, "bybit": None, "okx": None, "bitget": None, "hyperliquid": hl_payload, } def run( self, symbol: str, candles_1h: list[dict], funding_history: list[dict] | None = None, candles_by_tf: dict[str, list[dict]] | None = None, signal_fn: Callable[[dict[str, Any]], dict[str, Any]] | None = None, klines_15m: list[dict] | None = None, horizon: str = "primary", sniper_only: bool = False, breakeven_after_tp1: bool = False, signal_threshold: int | None = None, oi_history: list[dict] | None = None, tape_history: list[dict] | None = None, ) -> dict[str, Any]: """Run a causal bar-by-bar backtest over sorted 1h candles, historical funding, and optional microstructure tape.""" bars = sorted(candles_1h, key=lambda c: int(c["timestamp"])) if len(bars) <= self.warmup_bars + 1: raise ValueError( f"Minimal {self.warmup_bars + 2} candle 1H dibutuhkan untuk backtest (diterima {len(bars)})." ) funding_sorted = sorted(funding_history or [], key=lambda x: int(x["timestamp"])) funding_ts = [int(x["timestamp"]) for x in funding_sorted] oi_sorted = None if oi_history: dedup_oi: dict[int, dict] = {} for item in oi_history: ts_val = int(item.get("timestamp") or item.get("time") or 0) dedup_oi[ts_val] = item oi_sorted = [dedup_oi[ts_val] for ts_val in sorted(dedup_oi.keys())] oi_ts = ( [int(x.get("timestamp") or x.get("time") or 0) for x in oi_sorted] if oi_sorted else None ) tape_sorted = sorted(tape_history, key=lambda x: int(x.get("timestamp_ms") or 0)) if tape_history else None tape_ts = [int(x.get("timestamp_ms") or 0) for x in tape_sorted] if tape_sorted else None tf_map = dict(candles_by_tf or {}) if klines_15m: tf_map["15m"] = klines_15m tf_sorted: dict[str, list[dict]] = {} tf_ts: dict[str, list[int]] = {} for tf_name, tf_bars in tf_map.items(): ordered = sorted(tf_bars, key=lambda c: int(c["timestamp"])) tf_sorted[tf_name] = ordered tf_ts[tf_name] = [int(c["timestamp"]) for c in ordered] if signal_fn is not None: evaluate = signal_fn else: # Reset isolated L2/HL trackers per run so historical replay never leaks across runs or into live state self._engine._l2_tracker = L2OrderbookTracker() self._engine._hl_tracker = HyperliquidWhaleTracker() # Automatic OHLCV_FUNDING_ONLY threshold calibration (score >= 2 when 4 live factors are absent) eff_thresh = int(signal_threshold) if signal_threshold is not None else 2 h_thresholds = {"primary": eff_thresh, "intraday": eff_thresh, "swing": eff_thresh} evaluate = lambda raw: self._engine.compute(raw, horizon_thresholds=h_thresholds) slip = self.slippage_bps / 10_000.0 fee_rate = self.taker_fee_bps / 10_000.0 equity = self.initial_capital_usd peak_equity = equity max_drawdown_pct = 0.0 total_fees_usd = 0.0 total_funding_usd = 0.0 trades: list[dict[str, Any]] = [] equity_curve: list[dict[str, Any]] = [] pos: dict[str, Any] | None = None bars_evaluated = 0 def _close_leg( cur_pos: dict[str, Any], weight: float, raw_exit_px: float, apply_slippage: bool, ) -> tuple[float, float]: """Compute (gross_pnl, exit_fee) for exiting `weight` of cur_pos.""" qty_leg = cur_pos["total_qty"] * weight if cur_pos["direction"] == "LONG": exit_px = raw_exit_px * (1.0 - slip) if apply_slippage else raw_exit_px gross = (exit_px - cur_pos["entry_fill"]) * qty_leg else: exit_px = raw_exit_px * (1.0 + slip) if apply_slippage else raw_exit_px gross = (cur_pos["entry_fill"] - exit_px) * qty_leg exit_fee = abs(qty_leg * exit_px) * fee_rate return gross, exit_fee def _finalize_trade(cur_pos: dict[str, Any], exit_time: int, last_px: float, reason: str) -> None: nonlocal total_fees_usd, total_funding_usd net_pnl = cur_pos["realized_gross"] - cur_pos["fees_paid"] - cur_pos["funding_paid"] risk_usd = cur_pos["initial_risk_usd"] r_mult = (net_pnl / risk_usd) if risk_usd > 0 else 0.0 total_fees_usd += cur_pos["fees_paid"] total_funding_usd += cur_pos["funding_paid"] trades.append({ "entry_time": cur_pos["entry_time"], "exit_time": exit_time, "direction": cur_pos["direction"], "entry_price": round(cur_pos["entry_fill"], 6), "exit_price": round(last_px, 6), "exit_reason": reason, "gross_pnl_usd": round(cur_pos["realized_gross"], 4), "fees_usd": round(cur_pos["fees_paid"], 4), "funding_usd": round(cur_pos["funding_paid"], 4), "net_pnl_usd": round(net_pnl, 4), "r_multiple": round(r_mult, 4), }) # Step through decision bars i in [warmup_bars, len(bars) - 2]; execute on bar j = i + 1 for i in range(self.warmup_bars, len(bars) - 1): t_decision = int(bars[i]["timestamp"]) next_bar = bars[i + 1] t_bar = int(next_bar["timestamp"]) bar_open = float(next_bar["open"]) bar_high = float(next_bar["high"]) bar_low = float(next_bar["low"]) bar_close = float(next_bar["close"]) # 1. If flat, causally evaluate SignalEngine up to bars[i] and optionally enter at bars[i+1].open if pos is None: bars_evaluated += 1 tape_entry = None if tape_sorted and tape_ts: t_idx = bisect_right(tape_ts, t_decision) if t_idx > 0: cand = tape_sorted[t_idx - 1] cand_ts = int(cand.get("timestamp_ms") or 0) if (t_decision - cand_ts) <= 3_600_000: tape_entry = cand raw_data = self._build_causal_raw( symbol=symbol, bars_1h_prefix=bars[: i + 1], t_now=t_decision, candles_by_tf=tf_sorted, tf_timestamps=tf_ts, funding_sorted=funding_sorted, funding_ts=funding_ts, oi_history=oi_sorted, oi_timestamps=oi_ts, tape_entry=tape_entry, ) sig = evaluate(raw_data) if sniper_only and sig.get("sniper_grade") != "SNIPER_A_PLUS": direction = "NEUTRAL" levels = None elif horizon in ("primary", "intraday", "swing") and isinstance(sig.get("horizons"), dict) and horizon in sig["horizons"]: h_obj = sig["horizons"][horizon] direction = h_obj.get("direction", "NEUTRAL") levels = h_obj.get("trade_levels") else: direction = sig.get("direction", "NEUTRAL") levels = sig.get("trade_levels") if direction in ("LONG", "SHORT") and levels and equity > 0: sl = float(levels["stop_loss"]) tp1_raw = levels.get("take_profit_1", levels.get("tp1")) tp2_raw = levels.get("take_profit_2", levels.get("tp2")) tp1 = float(tp1_raw) tp2 = float(tp2_raw) if tp2_raw else None entry_fill = bar_open * (1.0 + slip) if direction == "LONG" else bar_open * (1.0 - slip) levels_valid = ( (direction == "LONG" and sl < entry_fill < tp1 and (tp2 is None or tp2 > tp1)) or (direction == "SHORT" and sl > entry_fill > tp1 and (tp2 is None or tp2 < tp1)) ) if levels_valid: notional = equity * self.position_size_pct * self.leverage total_qty = notional / entry_fill entry_fee = notional * fee_rate equity -= entry_fee risk_usd = abs(entry_fill - sl) * total_qty pos = { "direction": direction, "entry_time": t_bar, "entry_fill": entry_fill, "total_qty": total_qty, "remaining_weight": 1.0, "sl": sl, "tp1": tp1, "tp2": tp2, "tp1_hit": False, "initial_risk_usd": risk_usd, "realized_gross": 0.0, "fees_paid": entry_fee, "funding_paid": 0.0, } else: bars_evaluated += 1 # 2. Simulate intra-bar exits on next_bar (strict SL-first tie-breaking) if pos is not None: is_long = pos["direction"] == "LONG" sl_hit = (bar_low <= pos["sl"]) if is_long else (bar_high >= pos["sl"]) if sl_hit: rem = pos["remaining_weight"] gross, leg_fee = _close_leg(pos, rem, pos["sl"], apply_slippage=True) pos["realized_gross"] += gross pos["fees_paid"] += leg_fee equity += gross - leg_fee reason = ( "STOP_LOSS_BREAKEVEN" if pos.get("breakeven_armed") else ("STOP_LOSS_AFTER_TP1" if pos["tp1_hit"] else "STOP_LOSS") ) _finalize_trade(pos, t_bar, pos["sl"], reason) pos = None else: # Check TP1 first if not pos["tp1_hit"]: tp1_hit = (bar_high >= pos["tp1"]) if is_long else (bar_low <= pos["tp1"]) if tp1_hit: tp1_frac = min(pos["remaining_weight"], self.tp1_weight if pos["tp2"] else pos["remaining_weight"]) if tp1_frac > 0: gross, leg_fee = _close_leg(pos, tp1_frac, pos["tp1"], apply_slippage=False) pos["realized_gross"] += gross pos["fees_paid"] += leg_fee equity += gross - leg_fee pos["remaining_weight"] -= tp1_frac pos["tp1_hit"] = True if breakeven_after_tp1: pos["sl"] = ( pos["entry_fill"] * (1.0 + 0.0006) if is_long else pos["entry_fill"] * (1.0 - 0.0006) ) pos["breakeven_armed"] = True if pos["remaining_weight"] <= 1e-9 or pos["tp2"] is None: _finalize_trade(pos, t_bar, pos["tp1"], "TAKE_PROFIT_1") pos = None # Check TP2 if still open if pos is not None and pos["tp2"] is not None: tp2_hit = (bar_high >= pos["tp2"]) if is_long else (bar_low <= pos["tp2"]) if tp2_hit: rem = pos["remaining_weight"] gross, leg_fee = _close_leg(pos, rem, pos["tp2"], apply_slippage=False) pos["realized_gross"] += gross pos["fees_paid"] += leg_fee equity += gross - leg_fee _finalize_trade(pos, t_bar, pos["tp2"], "TAKE_PROFIT_2") pos = None # 3. Apply 8h UTC funding settlement if position remains held at bar close if pos is not None and (t_bar % EIGHT_HOURS_MS == 0): fr = self._latest_funding_rate(funding_sorted, funding_ts, t_bar) rem_notional = pos["total_qty"] * pos["remaining_weight"] * bar_close funding_cashflow = (fr * rem_notional) if is_long else (-fr * rem_notional) pos["funding_paid"] += funding_cashflow equity -= funding_cashflow # 4. Mark-to-market equity curve & drawdown tracking unrealized = 0.0 if pos is not None: rem_qty = pos["total_qty"] * pos["remaining_weight"] if pos["direction"] == "LONG": unrealized = (bar_close - pos["entry_fill"]) * rem_qty else: unrealized = (pos["entry_fill"] - bar_close) * rem_qty mtm_equity = max(0.0, equity + unrealized) if mtm_equity > peak_equity: peak_equity = mtm_equity dd_pct = ((peak_equity - mtm_equity) / peak_equity * 100.0) if peak_equity > 0 else 0.0 if dd_pct > max_drawdown_pct: max_drawdown_pct = dd_pct equity_curve.append({ "timestamp": t_bar, "equity_usd": round(mtm_equity, 4), "drawdown_pct": round(dd_pct, 4), }) # Force close any lingering position at final bar close so total PnL reconciles if pos is not None: final_bar = bars[-1] final_close = float(final_bar["close"]) final_ts = int(final_bar["timestamp"]) gross, leg_fee = _close_leg(pos, pos["remaining_weight"], final_close, apply_slippage=True) pos["realized_gross"] += gross pos["fees_paid"] += leg_fee equity += gross - leg_fee _finalize_trade(pos, final_ts, final_close, "END_OF_DATA") pos = None if equity_curve: final_eq = max(0.0, equity) if final_eq > peak_equity: peak_equity = final_eq final_dd = ((peak_equity - final_eq) / peak_equity * 100.0) if peak_equity > 0 else 0.0 if final_dd > max_drawdown_pct: max_drawdown_pct = final_dd equity_curve[-1]["equity_usd"] = round(final_eq, 4) equity_curve[-1]["drawdown_pct"] = round(final_dd, 4) total_trades = len(trades) winning_trades = sum(1 for t in trades if t["net_pnl_usd"] > 0) losing_trades = sum(1 for t in trades if t["net_pnl_usd"] < 0) win_rate_pct = (winning_trades / total_trades * 100.0) if total_trades > 0 else 0.0 gross_wins = sum(t["net_pnl_usd"] for t in trades if t["net_pnl_usd"] > 0) gross_losses = abs(sum(t["net_pnl_usd"] for t in trades if t["net_pnl_usd"] < 0)) if gross_losses > 0: profit_factor = round(gross_wins / gross_losses, 4) elif gross_wins > 0: profit_factor = 999.0 else: profit_factor = 0.0 net_pnl_usd = equity - self.initial_capital_usd net_return_pct = (net_pnl_usd / self.initial_capital_usd * 100.0) if self.initial_capital_usd > 0 else 0.0 expectancy_usd = (sum(t["net_pnl_usd"] for t in trades) / total_trades) if total_trades > 0 else 0.0 expectancy_r = (sum(t["r_multiple"] for t in trades) / total_trades) if total_trades > 0 else 0.0 # Annualized Sharpe & Sortino from hourly equity curve returns bar_returns: list[float] = [] prev_eq = self.initial_capital_usd for pt in equity_curve: cur_eq = pt["equity_usd"] if prev_eq > 0: bar_returns.append((cur_eq - prev_eq) / prev_eq) prev_eq = cur_eq sharpe_ratio = 0.0 sortino_ratio = 0.0 if bar_returns: mean_r = sum(bar_returns) / len(bar_returns) var_r = sum((r - mean_r) ** 2 for r in bar_returns) / len(bar_returns) std_r = math.sqrt(var_r) if std_r > 1e-12: sharpe_ratio = (mean_r / std_r) * math.sqrt(HOURS_PER_YEAR) downside_sq = sum(min(0.0, r) ** 2 for r in bar_returns) / len(bar_returns) downside_std = math.sqrt(downside_sq) if downside_std > 1e-12: sortino_ratio = (mean_r / downside_std) * math.sqrt(HOURS_PER_YEAR) return { "symbol": symbol.upper(), "telemetry_fidelity": "FULL_TELEMETRY_REPLAY" if tape_history else "OHLCV_FUNDING_ONLY", "horizon": horizon, "sniper_only": bool(sniper_only), "breakeven_after_tp1": bool(breakeven_after_tp1), "bars_evaluated": bars_evaluated, "warmup_bars": self.warmup_bars, "total_trades": total_trades, "winning_trades": winning_trades, "losing_trades": losing_trades, "win_rate_pct": round(win_rate_pct, 2), "profit_factor": profit_factor, "expectancy_usd": round(expectancy_usd, 4), "expectancy_r": round(expectancy_r, 4), "sharpe_ratio": round(sharpe_ratio, 4), "sortino_ratio": round(sortino_ratio, 4), "max_drawdown_pct": round(max_drawdown_pct, 2), "initial_capital_usd": round(self.initial_capital_usd, 2), "final_equity_usd": round(equity, 2), "net_pnl_usd": round(net_pnl_usd, 2), "net_return_pct": round(net_return_pct, 2), "total_fees_usd": round(total_fees_usd, 4), "total_funding_usd": round(total_funding_usd, 4), "equity_curve": equity_curve, "trades": trades, }