diff --git a/backtest_experiments.py b/backtest_experiments.py new file mode 100644 index 0000000..16a4870 --- /dev/null +++ b/backtest_experiments.py @@ -0,0 +1,235 @@ +"""Walk-forward tests for multi-session and volume-spike strategies.""" + +from __future__ import annotations + +import itertools +import sys +from zoneinfo import ZoneInfo + +import numpy as np +import pandas as pd + +from data import fetch_candles +from strategy import Trade +from strategy_multi import MultiParams, run_multi +from strategy_volume import VolumeParams, run_volume + +NY = ZoneInfo("America/New_York") + +INITIAL_CAPITAL = 1_000.0 +RISK_PCT = 0.02 +TAKER_FEE = 0.00055 +LEVERAGE = 10 +TRAIN_RATIO = 0.5 +TIMEFRAME = "5m" + +# ── Grids ──────────────────────────────────────────────────────────── + +GRID_MULTI = { + "rr_ratio": [2.0, 2.5, 3.0], + "max_trades": [1, 2], + "fvg_expiry": [6, 12], + "min_range_pct": [0.0, 0.1, 0.2], + "min_fvg_pct": [0.0, 0.02], + "first_fvg_only": [False, True], +} # 3*2*2*3*2*2 = 144 + +GRID_VOLUME = { + "vol_lookback": [12, 24], + "vol_mult": [1.5, 2.0, 3.0], + "spike_bars": [2, 3], + "rr_ratio": [2.0, 2.5, 3.0], + "fvg_expiry": [6, 12], + "cooldown": [6, 12], + "min_fvg_pct": [0.0, 0.02], + "first_fvg_only": [False, True], +} # 2*3*2*3*2*2*2*2 = 576 + + +# ── Shared infra ───────────────────────────────────────────────────── + +def trades_to_pnl(trades: list[Trade], capital: float) -> list[dict]: + results = [] + equity = capital + for t in trades: + risk_dollar = equity * RISK_PCT + risk_dist = abs(t.entry - t.stop) + if risk_dist <= 0 or equity <= 0: + continue + pos_size = risk_dollar / risk_dist + pos_value = pos_size * t.entry + max_pos = equity * LEVERAGE + if pos_value > max_pos: + pos_size = max_pos / t.entry + pos_value = max_pos + if t.direction == "long": + gross = pos_size * (t.exit_price - t.entry) + else: + gross = pos_size * (t.entry - t.exit_price) + commission = pos_value * TAKER_FEE * 2 + pnl_net = gross - commission + equity += pnl_net + results.append({ + "pnl_net": pnl_net, "commission": commission, + "equity_after": equity, "entry_time": t.entry_time, + }) + return results + + +def compute_metrics(dollar_trades: list[dict], initial_capital: float, + n_days: int) -> dict: + empty = {"trades": 0, "wr": 0, "total_pnl": 0, "total_comm": 0, + "total_ret": 0, "sharpe": 0, "max_dd": 0, "monthly_pnl": 0, + "avg_win": 0, "avg_loss": 0} + if not dollar_trades: + return empty + + pnls = [t["pnl_net"] for t in dollar_trades] + wins = [p for p in pnls if p > 0] + losses = [p for p in pnls if p <= 0] + total_pnl = sum(pnls) + total_comm = sum(t["commission"] for t in dollar_trades) + wr = len(wins) / len(pnls) * 100 + + equity_curve = [initial_capital] + for t in dollar_trades: + equity_curve.append(t["equity_after"]) + eq = np.array(equity_curve) + peak = np.maximum.accumulate(eq) + dd_pct = (peak - eq) / peak * 100 + max_dd = float(dd_pct.max()) + + if len(pnls) > 1 and n_days > 1: + daily_pnl = np.zeros(n_days) + t0 = pd.Timestamp(dollar_trades[0]["entry_time"]) + if t0.tzinfo is None: + t0 = t0.tz_localize("UTC") + t0_date = t0.date() + for t in dollar_trades: + tsi = pd.Timestamp(t["entry_time"]) + if tsi.tzinfo is None: + tsi = tsi.tz_localize("UTC") + day_idx = (tsi.date() - t0_date).days + day_idx = max(0, min(day_idx, n_days - 1)) + daily_pnl[day_idx] += t["pnl_net"] + daily_ret = daily_pnl / initial_capital + std = np.std(daily_ret) + sharpe = float(np.mean(daily_ret) / std * np.sqrt(365)) if std > 0 else 0.0 + else: + sharpe = 0.0 + + months = n_days / 30.44 + return { + "trades": len(pnls), "wr": round(wr, 1), + "total_pnl": round(total_pnl, 2), "total_comm": round(total_comm, 2), + "total_ret": round(total_pnl / initial_capital * 100, 1), + "sharpe": round(sharpe, 2), "max_dd": round(max_dd, 1), + "monthly_pnl": round(total_pnl / months, 2) if months > 0 else 0, + "avg_win": round(np.mean(wins), 2) if wins else 0, + "avg_loss": round(np.mean(losses), 2) if losses else 0, + } + + +def _split(df): + df["_date"] = df["timestamp"].dt.date + dates = sorted(df["_date"].unique()) + split = int(len(dates) * TRAIN_RATIO) + train_dates = set(dates[:split]) + test_dates = set(dates[split:]) + df_train = df[df["_date"].isin(train_dates)].copy().drop(columns=["_date"]) + df_test = df[df["_date"].isin(test_dates)].copy().drop(columns=["_date"]) + df.drop(columns=["_date"], inplace=True) + return df_train, df_test, dates, split + + +def _print_result(name: str, train: dict, test: dict, params): + print(f"\n {'Metric':<14s} {'In-Sample':>12s} {'Out-of-Sample':>14s}") + print(f" {'-'*42}") + for label, k in [("Trades","trades"),("WR%","wr"),("PnL","total_pnl"), + ("Return%","total_ret"),("Comm","total_comm"), + ("Sharpe","sharpe"),("MaxDD","max_dd"),("$/mo","monthly_pnl")]: + tv, ev = train[k], test[k] + if k in ("total_pnl","total_comm","monthly_pnl","avg_win","avg_loss"): + print(f" {label:<14s} ${tv:>+11,.2f} ${ev:>+13,.2f}") + elif k in ("wr","total_ret","max_dd"): + print(f" {label:<14s} {tv:>11.1f}% {ev:>13.1f}%") + elif k == "sharpe": + print(f" {label:<14s} {tv:>12.2f} {ev:>14.2f}") + else: + print(f" {label:<14s} {tv:>12} {ev:>14}") + verdict = "PASS" if test.get("total_pnl", 0) > 0 else "FAIL" + print(f"\n OOS: {verdict} | ${test['total_pnl']:+,.2f} ({test['total_ret']:+.1f}%)") + + +# ── Multi-session experiment ───────────────────────────────────────── + +def test_multi(symbol: str, df: pd.DataFrame): + df_train, df_test, dates, split = _split(df.copy()) + n_train, n_test = split, len(dates) - split + + print(f"\n{'='*65}") + print(f" MULTI-SESSION | {symbol} | Asia+London+NYSE") + print(f"{'='*65}") + + keys = list(GRID_MULTI.keys()) + combos = list(itertools.product(*GRID_MULTI.values())) + best_score, best_kw = -999.0, {} + for vals in combos: + kw = dict(zip(keys, vals)) + trades = run_multi(df_train.copy(), MultiParams(**kw)) + score = sum(t.pnl_r for t in trades) if len(trades) >= 3 else -999 + if score > best_score: + best_score, best_kw = score, kw + best = MultiParams(**best_kw) if best_kw else MultiParams() + print(f" Best: {best}") + + train_trades = run_multi(df_train.copy(), best) + test_trades = run_multi(df_test.copy(), best) + train_m = compute_metrics(trades_to_pnl(train_trades, INITIAL_CAPITAL), INITIAL_CAPITAL, n_train) + test_m = compute_metrics(trades_to_pnl(test_trades, INITIAL_CAPITAL), INITIAL_CAPITAL, n_test) + _print_result("Multi", train_m, test_m, best) + return test_m + + +# ── Volume-spike experiment ────────────────────────────────────────── + +def test_volume(symbol: str, df: pd.DataFrame): + df_train, df_test, dates, split = _split(df.copy()) + n_train, n_test = split, len(dates) - split + + print(f"\n{'='*65}") + print(f" VOLUME-SPIKE | {symbol} | 24/7") + print(f"{'='*65}") + + keys = list(GRID_VOLUME.keys()) + combos = list(itertools.product(*GRID_VOLUME.values())) + best_score, best_kw = -999.0, {} + for idx, vals in enumerate(combos): + kw = dict(zip(keys, vals)) + trades = run_volume(df_train.copy(), VolumeParams(**kw)) + score = sum(t.pnl_r for t in trades) if len(trades) >= 3 else -999 + if score > best_score: + best_score, best_kw = score, kw + if (idx + 1) % 100 == 0: + print(f"\r {idx+1}/{len(combos)}...", end="", flush=True) + print(f"\r {len(combos)}/{len(combos)} done. ") + best = VolumeParams(**best_kw) if best_kw else VolumeParams() + print(f" Best: {best}") + + train_trades = run_volume(df_train.copy(), best) + test_trades = run_volume(df_test.copy(), best) + train_m = compute_metrics(trades_to_pnl(train_trades, INITIAL_CAPITAL), INITIAL_CAPITAL, n_train) + test_m = compute_metrics(trades_to_pnl(test_trades, INITIAL_CAPITAL), INITIAL_CAPITAL, n_test) + _print_result("Volume", train_m, test_m, best) + return test_m + + +if __name__ == "__main__": + symbols = sys.argv[1:] if len(sys.argv) > 1 else [ + "ETH/USDT:USDT", "SOL/USDT:USDT", "BTC/USDT:USDT" + ] + + for sym in symbols: + df = fetch_candles(sym, 60, TIMEFRAME) + test_multi(sym, df) + test_volume(sym, df) diff --git a/backtest_rolling.py b/backtest_rolling.py new file mode 100644 index 0000000..646f7a5 --- /dev/null +++ b/backtest_rolling.py @@ -0,0 +1,233 @@ +"""Walk-forward backtest for rolling range strategy (24/7).""" + +from __future__ import annotations + +import itertools +import sys +from zoneinfo import ZoneInfo + +import numpy as np +import pandas as pd + +from data import fetch_candles +from strategy import Trade +from strategy_rolling import RollingParams, run_continuous + +NY = ZoneInfo("America/New_York") + +INITIAL_CAPITAL = 1_000.0 +RISK_PCT = 0.02 +TAKER_FEE = 0.00055 +LEVERAGE = 10 +TRAIN_RATIO = 0.5 +TIMEFRAME = "5m" + +GRID = { + "range_period": [6, 12, 24], # 30min, 1h, 2h on 5m + "rr_ratio": [2.0, 2.5, 3.0], + "fvg_expiry": [6, 12], + "cooldown": [3, 6, 12], + "min_range_pct": [0.0, 0.1, 0.2], + "min_fvg_pct": [0.0, 0.02], + "first_fvg_only": [False, True], +} +# 3*3*2*3*3*2*2 = 648 combos + + +def trades_to_pnl(trades: list[Trade], capital: float) -> list[dict]: + results = [] + equity = capital + for t in trades: + risk_dollar = equity * RISK_PCT + risk_dist = abs(t.entry - t.stop) + if risk_dist <= 0 or equity <= 0: + continue + pos_size = risk_dollar / risk_dist + pos_value = pos_size * t.entry + max_pos = equity * LEVERAGE + if pos_value > max_pos: + pos_size = max_pos / t.entry + pos_value = max_pos + + if t.direction == "long": + gross = pos_size * (t.exit_price - t.entry) + else: + gross = pos_size * (t.entry - t.exit_price) + commission = pos_value * TAKER_FEE * 2 + pnl_net = gross - commission + equity += pnl_net + results.append({ + "pnl_net": pnl_net, "commission": commission, + "equity_after": equity, "entry_time": t.entry_time, + }) + return results + + +def compute_metrics(dollar_trades: list[dict], initial_capital: float, + n_days: int) -> dict: + if not dollar_trades: + return {"trades": 0, "wins": 0, "losses": 0, "wr": 0, "total_pnl": 0, + "total_comm": 0, "total_ret": 0, "sharpe": 0, "max_dd": 0, + "monthly_pnl": 0, "avg_win": 0, "avg_loss": 0} + + pnls = [t["pnl_net"] for t in dollar_trades] + wins = [p for p in pnls if p > 0] + losses = [p for p in pnls if p <= 0] + total_pnl = sum(pnls) + total_comm = sum(t["commission"] for t in dollar_trades) + wr = len(wins) / len(pnls) * 100 + + equity_curve = [initial_capital] + for t in dollar_trades: + equity_curve.append(t["equity_after"]) + eq = np.array(equity_curve) + peak = np.maximum.accumulate(eq) + dd_pct = (peak - eq) / peak * 100 + max_dd = float(dd_pct.max()) + + if len(pnls) > 1 and n_days > 1: + daily_pnl = np.zeros(n_days) + ts0 = pd.Timestamp(dollar_trades[0]["entry_time"]) + t0 = (ts0.tz_convert(NY) if ts0.tzinfo else ts0.tz_localize("UTC").tz_convert(NY)).date() + for t in dollar_trades: + ts = t["entry_time"] + if ts is not None: + tsi = pd.Timestamp(ts) + d = (tsi.tz_convert(NY) if tsi.tzinfo else tsi.tz_localize("UTC").tz_convert(NY)).date() + day_idx = (d - t0).days + day_idx = max(0, min(day_idx, n_days - 1)) + daily_pnl[day_idx] += t["pnl_net"] + daily_ret = daily_pnl / initial_capital + std = np.std(daily_ret) + sharpe = float(np.mean(daily_ret) / std * np.sqrt(365)) if std > 0 else 0.0 + else: + sharpe = 0.0 + + months = n_days / 30.44 + return { + "trades": len(pnls), "wins": len(wins), "losses": len(losses), + "wr": round(wr, 1), "total_pnl": round(total_pnl, 2), + "total_comm": round(total_comm, 2), + "total_ret": round(total_pnl / initial_capital * 100, 1), + "sharpe": round(sharpe, 2), "max_dd": round(max_dd, 1), + "monthly_pnl": round(total_pnl / months, 2) if months > 0 else 0, + "avg_win": round(np.mean(wins), 2) if wins else 0, + "avg_loss": round(np.mean(losses), 2) if losses else 0, + } + + +def _split_by_date(df: pd.DataFrame): + """Split dataframe into train/test by calendar date.""" + df["_date"] = df["timestamp"].dt.date + dates = sorted(df["_date"].unique()) + split = int(len(dates) * TRAIN_RATIO) + train_dates = set(dates[:split]) + test_dates = set(dates[split:]) + df_train = df[df["_date"].isin(train_dates)].copy() + df_test = df[df["_date"].isin(test_dates)].copy() + df.drop(columns=["_date"], inplace=True) + df_train.drop(columns=["_date"], inplace=True) + df_test.drop(columns=["_date"], inplace=True) + return df_train, df_test, dates, split + + +def find_best_params(df_train: pd.DataFrame) -> RollingParams: + keys = list(GRID.keys()) + combos = list(itertools.product(*GRID.values())) + best_score = -999.0 + best_kw = {} + + for idx, vals in enumerate(combos): + kw = dict(zip(keys, vals)) + p = RollingParams(**kw) + trades = run_continuous(df_train, p) + score = sum(t.pnl_r for t in trades) if len(trades) >= 3 else -999 + if score > best_score: + best_score = score + best_kw = kw + if (idx + 1) % 100 == 0: + print(f"\r {idx+1}/{len(combos)}...", end="", flush=True) + + print(f"\r {len(combos)}/{len(combos)} done. ") + return RollingParams(**best_kw) if best_kw else RollingParams() + + +def walk_forward(symbol: str, days: int = 60): + df = fetch_candles(symbol, days, TIMEFRAME) + df_train, df_test, dates, split = _split_by_date(df) + n_train = split + n_test = len(dates) - split + + print(f"\n{'='*65}") + print(f" Rolling WF | {symbol} | {days}d | {TIMEFRAME} | 24/7") + print(f"{'='*65}") + print(f" Train: {n_train} days ({dates[0]} → {dates[split-1]})") + print(f" Test: {n_test} days ({dates[split]} → {dates[-1]})") + print(f" Capital: ${INITIAL_CAPITAL:,.0f} | Risk: {RISK_PCT*100:.0f}% | Lev: {LEVERAGE}x") + + n_combos = len(list(itertools.product(*GRID.values()))) + print(f"\n Phase 1: Grid search ({n_combos} combos)...") + best = find_best_params(df_train) + print(f" Best params: {best}") + + # In-sample + train_trades = run_continuous(df_train, best) + train_dollar = trades_to_pnl(train_trades, INITIAL_CAPITAL) + train_m = compute_metrics(train_dollar, INITIAL_CAPITAL, n_train) + + # Out-of-sample + print(f"\n Phase 2: Out-of-sample test...") + test_trades = run_continuous(df_test, best) + test_dollar = trades_to_pnl(test_trades, INITIAL_CAPITAL) + test_m = compute_metrics(test_dollar, INITIAL_CAPITAL, n_test) + + _print_comparison(train_m, test_m) + return {"train": train_m, "test": test_m, "params": best} + + +def _print_comparison(train: dict, test: dict): + print(f"\n {'Metric':<14s} {'In-Sample':>12s} {'Out-of-Sample':>14s}") + print(f" {'-'*42}") + rows = [ + ("Trades", f"{train['trades']}", f"{test['trades']}"), + ("Win Rate", f"{train['wr']}%", f"{test['wr']}%"), + ("Total PnL", f"${train['total_pnl']:+,.2f}", f"${test['total_pnl']:+,.2f}"), + ("Return", f"{train['total_ret']:+.1f}%", f"{test['total_ret']:+.1f}%"), + ("Commission", f"${train['total_comm']:,.2f}", f"${test['total_comm']:,.2f}"), + ("Sharpe", f"{train['sharpe']:.2f}", f"{test['sharpe']:.2f}"), + ("Max DD", f"{train['max_dd']:.1f}%", f"{test['max_dd']:.1f}%"), + ("Monthly PnL", f"${train['monthly_pnl']:+,.2f}", f"${test['monthly_pnl']:+,.2f}"), + ("Avg Win", f"${train['avg_win']:+,.2f}", f"${test['avg_win']:+,.2f}"), + ("Avg Loss", f"${train['avg_loss']:+,.2f}", f"${test['avg_loss']:+,.2f}"), + ] + for label, tv, ev in rows: + print(f" {label:<14s} {tv:>12s} {ev:>14s}") + + print(f"\n {'='*42}") + verdict = "PASS" if test.get("total_pnl", 0) > 0 else "FAIL" + print(f" OOS Verdict: {verdict}") + if test["trades"] > 0: + print(f" OOS PnL: ${test['total_pnl']:+,.2f} ({test['total_ret']:+.1f}%)") + + +if __name__ == "__main__": + symbols = sys.argv[1:] if len(sys.argv) > 1 else [ + "BTC/USDT:USDT", "ETH/USDT:USDT", "SOL/USDT:USDT" + ] + all_results = {} + for sym in symbols: + all_results[sym] = walk_forward(sym, 60) + + if len(all_results) > 1: + print(f"\n\n{'='*70}") + print(f" ROLLING WF SUMMARY | ${INITIAL_CAPITAL:,.0f} | {RISK_PCT*100:.0f}% risk | {LEVERAGE}x | 24/7") + print(f"{'='*70}") + print(f" {'Symbol':<16s} {'OOS PnL':>10s} {'Ret%':>7s} {'Sharpe':>8s} " + f"{'MaxDD':>7s} {'Trades':>7s} {'WR':>6s}") + print(f" {'-'*62}") + for sym, r in all_results.items(): + t = r["test"] + tag = sym.split("/")[0] + print(f" {tag:<16s} ${t['total_pnl']:>+9,.2f} {t['total_ret']:>+6.1f}% " + f"{t['sharpe']:>8.2f} {t['max_dd']:>6.1f}% {t['trades']:>7d} " + f"{t['wr']:>5.1f}%") diff --git a/strategy_multi.py b/strategy_multi.py new file mode 100644 index 0000000..c7cea56 --- /dev/null +++ b/strategy_multi.py @@ -0,0 +1,211 @@ +"""Multi-session ORB + FVG + Engulfing: NYSE + London + Asia.""" + +from __future__ import annotations + +from dataclasses import dataclass +from datetime import timezone + +import pandas as pd + +from strategy import FVG, Trade + + +@dataclass +class SessionDef: + """Session definition in UTC hours/minutes.""" + name: str + or_start_h: int # OR start hour (UTC) + or_start_m: int # OR start minute (UTC) + or_duration: int # OR duration in minutes + trade_hours: float # trading window after OR (hours) + + +# Crypto sessions (UTC) +SESSIONS = [ + SessionDef("Asia", 0, 0, 15, 2.0), # 00:00-00:15, trade until 02:00 + SessionDef("London", 8, 0, 15, 2.0), # 08:00-08:15, trade until 10:00 + SessionDef("NYSE", 14, 30, 15, 2.0), # 14:30-14:45, trade until 16:30 +] + + +@dataclass +class MultiParams: + rr_ratio: float = 3.0 + max_trades: int = 1 # per session + fvg_expiry: int = 12 # bars + min_range_pct: float = 0.0 + min_fvg_pct: float = 0.0 + first_fvg_only: bool = False + + +def _run_session(df: pd.DataFrame, sess: SessionDef, + p: MultiParams) -> list[Trade]: + """Run one session on one day's data (UTC timestamps).""" + ts = df["timestamp"].dt.tz_convert(timezone.utc) + + # Opening range + or_end_m = sess.or_start_m + sess.or_duration + or_end_h = sess.or_start_h + or_end_m // 60 + or_end_m = or_end_m % 60 + + or_mask = ( + (ts.dt.hour == sess.or_start_h) & (ts.dt.minute >= sess.or_start_m) + ) + if or_end_h > sess.or_start_h: + or_mask = or_mask | ( + (ts.dt.hour >= sess.or_start_h + 1) & (ts.dt.hour < or_end_h) + ) + if or_end_m > 0: + or_mask = or_mask | ( + (ts.dt.hour == or_end_h) & (ts.dt.minute < or_end_m) + ) + else: + or_mask = or_mask & (ts.dt.minute < or_end_m) + + rc = df[or_mask] + if len(rc) < 1: + return [] + + rh = float(rc["high"].max()) + rl = float(rc["low"].min()) + mid = (rh + rl) / 2 + + if p.min_range_pct > 0 and mid > 0: + if (rh - rl) / mid < p.min_range_pct / 100: + return [] + + # Trading window after OR + trade_end_minutes = (sess.or_start_h * 60 + sess.or_start_m + + sess.or_duration + int(p.max_trades * 60 * sess.trade_hours / p.max_trades)) + # Simpler: end = or_start + or_duration + trade_hours + total_minutes = sess.or_start_h * 60 + sess.or_start_m + sess.or_duration + end_minutes = total_minutes + int(sess.trade_hours * 60) + + after_mask = pd.Series(False, index=df.index) + for idx in df.index: + t = ts.iloc[idx - df.index[0]] if idx >= df.index[0] else ts.iloc[0] + m = t.hour * 60 + t.minute + if total_minutes <= m < end_minutes: + after_mask.iloc[idx - df.index[0]] = True + + after = df[after_mask].reset_index(drop=True) + if len(after) < 3: + return [] + + # Same FVG + engulfing logic + trades: list[Trade] = [] + fvgs: list[FVG] = [] + active: Trade | None = None + trade_count = 0 + + for i in range(len(after)): + c = after.iloc[i] + + if active: + hit_sl = hit_tp = False + if active.direction == "long": + hit_sl = c["low"] <= active.stop + hit_tp = c["high"] >= active.tp + else: + hit_sl = c["high"] >= active.stop + hit_tp = c["low"] <= active.tp + + if hit_sl: + active.exit_price = active.stop + active.exit_time = c["timestamp"] + active.result = "loss" + active.pnl_r = -1.0 + trades.append(active) + active = None + elif hit_tp: + active.exit_price = active.tp + active.exit_time = c["timestamp"] + active.result = "win" + active.pnl_r = p.rr_ratio + trades.append(active) + active = None + else: + continue + + if trade_count >= p.max_trades: + continue + + if i >= 2: + c0, c1 = after.iloc[i - 2], after.iloc[i - 1] + fvg = None + if c1["close"] > rh and c["low"] > c0["high"]: + fvg = FVG("bull", c0["high"], c["low"], i) + elif c1["close"] < rl and c["high"] < c0["low"]: + fvg = FVG("bear", c["high"], c0["low"], i) + if fvg: + gap = fvg.zone_high - fvg.zone_low + if p.min_fvg_pct > 0 and mid > 0 and gap / mid < p.min_fvg_pct / 100: + fvg = None + if fvg and not (p.first_fvg_only and fvgs): + fvgs.append(fvg) + + fvgs = [f for f in fvgs if not f.used and (i - f.bar_idx) < p.fvg_expiry] + + if i < 1: + continue + prev = after.iloc[i - 1] + for fvg in fvgs: + if fvg.used: + continue + if not (prev["low"] <= fvg.zone_high and prev["high"] >= fvg.zone_low): + continue + if fvg.direction == "bull": + ok = (prev["close"] < prev["open"] + and c["close"] > c["open"] + and c["close"] >= prev["open"] + and c["open"] <= prev["close"]) + else: + ok = (prev["close"] > prev["open"] + and c["close"] < c["open"] + and c["close"] <= prev["open"] + and c["open"] >= prev["close"]) + if not ok: + continue + + entry = float(c["close"]) + stop = float(c["low"]) if fvg.direction == "bull" else float(c["high"]) + risk = abs(entry - stop) + if risk <= 0: + continue + tp = entry + p.rr_ratio * risk if fvg.direction == "bull" else entry - p.rr_ratio * risk + active = Trade( + direction="long" if fvg.direction == "bull" else "short", + entry=entry, stop=stop, tp=tp, entry_time=c["timestamp"], + ) + fvg.used = True + trade_count += 1 + break + + if active: + last = after.iloc[-1] + active.exit_price = float(last["close"]) + active.exit_time = last["timestamp"] + risk = abs(active.entry - active.stop) + pnl = ((active.exit_price - active.entry) if active.direction == "long" + else (active.entry - active.exit_price)) + active.pnl_r = pnl / risk if risk > 0 else 0 + active.result = "win" if active.pnl_r > 0 else "loss" + trades.append(active) + + return trades + + +def run_multi(df: pd.DataFrame, p: MultiParams | None = None, + sessions: list[SessionDef] | None = None) -> list[Trade]: + """Run all sessions across all UTC dates.""" + p = p or MultiParams() + sessions = sessions or SESSIONS + df["_utc_date"] = df["timestamp"].dt.tz_convert(timezone.utc).dt.date + all_trades = [] + + for _, day_df in df.groupby("_utc_date"): + for sess in sessions: + all_trades.extend(_run_session(day_df.reset_index(drop=True), sess, p)) + + df.drop(columns=["_utc_date"], inplace=True) + return all_trades diff --git a/strategy_rolling.py b/strategy_rolling.py new file mode 100644 index 0000000..d8e5097 --- /dev/null +++ b/strategy_rolling.py @@ -0,0 +1,173 @@ +"""Rolling Range Breakout + FVG + Engulfing strategy (24/7, no time binding). + +Instead of NYSE opening range, uses rolling high/low of last N bars +as breakout levels. Works on any market hours. +""" + +from __future__ import annotations + +from dataclasses import dataclass + +import pandas as pd + +from strategy import FVG, Trade + + +@dataclass +class RollingParams: + range_period: int = 12 # rolling range lookback (bars) + rr_ratio: float = 3.0 + fvg_expiry: int = 12 # FVG valid N bars + cooldown: int = 6 # bars to wait after trade + min_range_pct: float = 0.0 # min range as % of price + min_fvg_pct: float = 0.0 # min FVG gap as % of price + first_fvg_only: bool = False + + +def run_continuous(df: pd.DataFrame, p: RollingParams | None = None) -> list[Trade]: + """Process entire dataframe with rolling range breakout. No time restrictions.""" + p = p or RollingParams() + n = len(df) + if n < p.range_period + 5: + return [] + + highs = df["high"].values + lows = df["low"].values + opens = df["open"].values + closes = df["close"].values + timestamps = df["timestamp"].values + + trades: list[Trade] = [] + fvgs: list[FVG] = [] + active: Trade | None = None + cooldown_until = 0 + + for i in range(p.range_period + 2, n): + # Rolling range BEFORE the 3-candle FVG pattern (exclude i, i-1, i-2) + rng_start = max(0, i - 2 - p.range_period) + rng_end = i - 2 + rh = float(highs[rng_start:rng_end].max()) + rl = float(lows[rng_start:rng_end].min()) + mid = (rh + rl) / 2 + + # Min range filter + if p.min_range_pct > 0 and mid > 0: + if (rh - rl) / mid < p.min_range_pct / 100: + continue + + c_high = float(highs[i]) + c_low = float(lows[i]) + c_open = float(opens[i]) + c_close = float(closes[i]) + c_ts = timestamps[i] + + # Check SL / TP on active trade + if active: + hit_sl = hit_tp = False + if active.direction == "long": + hit_sl = c_low <= active.stop + hit_tp = c_high >= active.tp + else: + hit_sl = c_high >= active.stop + hit_tp = c_low <= active.tp + + if hit_sl: + active.exit_price = active.stop + active.exit_time = c_ts + active.result = "loss" + active.pnl_r = -1.0 + trades.append(active) + active = None + cooldown_until = i + p.cooldown + elif hit_tp: + active.exit_price = active.tp + active.exit_time = c_ts + active.result = "win" + active.pnl_r = p.rr_ratio + trades.append(active) + active = None + cooldown_until = i + p.cooldown + else: + continue + + # Cooldown after last trade + if i < cooldown_until: + continue + + # Detect FVG (need 3 bars) + if i >= 2: + c0_high = float(highs[i - 2]) + c0_low = float(lows[i - 2]) + c1_close = float(closes[i - 1]) + fvg = None + + if c1_close > rh and c_low > c0_high: + fvg = FVG("bull", c0_high, c_low, i) + elif c1_close < rl and c_high < c0_low: + fvg = FVG("bear", c_high, c0_low, i) + + if fvg: + gap = fvg.zone_high - fvg.zone_low + if p.min_fvg_pct > 0 and mid > 0 and gap / mid < p.min_fvg_pct / 100: + fvg = None + if fvg and not (p.first_fvg_only and fvgs): + fvgs.append(fvg) + + # Expire old FVGs + fvgs = [f for f in fvgs if not f.used and (i - f.bar_idx) < p.fvg_expiry] + + # Check retest + engulfing + if i < 1: + continue + prev_high = float(highs[i - 1]) + prev_low = float(lows[i - 1]) + prev_open = float(opens[i - 1]) + prev_close = float(closes[i - 1]) + + for fvg in fvgs: + if fvg.used: + continue + if not (prev_low <= fvg.zone_high and prev_high >= fvg.zone_low): + continue + + # Engulfing check + if fvg.direction == "bull": + ok = (prev_close < prev_open + and c_close > c_open + and c_close >= prev_open + and c_open <= prev_close) + else: + ok = (prev_close > prev_open + and c_close < c_open + and c_close <= prev_open + and c_open >= prev_close) + if not ok: + continue + + entry = c_close + stop = c_low if fvg.direction == "bull" else c_high + risk = abs(entry - stop) + if risk <= 0: + continue + + tp = entry + p.rr_ratio * risk if fvg.direction == "bull" else entry - p.rr_ratio * risk + active = Trade( + direction="long" if fvg.direction == "bull" else "short", + entry=entry, stop=stop, tp=tp, entry_time=c_ts, + ) + fvg.used = True + break + + # Close remaining position at last bar + if active: + last_close = float(closes[-1]) + risk = abs(active.entry - active.stop) + pnl = ((last_close - active.entry) if active.direction == "long" + else (active.entry - last_close)) + active.exit_price = last_close + active.exit_time = timestamps[-1] + active.pnl_r = pnl / risk if risk > 0 else 0 + active.result = "win" if active.pnl_r > 0 else "loss" + trades.append(active) + + return trades diff --git a/strategy_volume.py b/strategy_volume.py new file mode 100644 index 0000000..675d413 --- /dev/null +++ b/strategy_volume.py @@ -0,0 +1,189 @@ +"""Volume-spike Range + FVG + Engulfing strategy. + +Forms breakout levels from volume spikes instead of fixed time windows. +A volume spike defines a "range" — then FVG + engulfing after breakout. +""" + +from __future__ import annotations + +from dataclasses import dataclass + +import numpy as np +import pandas as pd + +from strategy import FVG, Trade + + +@dataclass +class VolumeParams: + vol_lookback: int = 24 # rolling avg volume window (bars) + vol_mult: float = 2.0 # spike threshold (x * avg) + spike_bars: int = 3 # N bars around spike to form range + rr_ratio: float = 3.0 + fvg_expiry: int = 12 + cooldown: int = 6 # bars after trade + min_range_pct: float = 0.0 + min_fvg_pct: float = 0.0 + first_fvg_only: bool = False + + +def run_volume(df: pd.DataFrame, p: VolumeParams | None = None) -> list[Trade]: + """Process data with volume-spike based ranges.""" + p = p or VolumeParams() + n = len(df) + if n < p.vol_lookback + 10: + return [] + + highs = df["high"].values.astype(float) + lows = df["low"].values.astype(float) + opens = df["open"].values.astype(float) + closes = df["close"].values.astype(float) + volumes = df["volume"].values.astype(float) + timestamps = df["timestamp"].values + + trades: list[Trade] = [] + fvgs: list[FVG] = [] + active: Trade | None = None + cooldown_until = 0 + + # Current range (set by volume spikes) + rh = rl = mid = 0.0 + range_set = False + range_bar = 0 # when range was last set + + for i in range(p.vol_lookback, n): + # Detect volume spike + avg_vol = float(np.mean(volumes[i - p.vol_lookback:i])) + if avg_vol > 0 and volumes[i] >= avg_vol * p.vol_mult: + # Set range from spike neighborhood + start = max(0, i - p.spike_bars) + end = min(n, i + 1) + rh = float(highs[start:end].max()) + rl = float(lows[start:end].min()) + mid = (rh + rl) / 2 + range_set = True + range_bar = i + fvgs = [] # reset FVGs on new range + + if not range_set: + continue + + # Range too old (>2h = 24 bars on 5m) + if i - range_bar > 24: + range_set = False + continue + + # Min range filter + if p.min_range_pct > 0 and mid > 0: + if (rh - rl) / mid < p.min_range_pct / 100: + continue + + c_high = float(highs[i]) + c_low = float(lows[i]) + c_open = float(opens[i]) + c_close = float(closes[i]) + c_ts = timestamps[i] + + # Check SL / TP + if active: + hit_sl = hit_tp = False + if active.direction == "long": + hit_sl = c_low <= active.stop + hit_tp = c_high >= active.tp + else: + hit_sl = c_high >= active.stop + hit_tp = c_low <= active.tp + + if hit_sl: + active.exit_price = active.stop + active.exit_time = c_ts + active.result = "loss" + active.pnl_r = -1.0 + trades.append(active) + active = None + cooldown_until = i + p.cooldown + elif hit_tp: + active.exit_price = active.tp + active.exit_time = c_ts + active.result = "win" + active.pnl_r = p.rr_ratio + trades.append(active) + active = None + cooldown_until = i + p.cooldown + else: + continue + + if i < cooldown_until: + continue + + # Detect FVG + if i >= 2: + c0_high = float(highs[i - 2]) + c0_low = float(lows[i - 2]) + c1_close = float(closes[i - 1]) + fvg = None + + if c1_close > rh and c_low > c0_high: + fvg = FVG("bull", c0_high, c_low, i) + elif c1_close < rl and c_high < c0_low: + fvg = FVG("bear", c_high, c0_low, i) + + if fvg: + gap = fvg.zone_high - fvg.zone_low + if p.min_fvg_pct > 0 and mid > 0 and gap / mid < p.min_fvg_pct / 100: + fvg = None + if fvg and not (p.first_fvg_only and fvgs): + fvgs.append(fvg) + + fvgs = [f for f in fvgs if not f.used and (i - f.bar_idx) < p.fvg_expiry] + + if i < 1: + continue + prev_high = float(highs[i - 1]) + prev_low = float(lows[i - 1]) + prev_open = float(opens[i - 1]) + prev_close = float(closes[i - 1]) + + for fvg in fvgs: + if fvg.used: + continue + if not (prev_low <= fvg.zone_high and prev_high >= fvg.zone_low): + continue + if fvg.direction == "bull": + ok = (prev_close < prev_open + and c_close > c_open + and c_close >= prev_open + and c_open <= prev_close) + else: + ok = (prev_close > prev_open + and c_close < c_open + and c_close <= prev_open + and c_open >= prev_close) + if not ok: + continue + + entry = c_close + stop = c_low if fvg.direction == "bull" else c_high + risk = abs(entry - stop) + if risk <= 0: + continue + tp = entry + p.rr_ratio * risk if fvg.direction == "bull" else entry - p.rr_ratio * risk + active = Trade( + direction="long" if fvg.direction == "bull" else "short", + entry=entry, stop=stop, tp=tp, entry_time=c_ts, + ) + fvg.used = True + break + + if active: + last_close = float(closes[-1]) + risk = abs(active.entry - active.stop) + pnl = ((last_close - active.entry) if active.direction == "long" + else (active.entry - last_close)) + active.exit_price = last_close + active.exit_time = timestamps[-1] + active.pnl_r = pnl / risk if risk > 0 else 0 + active.result = "win" if active.pnl_r > 0 else "loss" + trades.append(active) + + return trades