feat: ORB+FVG+Engulfing scalp-бот с walk-forward бэктестом
- strategy.py: стратегия с настраиваемыми параметрами (RR, FVG expiry, range filter) - data.py: загрузка свечей с Bybit (1m/5m/15m) с кэшированием - optimize.py: grid search по параметрам (972 комбинации) - backtest.py: простой бэктест в R-единицах - backtest_wf.py: walk-forward (50/50 split) с реалистичными комиссиями и Sharpe - backtest_leverage.py: sweep по плечам (1x-50x) с проверкой маржи и ликвидации Результат: на 5m ETH +10.5%/мес (Sharpe 3.11), SOL +5.9%/мес при 2% риске Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,3 @@
|
||||
cache/
|
||||
__pycache__/
|
||||
.venv/
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
"""Backtest the ORB+FVG+Engulfing scalping strategy."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from data import fetch_1m
|
||||
from strategy import run_day
|
||||
|
||||
NY = ZoneInfo("America/New_York")
|
||||
|
||||
|
||||
def backtest(symbol: str = "BTC/USDT:USDT", days: int = 60):
|
||||
df = fetch_1m(symbol, days)
|
||||
df["ny_date"] = df["timestamp"].dt.tz_convert(NY).dt.date
|
||||
|
||||
all_trades = []
|
||||
session_count = 0
|
||||
for date, day_df in df.groupby("ny_date"):
|
||||
trades = run_day(day_df.reset_index(drop=True))
|
||||
all_trades.extend(trades)
|
||||
session_count += 1
|
||||
|
||||
# ── Stats ──
|
||||
total = len(all_trades)
|
||||
if total == 0:
|
||||
print(f"No trades in {session_count} sessions over {days} days.")
|
||||
return
|
||||
|
||||
wins = sum(1 for t in all_trades if t.result == "win")
|
||||
losses = total - wins
|
||||
wr = wins / total * 100
|
||||
total_r = sum(t.pnl_r for t in all_trades)
|
||||
avg_r = total_r / total
|
||||
pf = (wins * 3) / max(losses, 1)
|
||||
|
||||
# Max consecutive losses
|
||||
max_streak = streak = 0
|
||||
for t in all_trades:
|
||||
if t.result == "loss":
|
||||
streak += 1
|
||||
max_streak = max(max_streak, streak)
|
||||
else:
|
||||
streak = 0
|
||||
|
||||
# Equity curve (starting at 0 R)
|
||||
equity = 0.0
|
||||
peak = 0.0
|
||||
max_dd_r = 0.0
|
||||
for t in all_trades:
|
||||
equity += t.pnl_r
|
||||
peak = max(peak, equity)
|
||||
dd = peak - equity
|
||||
max_dd_r = max(max_dd_r, dd)
|
||||
|
||||
print(f"\n{'='*60}")
|
||||
print(f" ORB + FVG + Engulfing Scalp | {symbol} | {days}d")
|
||||
print(f"{'='*60}")
|
||||
print(f" Sessions: {session_count}")
|
||||
print(f" Trades: {total}")
|
||||
print(f" Win rate: {wr:.1f}%")
|
||||
print(f" Wins / Losses: {wins} / {losses}")
|
||||
print(f" Total R: {total_r:+.1f}R")
|
||||
print(f" Avg R/trade: {avg_r:+.2f}R")
|
||||
print(f" Profit factor: {pf:.2f}")
|
||||
print(f" Max consec loss: {max_streak}")
|
||||
print(f" Max drawdown: {max_dd_r:.1f}R")
|
||||
print(f" Expectancy/day: {total_r / session_count:+.2f}R")
|
||||
print(f"{'='*60}")
|
||||
|
||||
# ── Trade log ──
|
||||
print(f"\n{'Date':>20} {'Dir':>5} {'Entry':>10} {'SL':>10} {'TP':>10}"
|
||||
f" {'Exit':>10} {'R':>6} {'Res':>4}")
|
||||
print("-" * 82)
|
||||
for t in all_trades:
|
||||
ts = str(t.entry_time)[:16] if t.entry_time else ""
|
||||
print(f"{ts:>20} {t.direction:>5} {t.entry:>10.1f} {t.stop:>10.1f}"
|
||||
f" {t.tp:>10.1f} {t.exit_price:>10.1f} {t.pnl_r:>+6.1f} {t.result:>4}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sym = sys.argv[1] if len(sys.argv) > 1 else "BTC/USDT:USDT"
|
||||
d = int(sys.argv[2]) if len(sys.argv) > 2 else 60
|
||||
backtest(sym, d)
|
||||
@@ -0,0 +1,198 @@
|
||||
"""Sweep leverage on 5m walk-forward for ETH and SOL (best from prior test)."""
|
||||
|
||||
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 Params, Trade, run_day
|
||||
|
||||
NY = ZoneInfo("America/New_York")
|
||||
|
||||
INITIAL_CAPITAL = 1_000.0
|
||||
RISK_PCT = 0.02
|
||||
TAKER_FEE = 0.00055
|
||||
TRAIN_RATIO = 0.5
|
||||
TIMEFRAME = "5m"
|
||||
OR_MINUTES = 15
|
||||
LEVERAGES = [1, 2, 5, 10, 20, 50]
|
||||
|
||||
GRID = {
|
||||
"rr_ratio": [2.0, 2.5, 3.0],
|
||||
"max_trades": [1, 2, 3],
|
||||
"min_range_pct": [0.0, 0.1, 0.2],
|
||||
"min_fvg_pct": [0.0, 0.02, 0.05],
|
||||
"first_fvg_only": [False, True],
|
||||
"fvg_expiry": [6, 12],
|
||||
}
|
||||
|
||||
|
||||
def trades_to_pnl(trades: list[Trade], capital: float,
|
||||
leverage: int) -> list[dict]:
|
||||
"""Convert trades to dollar PnL with leverage constraint."""
|
||||
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
|
||||
|
||||
# Risk-based position size
|
||||
pos_size = risk_dollar / risk_dist
|
||||
pos_value = pos_size * t.entry
|
||||
|
||||
# Leverage cap: max position = equity * leverage
|
||||
max_pos = equity * leverage
|
||||
if pos_value > max_pos:
|
||||
pos_size = max_pos / t.entry
|
||||
pos_value = max_pos
|
||||
|
||||
# Gross PnL
|
||||
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
|
||||
|
||||
# Liquidation check (simplified): loss > margin
|
||||
margin = pos_value / leverage
|
||||
if -pnl_net >= margin * 0.9: # 90% of margin = liq
|
||||
pnl_net = -margin * 0.9
|
||||
equity += pnl_net
|
||||
results.append({
|
||||
"pnl_net": pnl_net, "commission": commission,
|
||||
"equity_after": equity, "entry_time": t.entry_time,
|
||||
"liquidated": True,
|
||||
})
|
||||
continue
|
||||
|
||||
equity += pnl_net
|
||||
results.append({
|
||||
"pnl_net": pnl_net, "commission": commission,
|
||||
"equity_after": equity, "entry_time": t.entry_time,
|
||||
"liquidated": False,
|
||||
})
|
||||
return results
|
||||
|
||||
|
||||
def compute_metrics(dollar_trades: list[dict], initial_capital: float,
|
||||
n_days: int) -> dict:
|
||||
if not dollar_trades:
|
||||
return {"trades": 0, "wr": 0, "total_pnl": 0, "total_ret": 0,
|
||||
"sharpe": 0, "max_dd": 0, "total_comm": 0, "monthly_pnl": 0,
|
||||
"liquidations": 0}
|
||||
|
||||
pnls = [t["pnl_net"] for t in dollar_trades]
|
||||
wins = [p for p in pnls if p > 0]
|
||||
total_pnl = sum(pnls)
|
||||
total_comm = sum(t["commission"] for t in dollar_trades)
|
||||
liqs = sum(1 for t in dollar_trades if t.get("liquidated"))
|
||||
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)
|
||||
for t in dollar_trades:
|
||||
ts = t["entry_time"]
|
||||
if ts is not None:
|
||||
day_idx = (ts.astimezone(NY).date() - dollar_trades[0]["entry_time"].astimezone(NY).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(252)) 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,
|
||||
"liquidations": liqs,
|
||||
}
|
||||
|
||||
|
||||
def _run_on_dates(df: pd.DataFrame, params: Params) -> list[Trade]:
|
||||
all_trades = []
|
||||
for _, day_df in df.groupby("ny_date"):
|
||||
all_trades.extend(run_day(day_df.reset_index(drop=True), params, OR_MINUTES))
|
||||
return all_trades
|
||||
|
||||
|
||||
def find_best_params(df_train: pd.DataFrame) -> Params:
|
||||
keys = list(GRID.keys())
|
||||
combos = list(itertools.product(*GRID.values()))
|
||||
best_score = -999
|
||||
best_kw = {}
|
||||
for vals in combos:
|
||||
kw = dict(zip(keys, vals))
|
||||
p = Params(**kw)
|
||||
trades = _run_on_dates(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
|
||||
return Params(**best_kw) if best_kw else Params()
|
||||
|
||||
|
||||
def run_leverage_sweep(symbol: str, days: int = 60):
|
||||
df = fetch_candles(symbol, days, TIMEFRAME)
|
||||
df["ny_date"] = df["timestamp"].dt.tz_convert(NY).dt.date
|
||||
|
||||
dates = sorted(df["ny_date"].unique())
|
||||
split = int(len(dates) * TRAIN_RATIO)
|
||||
train_dates = set(dates[:split])
|
||||
test_dates = set(dates[split:])
|
||||
|
||||
df_train = df[df["ny_date"].isin(train_dates)]
|
||||
df_test = df[df["ny_date"].isin(test_dates)]
|
||||
|
||||
print(f"\n{'='*70}")
|
||||
print(f" Leverage Sweep | {symbol} | {TIMEFRAME} | {days}d")
|
||||
print(f"{'='*70}")
|
||||
|
||||
# Optimize once
|
||||
best_params = find_best_params(df_train)
|
||||
print(f" Best params: {best_params}")
|
||||
|
||||
# Get raw trades once
|
||||
test_trades = _run_on_dates(df_test, best_params)
|
||||
n_test = len(test_dates)
|
||||
|
||||
print(f"\n {'Lev':>4s} {'Trades':>7s} {'WR%':>6s} {'PnL':>10s} {'Ret%':>8s} "
|
||||
f"{'Sharpe':>7s} {'MaxDD':>7s} {'$/mo':>9s} {'Comm':>8s} {'Liqs':>5s}")
|
||||
print(f" {'-'*72}")
|
||||
|
||||
for lev in LEVERAGES:
|
||||
dollar = trades_to_pnl(test_trades, INITIAL_CAPITAL, lev)
|
||||
m = compute_metrics(dollar, INITIAL_CAPITAL, n_test)
|
||||
print(f" {lev:>4d}x {m['trades']:>7d} {m['wr']:>5.1f}% ${m['total_pnl']:>+9,.2f} "
|
||||
f"{m['total_ret']:>+7.1f}% {m['sharpe']:>7.2f} {m['max_dd']:>6.1f}% "
|
||||
f"${m.get('monthly_pnl',0):>+8,.2f} ${m['total_comm']:>7,.2f} "
|
||||
f"{m.get('liquidations',0):>5d}")
|
||||
|
||||
|
||||
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:
|
||||
run_leverage_sweep(sym, 60)
|
||||
+266
@@ -0,0 +1,266 @@
|
||||
"""Walk-forward backtest: optimize on in-sample, test on out-of-sample.
|
||||
|
||||
Adapted from remizov-trader backtest_4h.py approach:
|
||||
- Train/test split by date (50/50)
|
||||
- Realistic Bybit futures costs (taker 0.055% per side)
|
||||
- Dollar-based position sizing and PnL
|
||||
- Sharpe ratio, max drawdown %, equity curve
|
||||
"""
|
||||
|
||||
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 Params, Trade, run_day
|
||||
|
||||
NY = ZoneInfo("America/New_York")
|
||||
|
||||
# ── Config ───────────────────────────────────────────────────────────
|
||||
INITIAL_CAPITAL = 1_000.0
|
||||
RISK_PCT = 0.02 # 2% risk per trade
|
||||
TAKER_FEE = 0.00055 # Bybit linear futures taker fee (0.055%)
|
||||
TRAIN_RATIO = 0.5 # first 50% days = in-sample
|
||||
TIMEFRAME = "5m"
|
||||
OR_MINUTES = 15 # opening range duration (3 x 5m candles)
|
||||
|
||||
GRID = {
|
||||
"rr_ratio": [2.0, 2.5, 3.0],
|
||||
"max_trades": [1, 2, 3],
|
||||
"min_range_pct": [0.0, 0.1, 0.2],
|
||||
"min_fvg_pct": [0.0, 0.02, 0.05],
|
||||
"first_fvg_only": [False, True],
|
||||
"fvg_expiry": [6, 12], # bars (6=30min, 12=1h on 5m TF)
|
||||
}
|
||||
|
||||
|
||||
# ── Dollar PnL ───────────────────────────────────────────────────────
|
||||
|
||||
def trades_to_pnl(trades: list[Trade], capital: float) -> list[dict]:
|
||||
"""Convert R-based trades to dollar PnL with commission."""
|
||||
results = []
|
||||
equity = capital
|
||||
for t in trades:
|
||||
risk_dollar = equity * RISK_PCT
|
||||
risk_dist = abs(t.entry - t.stop)
|
||||
if risk_dist <= 0:
|
||||
continue
|
||||
pos_size = risk_dollar / risk_dist
|
||||
pos_value = pos_size * t.entry
|
||||
|
||||
# Gross PnL
|
||||
if t.direction == "long":
|
||||
gross = pos_size * (t.exit_price - t.entry)
|
||||
else:
|
||||
gross = pos_size * (t.entry - t.exit_price)
|
||||
|
||||
# Commission: taker on entry + exit
|
||||
commission = pos_value * TAKER_FEE * 2
|
||||
pnl_net = gross - commission
|
||||
|
||||
equity += pnl_net
|
||||
results.append({
|
||||
"pnl_net": pnl_net,
|
||||
"pnl_gross": gross,
|
||||
"commission": commission,
|
||||
"equity_after": equity,
|
||||
"entry_time": t.entry_time,
|
||||
})
|
||||
return results
|
||||
|
||||
|
||||
# ── Metrics (from remizov-trader) ────────────────────────────────────
|
||||
|
||||
def compute_metrics(dollar_trades: list[dict], initial_capital: float,
|
||||
n_days: int) -> dict:
|
||||
"""Compute trading metrics: Sharpe, max DD%, PnL, WR."""
|
||||
if not dollar_trades:
|
||||
return {"trades": 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 & max drawdown
|
||||
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())
|
||||
|
||||
# Sharpe ratio (daily returns, annualized)
|
||||
if len(pnls) > 1 and n_days > 1:
|
||||
daily_pnl = np.zeros(n_days)
|
||||
for t in dollar_trades:
|
||||
ts = t["entry_time"]
|
||||
if ts is not None:
|
||||
day_idx = (ts.astimezone(NY).date() - dollar_trades[0]["entry_time"].astimezone(NY).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(252)) 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,
|
||||
}
|
||||
|
||||
|
||||
# ── Grid search on in-sample ─────────────────────────────────────────
|
||||
|
||||
def _run_on_dates(df: pd.DataFrame, params: Params) -> list[Trade]:
|
||||
"""Run strategy on pre-filtered dataframe, return trades."""
|
||||
all_trades = []
|
||||
for _, day_df in df.groupby("ny_date"):
|
||||
all_trades.extend(run_day(day_df.reset_index(drop=True), params, OR_MINUTES))
|
||||
return all_trades
|
||||
|
||||
|
||||
def _quick_score(trades: list[Trade]) -> float:
|
||||
"""Quick R-based score for grid search ranking."""
|
||||
if len(trades) < 3:
|
||||
return -999
|
||||
return sum(t.pnl_r for t in trades)
|
||||
|
||||
|
||||
def find_best_params(df_train: pd.DataFrame) -> Params:
|
||||
"""Grid search on training data, return best Params."""
|
||||
keys = list(GRID.keys())
|
||||
combos = list(itertools.product(*GRID.values()))
|
||||
best_score = -999
|
||||
best_kw = {}
|
||||
|
||||
for vals in combos:
|
||||
kw = dict(zip(keys, vals))
|
||||
p = Params(**kw)
|
||||
trades = _run_on_dates(df_train, p)
|
||||
score = _quick_score(trades)
|
||||
if score > best_score:
|
||||
best_score = score
|
||||
best_kw = kw
|
||||
|
||||
return Params(**best_kw) if best_kw else Params()
|
||||
|
||||
|
||||
# ── Main walk-forward ─────────────────────────────────────────────────
|
||||
|
||||
def walk_forward(symbol: str, days: int = 60):
|
||||
"""Walk-forward: optimize on first half, test on second half."""
|
||||
df = fetch_candles(symbol, days, TIMEFRAME)
|
||||
df["ny_date"] = df["timestamp"].dt.tz_convert(NY).dt.date
|
||||
|
||||
dates = sorted(df["ny_date"].unique())
|
||||
split = int(len(dates) * TRAIN_RATIO)
|
||||
train_dates = set(dates[:split])
|
||||
test_dates = set(dates[split:])
|
||||
|
||||
df_train = df[df["ny_date"].isin(train_dates)]
|
||||
df_test = df[df["ny_date"].isin(test_dates)]
|
||||
|
||||
print(f"\n{'='*60}")
|
||||
print(f" Walk-Forward | {symbol} | {days}d | {TIMEFRAME} | OR={OR_MINUTES}m")
|
||||
print(f"{'='*60}")
|
||||
print(f" Train: {len(train_dates)} days ({dates[0]} → {dates[split-1]})")
|
||||
print(f" Test: {len(test_dates)} days ({dates[split]} → {dates[-1]})")
|
||||
print(f" Capital: ${INITIAL_CAPITAL:,.0f} | Risk: {RISK_PCT*100:.0f}%")
|
||||
|
||||
# Phase 1: optimize on train
|
||||
print(f"\n Phase 1: Grid search ({len(list(itertools.product(*GRID.values())))} combos)...")
|
||||
best_params = find_best_params(df_train)
|
||||
print(f" Best in-sample params: {best_params}")
|
||||
|
||||
# In-sample result
|
||||
train_trades = _run_on_dates(df_train, best_params)
|
||||
train_dollar = trades_to_pnl(train_trades, INITIAL_CAPITAL)
|
||||
train_m = compute_metrics(train_dollar, INITIAL_CAPITAL, len(train_dates))
|
||||
|
||||
# Phase 2: test on out-of-sample
|
||||
print(f"\n Phase 2: Out-of-sample test...")
|
||||
test_trades = _run_on_dates(df_test, best_params)
|
||||
test_dollar = trades_to_pnl(test_trades, INITIAL_CAPITAL)
|
||||
test_m = compute_metrics(test_dollar, INITIAL_CAPITAL, len(test_dates))
|
||||
|
||||
# Print results
|
||||
_print_comparison(train_m, test_m, symbol)
|
||||
|
||||
return {"train": train_m, "test": test_m, "params": best_params}
|
||||
|
||||
|
||||
def _print_comparison(train: dict, test: dict, symbol: str):
|
||||
"""Print in-sample vs out-of-sample comparison."""
|
||||
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.get('total_comm',0):,.2f}", f"${test.get('total_comm',0):,.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.get('monthly_pnl',0):+,.2f}", f"${test.get('monthly_pnl',0):+,.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:
|
||||
degradation = ""
|
||||
if train["total_pnl"] > 0 and test["total_pnl"] > 0:
|
||||
deg = (1 - test["total_pnl"] / train["total_pnl"]) * 100
|
||||
degradation = f" | Degradation: {deg:.0f}%"
|
||||
print(f" OOS PnL: ${test['total_pnl']:+,.2f} ({test['total_ret']:+.1f}%){degradation}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
symbols = sys.argv[1:] if len(sys.argv) > 1 else [
|
||||
"BTC/USDT:USDT", "ETH/USDT:USDT", "SOL/USDT:USDT"
|
||||
]
|
||||
days = 60
|
||||
all_results = {}
|
||||
for sym in symbols:
|
||||
all_results[sym] = walk_forward(sym, days)
|
||||
|
||||
# Summary
|
||||
if len(all_results) > 1:
|
||||
print(f"\n\n{'='*70}")
|
||||
print(f" WALK-FORWARD SUMMARY | ${INITIAL_CAPITAL:,.0f} capital, {RISK_PCT*100:.0f}% risk")
|
||||
print(f"{'='*70}")
|
||||
print(f" {'Symbol':<16s} {'OOS PnL':>10s} {'OOS Ret':>8s} {'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']:>+7.1f}% "
|
||||
f"{t['sharpe']:>8.2f} {t['max_dd']:>6.1f}% {t['trades']:>7d} "
|
||||
f"{t['wr']:>5.1f}%")
|
||||
@@ -0,0 +1,58 @@
|
||||
"""Fetch and cache OHLCV candles from Bybit."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
import ccxt
|
||||
import pandas as pd
|
||||
|
||||
CACHE_DIR = Path(__file__).parent / "cache"
|
||||
|
||||
# Bar duration in ms per timeframe
|
||||
_BAR_MS = {"1m": 60_000, "5m": 300_000, "15m": 900_000}
|
||||
|
||||
|
||||
def fetch_candles(symbol: str = "BTC/USDT:USDT", days: int = 60,
|
||||
timeframe: str = "1m") -> pd.DataFrame:
|
||||
"""Fetch candles for any supported timeframe, cache to CSV."""
|
||||
CACHE_DIR.mkdir(exist_ok=True)
|
||||
tag = symbol.replace("/", "_").replace(":", "_")
|
||||
cache = CACHE_DIR / f"{tag}_{days}d_{timeframe}.csv"
|
||||
|
||||
if cache.exists():
|
||||
df = pd.read_csv(cache, parse_dates=["timestamp"])
|
||||
df["timestamp"] = df["timestamp"].dt.tz_localize("UTC") if df["timestamp"].dt.tz is None else df["timestamp"]
|
||||
print(f"Cache: {len(df)} candles from {cache.name}")
|
||||
return df
|
||||
|
||||
ex = ccxt.bybit({"enableRateLimit": True, "options": {"defaultType": "linear"}})
|
||||
ex.load_markets()
|
||||
|
||||
bar_ms = _BAR_MS.get(timeframe, 60_000)
|
||||
since = int((datetime.now(timezone.utc).timestamp() - days * 86400) * 1000)
|
||||
rows = []
|
||||
while True:
|
||||
batch = ex.fetch_ohlcv(symbol, timeframe, since=since, limit=1000)
|
||||
if not batch:
|
||||
break
|
||||
rows.extend(batch)
|
||||
since = batch[-1][0] + bar_ms
|
||||
print(f"\r {len(rows):,} candles...", end="", flush=True)
|
||||
if len(batch) < 1000:
|
||||
break
|
||||
|
||||
print(f"\n Total: {len(rows):,}")
|
||||
df = pd.DataFrame(rows, columns=["timestamp", "open", "high", "low", "close", "volume"])
|
||||
df["timestamp"] = pd.to_datetime(df["timestamp"], unit="ms", utc=True)
|
||||
df.drop_duplicates(subset="timestamp", inplace=True)
|
||||
df.sort_values("timestamp", inplace=True)
|
||||
df.reset_index(drop=True, inplace=True)
|
||||
df.to_csv(cache, index=False)
|
||||
return df
|
||||
|
||||
|
||||
def fetch_1m(symbol: str = "BTC/USDT:USDT", days: int = 60) -> pd.DataFrame:
|
||||
"""Backward-compatible wrapper."""
|
||||
return fetch_candles(symbol, days, "1m")
|
||||
+118
@@ -0,0 +1,118 @@
|
||||
"""Grid search over strategy parameters for multiple symbols."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import itertools
|
||||
import sys
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from data import fetch_1m
|
||||
from strategy import Params, run_day
|
||||
|
||||
NY = ZoneInfo("America/New_York")
|
||||
|
||||
# ── Parameter grid ──────────────────────────────────────────────────
|
||||
GRID = {
|
||||
"rr_ratio": [2.0, 2.5, 3.0],
|
||||
"max_trades": [1, 2, 3],
|
||||
"min_range_pct": [0.0, 0.1, 0.2], # % of price
|
||||
"min_fvg_pct": [0.0, 0.02, 0.05], # % of price
|
||||
"min_risk_pct": [0.0, 0.01, 0.03], # % of price
|
||||
"first_fvg_only": [False, True],
|
||||
"fvg_expiry": [15, 30],
|
||||
}
|
||||
# Total combos: 3*3*3*3*3*2*2 = 972
|
||||
|
||||
|
||||
def _run_backtest(df: pd.DataFrame, params: Params) -> dict:
|
||||
"""Run backtest on preloaded data, return stats dict."""
|
||||
df["ny_date"] = df["timestamp"].dt.tz_convert(NY).dt.date
|
||||
all_trades = []
|
||||
for _, day_df in df.groupby("ny_date"):
|
||||
all_trades.extend(run_day(day_df.reset_index(drop=True), params))
|
||||
|
||||
total = len(all_trades)
|
||||
if total == 0:
|
||||
return {"trades": 0, "wr": 0, "total_r": 0, "pf": 0, "max_dd": 0, "avg_r": 0}
|
||||
|
||||
wins = sum(1 for t in all_trades if t.result == "win")
|
||||
losses = total - wins
|
||||
wr = wins / total * 100
|
||||
total_r = sum(t.pnl_r for t in all_trades)
|
||||
avg_r = total_r / total
|
||||
pf = (wins * params.rr_ratio) / max(losses, 1)
|
||||
|
||||
# Max drawdown in R
|
||||
equity = peak = 0.0
|
||||
max_dd = 0.0
|
||||
for t in all_trades:
|
||||
equity += t.pnl_r
|
||||
peak = max(peak, equity)
|
||||
max_dd = max(max_dd, peak - equity)
|
||||
|
||||
return {
|
||||
"trades": total, "wins": wins, "wr": wr,
|
||||
"total_r": total_r, "avg_r": avg_r, "pf": pf, "max_dd": max_dd,
|
||||
}
|
||||
|
||||
|
||||
def optimize(symbol: str, days: int = 60):
|
||||
print(f"\n{'='*70}")
|
||||
print(f" Optimizing {symbol} | {days} days")
|
||||
print(f"{'='*70}")
|
||||
|
||||
df = fetch_1m(symbol, days)
|
||||
# Pre-compute ny_date once
|
||||
df["ny_date"] = df["timestamp"].dt.tz_convert(NY).dt.date
|
||||
|
||||
keys = list(GRID.keys())
|
||||
combos = list(itertools.product(*GRID.values()))
|
||||
print(f" {len(combos)} parameter combinations\n")
|
||||
|
||||
results = []
|
||||
for idx, vals in enumerate(combos):
|
||||
kw = dict(zip(keys, vals))
|
||||
p = Params(**kw)
|
||||
stats = _run_backtest(df, p)
|
||||
stats["params"] = kw
|
||||
results.append(stats)
|
||||
if (idx + 1) % 100 == 0:
|
||||
print(f"\r {idx+1}/{len(combos)}...", end="", flush=True)
|
||||
|
||||
print(f"\r {len(combos)}/{len(combos)} done. ")
|
||||
|
||||
# Sort by total_r, then profit factor
|
||||
results.sort(key=lambda x: (x["total_r"], x["pf"]), reverse=True)
|
||||
|
||||
# Show top 10
|
||||
print(f"\n {'#':>3} {'Trades':>6} {'WR%':>5} {'TotalR':>7} {'PF':>5} "
|
||||
f"{'MaxDD':>6} {'AvgR':>6} Params")
|
||||
print(" " + "-" * 90)
|
||||
for i, r in enumerate(results[:15]):
|
||||
if r["trades"] < 5:
|
||||
continue
|
||||
p = r["params"]
|
||||
short = (f"rr={p['rr_ratio']} mt={p['max_trades']} "
|
||||
f"rng={p['min_range_pct']} fvg={p['min_fvg_pct']} "
|
||||
f"risk={p['min_risk_pct']} 1st={p['first_fvg_only']} "
|
||||
f"exp={p['fvg_expiry']}")
|
||||
print(f" {i+1:>3} {r['trades']:>6} {r['wr']:>5.1f} {r['total_r']:>+7.1f} "
|
||||
f"{r['pf']:>5.2f} {r['max_dd']:>6.1f} {r['avg_r']:>+6.2f} {short}")
|
||||
|
||||
# Best result
|
||||
best = results[0]
|
||||
print(f"\n BEST: {best['total_r']:+.1f}R | WR={best['wr']:.1f}% | "
|
||||
f"PF={best['pf']:.2f} | {best['trades']} trades")
|
||||
print(f" Params: {best['params']}")
|
||||
return results
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
symbols = sys.argv[1:] if len(sys.argv) > 1 else [
|
||||
"BTC/USDT:USDT", "ETH/USDT:USDT", "SOL/USDT:USDT"
|
||||
]
|
||||
days = 60
|
||||
for sym in symbols:
|
||||
optimize(sym, days)
|
||||
@@ -0,0 +1,2 @@
|
||||
ccxt>=4.0
|
||||
pandas>=2.0
|
||||
+204
@@ -0,0 +1,204 @@
|
||||
"""Opening Range Breakout + FVG + Engulfing scalping strategy.
|
||||
|
||||
Configurable filters for optimization.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
import pandas as pd
|
||||
|
||||
NY = ZoneInfo("America/New_York")
|
||||
|
||||
|
||||
@dataclass
|
||||
class Params:
|
||||
rr_ratio: float = 3.0 # risk:reward (1:N)
|
||||
max_trades: int = 2 # max trades per session
|
||||
fvg_expiry: int = 30 # FVG valid N bars
|
||||
min_range_pct: float = 0.0 # min range as % of price (0 = off)
|
||||
min_fvg_pct: float = 0.0 # min FVG gap as % of price (0 = off)
|
||||
min_risk_pct: float = 0.0 # min stop distance as % of price (0 = off)
|
||||
session_end_h: int = 11 # stop entering after this hour (NY)
|
||||
session_end_m: int = 0
|
||||
first_fvg_only: bool = False # only trade the first FVG of the day
|
||||
|
||||
|
||||
@dataclass
|
||||
class FVG:
|
||||
direction: str
|
||||
zone_low: float
|
||||
zone_high: float
|
||||
bar_idx: int
|
||||
used: bool = False
|
||||
|
||||
|
||||
@dataclass
|
||||
class Trade:
|
||||
direction: str
|
||||
entry: float
|
||||
stop: float
|
||||
tp: float
|
||||
entry_time: object = None
|
||||
exit_price: float = 0.0
|
||||
exit_time: object = None
|
||||
result: str = ""
|
||||
pnl_r: float = 0.0
|
||||
|
||||
|
||||
def get_opening_range(df: pd.DataFrame,
|
||||
or_minutes: int = 5) -> tuple[float, float] | None:
|
||||
"""Get opening range high/low. or_minutes: range duration from 9:30."""
|
||||
ny = df["timestamp"].dt.tz_convert(NY)
|
||||
or_end = 30 + or_minutes # minutes past the hour
|
||||
mask = (ny.dt.hour == 9) & (ny.dt.minute >= 30) & (ny.dt.minute < or_end)
|
||||
rc = df[mask]
|
||||
if len(rc) < 1:
|
||||
return None
|
||||
return float(rc["high"].max()), float(rc["low"].min())
|
||||
|
||||
|
||||
def run_day(df_day: pd.DataFrame, p: Params | None = None,
|
||||
or_minutes: int = 5) -> list[Trade]:
|
||||
p = p or Params()
|
||||
rng = get_opening_range(df_day, or_minutes)
|
||||
if rng is None:
|
||||
return []
|
||||
rh, rl = rng
|
||||
mid = (rh + rl) / 2
|
||||
|
||||
# Filter: min range size
|
||||
if p.min_range_pct > 0 and mid > 0:
|
||||
if (rh - rl) / mid < p.min_range_pct / 100:
|
||||
return []
|
||||
|
||||
ny = df_day["timestamp"].dt.tz_convert(NY)
|
||||
or_end_min = 30 + or_minutes
|
||||
# After opening range: from or_end_min to 16:00 NY
|
||||
if or_end_min < 60:
|
||||
mask = (((ny.dt.hour == 9) & (ny.dt.minute >= or_end_min)) | (ny.dt.hour >= 10)) & (ny.dt.hour < 16)
|
||||
else:
|
||||
mask = (ny.dt.hour >= 10) & (ny.dt.hour < 16)
|
||||
after = df_day[mask].reset_index(drop=True)
|
||||
if len(after) < 5:
|
||||
return []
|
||||
|
||||
trades: list[Trade] = []
|
||||
fvgs: list[FVG] = []
|
||||
active: Trade | None = None
|
||||
trade_count = 0
|
||||
|
||||
for i in range(len(after)):
|
||||
c = after.iloc[i]
|
||||
c_ny = c["timestamp"].astimezone(NY)
|
||||
|
||||
# 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["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
|
||||
|
||||
# Max trades reached or past entry window
|
||||
if trade_count >= p.max_trades:
|
||||
continue
|
||||
in_window = (c_ny.hour < p.session_end_h
|
||||
or (c_ny.hour == p.session_end_h and c_ny.minute <= p.session_end_m))
|
||||
if not in_window:
|
||||
continue
|
||||
|
||||
# Detect FVG
|
||||
if i >= 2:
|
||||
c0, c1, c2 = after.iloc[i-2], after.iloc[i-1], c
|
||||
fvg = None
|
||||
if c1["close"] > rh and c2["low"] > c0["high"]:
|
||||
fvg = FVG("bull", c0["high"], c2["low"], i)
|
||||
elif c1["close"] < rl and c2["high"] < c0["low"]:
|
||||
fvg = FVG("bear", c2["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 = after.iloc[i - 1]
|
||||
for fvg in fvgs:
|
||||
if fvg.used:
|
||||
continue
|
||||
# Prev candle must touch FVG zone
|
||||
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 = float(c["close"])
|
||||
stop = float(c["low"]) if fvg.direction == "bull" else float(c["high"])
|
||||
risk = abs(entry - stop)
|
||||
if risk <= 0:
|
||||
continue
|
||||
if p.min_risk_pct > 0 and mid > 0 and risk / mid < p.min_risk_pct / 100:
|
||||
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
|
||||
|
||||
# Close open trade at session end
|
||||
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
|
||||
Reference in New Issue
Block a user