Dynamic Gap-Fill Mean Reversion Strategy: Trend & Volume Filters

EMA ATR RSI MEAN REVERSION GAP FILL Trend Filter VOLUME FILTER Trailing Stop
Created on: 2025-05-16 16:08:41 Modified on: 2025-05-16 16:10:56
Copy: 0 Number of hits: 329
avatar of ianzeng123 ianzeng123
2
Follow
319
Followers

 Dynamic Gap-Fill Mean Reversion Strategy: Trend & Volume Filters  Dynamic Gap-Fill Mean Reversion Strategy: Trend & Volume Filters

Overview

The Dynamic Gap-Fill Mean Reversion Strategy is a quantitative trading system specifically designed to target intraday gap-fill phenomena. The strategy is based on the natural tendency of markets to revert and fill significant gaps that occur. Operating on a 3-minute timeframe, the system utilizes specific price patterns, trend direction, and volume confirmation to filter high-probability trading opportunities. The system employs mean reversion principles and enhances trade success rate through multiple filters, including EMA trend filtering, volume confirmation, and RSI overbought filtering.

Strategy Principles

The core logic of the strategy revolves around gap detection and filling:

  1. Gap Detection Mechanism: The strategy first identifies intraday price gaps exceeding 0.5%. By comparing the previous trading day’s closing price with today’s opening price, it determines whether there is an upward or downward gap.

  2. Trend Confirmation: Using 50-period and 200-period Exponential Moving Averages (EMA) to determine the current market trend. Long trades are only considered when EMA50 is greater than EMA200; short trades are only considered when EMA50 is less than EMA200.

  3. Three-Candle Reversal Pattern: The strategy requires three consecutive candles to form a reversal pattern. For longs, an ascending pattern of close[2] < close[1] < close is needed; for shorts, a descending pattern of close[2] > close[1] > close is required.

  4. Volume Filtering: An optional volume filter ensures trades are only taken when volume is above the 20-period average, adding reliability to the signals.

  5. RSI Filtering: For short trades, an additional condition of RSI > 60 is added, ensuring the market is in a relatively overbought state, improving the quality of short signals.

Entry conditions combine all the above factors: - Long: Gap down + Three-candle up pattern + Volume confirmation + Uptrend - Short: Gap up + Three-candle down pattern + Volume confirmation + Downtrend + RSI overbought

Strategy Advantages

  1. Clear Market Anomaly Identification: The strategy focuses on a specific market anomaly—price gaps—which is a statistically significant market phenomenon providing a predictive edge.

  2. Multiple Confirmation Mechanisms: By combining gaps, trend filtering, volume confirmation, and price patterns, the strategy significantly reduces the possibility of false signals.

  3. Precise Risk Management: Uses ATR to set stop losses and profit targets, ensuring risk management adapts to changes in market volatility. A maximum dollar stop loss amount is set, effectively controlling risk exposure per trade.

  4. Dynamic Trailing Stop: Once a trade reaches a 2×ATR profit level, a trailing stop can be activated, allowing profitable trades to continue running while securing a portion of the profits.

  5. Flexible Parameter Settings: The strategy offers multiple adjustable parameters (gap size, ATR multipliers, maximum stop loss amount, etc.) that can be optimized according to the trader’s risk preferences and market conditions.

  6. Time Limit Protection: By setting a maximum holding time (50 bars), the strategy prevents trades from remaining in a losing position for extended periods, optimizing capital efficiency.

  7. Alignment with Market Microstructure: The strategy design aligns with market microstructure, focusing on intraday trading and avoiding overnight risk.

