Trend-Driven Pyramid Recovery EMA Crossover Strategy

EMA RSI Trailing Stop PYRAMID RECOVERY ENGULFING PATTERN STOP LOSS TAKE PROFIT
Created on: 2025-06-23 10:36:46 Modified on: 2025-06-23 10:36:46
Copy: 1 Number of hits: 238
avatar of ianzeng123 ianzeng123
2
Follow
319
Followers

 Trend-Driven Pyramid Recovery EMA Crossover Strategy  Trend-Driven Pyramid Recovery EMA Crossover Strategy

Overview

The Trend-Driven Pyramid Recovery EMA Crossover Strategy is a comprehensive quantitative trading system that combines trend following, reversal signal identification, and a pyramid-style position recovery mechanism. This strategy primarily relies on multiple Exponential Moving Average (EMA) crossovers to determine market trend direction, uses engulfing patterns to confirm entry signals, and incorporates pyramid-style capital management along with trailing stop functionality to create a complete trading loop. The strategy is specifically designed for the 4-hour timeframe and is suitable for trading major index markets, aiming to capture medium to long-term trend opportunities while providing risk management mechanisms.

Strategy Principles

This strategy primarily relies on three different period Exponential Moving Averages (EMA20, EMA50, and EMA200) to determine market trends, combined with candlestick patterns as entry signal triggers. Specifically, the strategy operates on the following principles:

  1. Trend Determination Mechanism:

    • Bullish trend condition: EMA20 > EMA50 > EMA200 and closing price > EMA200
    • Bearish trend condition: EMA20 < EMA50 < EMA200 and closing price < EMA200
  2. Entry Signals:

    • Trend following entry: Bullish engulfing pattern in a bullish trend
    • Reversal entry: Bearish engulfing pattern in a bearish trend (reverse thinking, as a reversal buy signal)
  3. Candle Filtering:

    • Eliminates indecision candles by calculating the ratio of body to overall range (body_ratio)
  4. Risk Management:

    • Fixed stop loss: Sets a stop loss at a fixed number of points
    • Fixed take profit: Sets take profit based on a multiple of stop loss points plus additional points
    • Trailing stop: Activates a trailing stop mechanism when profit reaches a specific number of points
  5. Pyramid Recovery Mechanism:

    • Increases position size based on the number of consecutive losses
    • Uses an exponential growth factor to adjust recovery positions
    • Sets maximum recovery levels to limit risk exposure

In the code implementation, three EMA indicators (20, 50, 200) are first defined, followed by candle filtering logic to eliminate indecision candles. The strategy has two buying conditions: trend buying and reversal buying. Trend buying requires EMA indicators to be in bullish alignment with a bullish engulfing pattern; reversal buying looks for bearish engulfing patterns in bearish-aligned markets as reversal signals. Stop loss and take profit levels are calculated based on fixed points, and trailing stops are activated after reaching specific profit levels. The pyramid recovery mechanism tracks trading results and exponentially increases position size after consecutive losses to quickly recover losses.

Strategy Advantages

  1. Comprehensive Market Adaptability: By including both trend following and reversal strategies, this system can find trading opportunities in different market environments, not limited to a single market condition.

  2. Multi-level Risk Management: Combines fixed stop loss, proportional take profit, and trailing stop loss triple protection mechanisms, protecting capital while not limiting potential returns.

  3. Pyramid Recovery Mechanism: Innovatively introduces a recovery system that scientifically increases positions to address consecutive loss situations, improving capital recovery efficiency. This mechanism can more quickly restore account equity after short-term drawdowns.

  4. Dynamic Position Management: Automatically adjusts position size based on trading performance, maintaining base positions during profitable periods and gradually increasing positions during losing periods to accelerate recovery.

  5. Combination of Technical Indicators and Patterns: Not only relies on technical indicators like moving averages but also incorporates candlestick pattern analysis, improving signal quality through multiple confirmations.

  6. Refined Entry Filtering: Filters out indecision candles through the body_ratio parameter, reducing false signal risk.

  7. Clear Visual Markers: Trade signals are intuitively displayed on the chart, facilitating backtest analysis and real-time monitoring.

Strategy Risks

  1. Rapid Position Expansion Risk: The pyramid recovery mechanism may lead to rapidly increasing positions during consecutive losses, potentially exacerbating losses if the market continues to be unfavorable. It is recommended to keep the max_recovery parameter within a reasonable range and adjust the base_position according to total capital.

  2. Lag During Trend Changes: Systems based on moving averages may react slowly during initial trend changes, resulting in delayed entry or exit timing. Consider incorporating more sensitive indicators such as RSI or MACD as auxiliary judgments.

  3. Fixed Point Stop Loss Risk: When market volatility changes, fixed point stop losses may be too wide or too narrow. Consider using ATR (Average True Range) to dynamically adjust stop loss distances.

  4. False Signals from Engulfing Patterns: Engulfing patterns may produce numerous false signals in ranging markets. Signal quality can be improved by adding volume confirmation or other auxiliary indicators.

  5. One-Directional Trading Limitation: The current strategy only executes long positions, potentially missing short opportunities in bear markets. Consider adding symmetrical short logic to adapt to bidirectional markets.

  6. Capital Management Pressure: At maximum recovery levels, substantial capital support is required. It is recommended to carefully set pyramid_factor and max_recovery parameters based on total account size.

