Files
scalp-bot/strategy_volume.py
anorandClaude Opus 4.6 af9c763923 test: эксперименты — rolling range, multi-session, volume-spike
Все три подхода убыточны на OOS:
- Rolling 24/7: -68%...-90% (слишком много шума)
- Multi-session (Asia+London+NYSE): -18%...-28%
- Volume-spike: -39%...-55%

Вывод: FVG+Engulfing edge работает ТОЛЬКО на NYSE open (5m).
Чем больше сигналов вне NYSE — тем хуже результат.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 03:58:49 +10:00

190 lines
6.0 KiB
Python

"""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