Strategy Risks

  1. Moderate Win Rate: The strategy’s approximately 46% win rate means slightly more losing trades than winning ones. While profitable overall, this may require good psychological resilience during consecutive loss periods.

  2. Market Dependency: The strategy explicitly states it’s only suitable for NASDAQ (US100) 3-minute charts, not tested or optimized for other assets or timeframes. This limits the strategy’s application range.

  3. Parameter Sensitivity: Like most quantitative strategies, performance may be highly sensitive to parameter selection. Over-optimization might lead to backtest performance that doesn’t translate well to live trading.

  4. Limited Trading Frequency: Executing only one trade per day limits profit potential, especially on days with lower volatility where other opportunities might be missed.

  5. Gap Occurrence Frequency Risk: The strategy relies on the occurrence of gaps of a specific size, which might lead to extended periods without trading signals during calm market periods.

  6. Strategy Decay Risk: As more traders employ similar strategies, the gap-filling effect may diminish, leading to reduced strategy efficiency.

Mitigation Measures: - Implement strict money management, risking no more than 1-2% of account per trade - Regularly revalidate and optimize strategy parameters - Consider adjusting gap thresholds under different market conditions - Allow sufficient time to monitor strategy performance in live trading

Strategy Optimization Directions

  1. Enhanced Trend Filtering: The current strategy uses simple EMA crossovers as trend indicators. Consider integrating more sophisticated trend identification methods, such as ADX (Average Directional Index) or multi-timeframe trend analysis, to improve filtering quality.

  2. Optimized Entry Timing: The current three-candle reversal pattern may be overly simplistic. Consider adding technical confirmations such as candlestick formations, support/resistance levels, or price action analysis to optimize entry timing.

  3. Dynamic Stop-Loss and Take-Profit Targets: While using fixed ATR multipliers is reasonable, implementing dynamic adjustments based on market volatility or intraday timing could be beneficial. For example, increasing ATR multipliers during high volatility periods or adjusting risk parameters based on the trading session.

  4. Machine Learning Enhancement: Analyzing historical gap-fill success rate features (such as gap size, market conditions, timing, etc.) through machine learning models could potentially further improve strategy performance.

  5. Increased Trading Frequency: Consider modifying the strategy to allow multiple trades within the same trading day, especially when a previous trade has concluded and a new valid signal appears. This may increase overall returns but should be tested carefully to ensure it doesn’t introduce overtrading.

  6. Related Market Signal Integration: Consider integrating signals from related markets (such as futures, ETFs, or related sector indices) as confirmations. This may provide additional informational edge, especially in determining whether a gap will be filled.

  7. Time-Based Filtering: Markets may behave differently during different time periods. Adding filters based on trading time might enhance strategy performance, such as avoiding high-volatility periods at market open and close.

Summary

The Dynamic Gap-Fill Mean Reversion Strategy is a carefully designed intraday trading system focused on exploiting the statistical tendency of markets to revert and fill gaps. The strategy combines gap detection, trend confirmation, volume filtering, and price pattern recognition to create a multi-layered trading decision framework.

The core strengths of the strategy lie in its clearly defined entry rules, ATR-based risk management, and multiple confirmation mechanisms. Despite a moderate win rate (approximately 46%), the strategy manages to generate positive returns in backtesting through precise risk-reward settings (2:1 risk-reward ratio).

The strategy is particularly suitable for traders seeking to capitalize on specific market anomalies, especially those interested in intraday NASDAQ trading. However, potential users should be aware of the strategy’s limitations, including market dependency and parameter sensitivity.

By implementing the suggested optimization measures, particularly enhancing trend filters and improving entry timing, the strategy could potentially further improve its performance and robustness. As market conditions change, regular reassessment and adjustment of parameters will be key to maintaining long-term success.

Ultimately, this strategy represents a balanced quantitative trading approach, combining technical analysis and statistical concepts to capture specific behavioral patterns in the market in a systematic way.

Strategy source code
/*backtest
start: 2025-04-15 00:00:00
end: 2025-05-14 08:00:00
period: 2d
basePeriod: 2d
exchanges: [{"eid":"Futures_Binance","currency":"SOL_USDT"}]
*/

//@version=5
strategy("Gap Fill Mean Reversion Strategy – NASDAQ 3-Minute", overlay=true, default_qty_type=strategy.fixed, default_qty_value=1)