Strategy Optimization Directions

  1. Dynamic Stop Loss Mechanism: Replace fixed point stop losses with ATR-based dynamic stop losses to better adapt to changes in market volatility. This can be implemented by calculating the current ATR value and setting the stop loss as the entry price minus a multiple of ATR.

  2. Add Short Logic: Incorporate symmetrical short conditions to make the strategy equally effective in declining markets. This can be implemented by copying the existing buy logic and reversing the conditions and entry direction.

  3. Improve Trend Determination: Introduce additional trend confirmation tools beyond EMA, such as ADX (Average Directional Index), to filter for stronger trend environments. Conditions like “ADX > 25” can be added as trend strength filters.

  4. Risk Ratio Optimization: Find optimal stop loss to take profit ratios based on historical backtest data, potentially requiring adjustments to the tp_multiplier parameter.

  5. Time Filters: Add time filtering conditions to avoid low volatility or unstable market periods. Especially for index trading, focus on active market sessions.

  6. Optimize Recovery System: Consider dynamically adjusting the pyramid_factor based on win rate and risk-reward ratio, rather than using a fixed multiplier. An adaptive adjustment mechanism based on recent performance can be implemented.

  7. Partial Profit Locking: After reaching certain profit levels, partially close positions to lock in some profits while maintaining remaining positions to track trends.

  8. Sentiment Indicator Integration: Introduce market sentiment indicators such as VIX or market breadth indicators, adjusting strategy parameters or pausing trading during extreme sentiment periods.

Summary

The Trend-Driven Pyramid Recovery EMA Crossover Strategy is a comprehensive system combining multiple trading concepts, primarily using EMA crossovers to determine trends, engulfing patterns to confirm signals, and an innovative pyramid recovery mechanism to manage risk and optimize capital efficiency. The core advantage of this strategy lies in its ability to adapt to different market environments while providing comprehensive risk control mechanisms.

This strategy is particularly suitable for traders who have a certain understanding of technical analysis and are willing to accept moderate risk in pursuit of long-term stable returns. Through implementation of the above optimization directions, the robustness and adaptability of the strategy can be further enhanced, especially in environments with significant market volatility changes. It’s worth noting that any quantitative strategy requires thorough backtest verification before actual application and parameter adjustment based on individual risk tolerance.

Overall, this strategy represents a typical method in modern quantitative trading that comprehensively applies technical analysis, risk management, and capital management, providing traders with an expandable framework that can be customized and optimized according to individual needs and market environments.

Strategy source code
/*backtest
start: 2024-06-23 00:00:00
end: 2025-06-21 08:00:00
period: 2d
basePeriod: 2d
exchanges: [{"eid":"Futures_Binance","currency":"DOGE_USDT"}]
*/

//@version=5
strategy("DJ30 Sniper (Trend + Reversal Buy + Pyramid Recovery + Trailing)", overlay=true, default_qty_value=1)

// === INPUTS ===
ema_fast = input.int(20, "EMA Fast")
ema_mid = input.int(50, "EMA Mid")
ema_slow = input.int(200, "EMA Slow")
rsi_period = input.int(14, "RSI Period")
sl_points = input.int(650, "Stop Loss (Points)")
tp_extra = input.int(200, "Extra TP Points")
tp_multiplier = 5
trailing_trigger = input.int(100, "Activate Trailing SL After (Points)")
trailing_stop = input.int(500, "Trailing Stop Size (Points)")

// === Recovery Settings ===
max_recovery = input.int(3, "Max Pyramid Levels", minval=1)
base_position = input.float(1000, "Base Order Size ($)")  // 🔁 doubled from 500 to 1000
pyramid_factor = input.float(2.0, "Recovery Multiplier")

// === MAs ===
ema20 = ta.ema(close, ema_fast)
ema50 = ta.ema(close, ema_mid)
ema200 = ta.ema(close, ema_slow)

// === Candle Filter ===
body = math.abs(close - open)
candle_range = high - low
body_ratio = candle_range != 0 ? body / candle_range : 0
not_indecision = body_ratio > 0.3

// === Buy Conditions ===
bull_trend = ema20 > ema50 and ema50 > ema200 and close > ema200
engulfing_bullish = close > open and close > close[1] and open < open[1]
buy_trend = bull_trend and engulfing_bullish and not_indecision

bear_trend = ema20 < ema50 and ema50 < ema200 and close < ema200
engulfing_bearish = close < open and close < close[1] and open > open[1]
buy_reversal = bear_trend and engulfing_bearish and not_indecision

buy_condition = buy_trend or buy_reversal

// === SL/TP ===
tp_points = sl_points * tp_multiplier + tp_extra
sl_buy = close - sl_points * syminfo.mintick
tp_buy = close + tp_points * syminfo.mintick

// === Recovery Logic ===
var int recovery_level = 0
var float position_size = base_position

if strategy.closedtrades > 0
    last_trade = strategy.closedtrades - 1
    last_profit = strategy.closedtrades.profit(last_trade)
    if last_profit > 0
        recovery_level := 0
    else
        recovery_level := math.min(recovery_level + 1, max_recovery)

position_size := base_position * math.pow(pyramid_factor, recovery_level)

// === Trade Execution ===
if buy_condition and strategy.opentrades == 0
    strategy.entry("Buy DJ30", strategy.long, qty=position_size)

// === Exit Logic ===
if strategy.opentrades > 0
    entry_price = strategy.opentrades.entry_price(0)
    unrealized_points = (close - entry_price) / syminfo.mintick

    if unrealized_points >= trailing_trigger
        strategy.exit("Trail Exit", from_entry="Buy DJ30", trail_points=trailing_stop, trail_offset=trailing_stop)
    else
        strategy.exit("Fixed Exit", from_entry="Buy DJ30", stop=sl_buy, limit=tp_buy)

// === Visual Markers ===
plotshape(buy_trend, location=location.belowbar, style=shape.labelup, color=color.green, text="TrendBuy")
plotshape(buy_reversal, location=location.belowbar, style=shape.labelup, color=color.orange, text="RevBuy")