Все три подхода убыточны на 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>
212 lines
7.0 KiB
Python
212 lines
7.0 KiB
Python
"""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
|