// === INPUTS ===
gapPct        = input.float(0.5, title="Minimum Gap (%)") / 100
useVolume     = input.bool(true, title="Use Volume Filter")
atrMultTP     = input.float(2.0, title="TP Multiplier (ATR)")
atrMultSL     = input.float(1.0, title="SL Multiplier (ATR)")
trailStartATR = input.float(2.0, title="Trailing Trigger (ATR)")
trailOffsetATR = input.float(1.0, title="Trailing Offset (ATR)")
maxSLusd      = input.float(100, title="Max Stop Loss (USD)")
maxBars       = input.int(50, title="Max Bars in Trade")

// === INDICATORS ===
ema50 = ta.ema(close, 50)
ema200 = ta.ema(close, 200)
trendUp = ema50 > ema200
trendDown = ema50 < ema200

rsi = ta.rsi(close, 14)
rsiShortCond = rsi > 60

// === GAP DETECTION ===
prevClose = request.security(syminfo.tickerid, "D", close[1])
todayOpen = request.security(syminfo.tickerid, "D", open)
gapUp     = todayOpen > prevClose * (1 + gapPct)
gapDown   = todayOpen < prevClose * (1 - gapPct)

// === VOLUME FILTER ===
volumeOK = not useVolume or (volume > ta.sma(volume, 20))

// === 3-CANDLE REVERSAL CONFIRMATION ===
threeDown = close[2] > close[1] and close[1] > close
threeUp   = close[2] < close[1] and close[1] < close

// === ENTRY CONDITIONS ===
longCond  = gapDown and threeUp and volumeOK and trendUp
shortCond = gapUp and threeDown and volumeOK and trendDown and rsiShortCond

// === ATR AND CALCULATIONS ===
atr = ta.atr(14)
entryPrice = strategy.opentrades > 0 ? strategy.opentrades.entry_price(0) : na
inLong = strategy.position_size > 0
inShort = strategy.position_size < 0

// === TRAILING STOP CONDITIONS ===
trailTrigger = atr * trailStartATR
trailOffset = atr * trailOffsetATR

longTrailCond = inLong and close > entryPrice + trailTrigger
shortTrailCond = inShort and close < entryPrice - trailTrigger

// === STOP LOSS DISTANCE (fixed USD limit applied) ===
slDistance = math.min(atr * atrMultSL, maxSLusd / syminfo.pointvalue)

// === ENTRIES ===
if (longCond)
    strategy.entry("Gap Long", strategy.long)

if (shortCond)
    strategy.entry("Gap Short", strategy.short)

// === EXITS ===
// LONG
if (longTrailCond)
    strategy.exit("Trail Long", from_entry="Gap Long", trail_points=trailOffset, trail_offset=trailOffset)
else if (inLong)
    strategy.exit("SL/TP Long", from_entry="Gap Long", stop=entryPrice - slDistance, limit=entryPrice + atr * atrMultTP)

// SHORT
if (shortTrailCond)
    strategy.exit("Trail Short", from_entry="Gap Short", trail_points=trailOffset, trail_offset=trailOffset)
else if (inShort)
    strategy.exit("SL/TP Short", from_entry="Gap Short", stop=entryPrice + slDistance, limit=entryPrice - atr * atrMultTP)

// === MAXIMUM TRADE DURATION CONTROL ===
strategy.close("Gap Long", when=inLong and (bar_index - strategy.opentrades.entry_bar_index(0)) >= maxBars)
strategy.close("Gap Short", when=inShort and (bar_index - strategy.opentrades.entry_bar_index(0)) >= maxBars)

// === VISUALS ===
plotshape(longCond, title="Long Signal", location=location.belowbar, style=shape.triangleup, color=color.green)
plotshape(shortCond, title="Short Signal", location=location.abovebar, style=shape.triangledown, color=color.red)
plot(ema50, color=color.orange, title="EMA 50")
plot(ema200, color=color.blue, title="EMA 200")