Multi-Timeframe Trend Following and Reversal Strategy Based on Fibonacci and McGinley Dynamic Indicator
FMZQuant

FMZQuant @fmzquant

Joined:
Apr 25, 2024

Multi-Timeframe Trend Following and Reversal Strategy Based on Fibonacci and McGinley Dynamic Indicator

Publish Date: May 26
2 1

Image description

Image description

Overview
This strategy is a quantitative trading system that combines multiple technical analysis tools, focusing on identifying market trends and reversal points. It uses the daily chart (1440 minutes) as the base timeframe and generates trading signals by analyzing candlestick patterns, trend strength, and dynamic Fibonacci levels. The core of the strategy lies in identifying contextual engulfing patterns, using the McGinley Dynamic indicator, Exponential Moving Average (EMA), and Simple Moving Average (MA) crossovers to optimize entry and exit points. Additionally, the strategy employs adaptive stop-loss and dynamic profit-taking mechanisms to manage risk and optimize returns.

Strategy Principles
The strategy's working principles are based on several key components:

  1. Trend Detection Logic: Uses a fixed 160 candles for trend analysis, determining the overall market direction by counting consecutive up-trending and down-trending candles. When a sufficient number of consecutive up or down candles occur, the system marks it as an "Uptrend" or "Downtrend."

  2. Multi-Timeframe Analysis: The strategy allows users to select a secondary analysis timeframe (default is daily chart) to gain a more comprehensive market perspective. This approach helps confirm signals from the primary timeframe, reducing false signals.

  3. Engulfing Pattern Recognition: On the user-selected timeframe, the strategy identifies bullish and bearish engulfing patterns. These patterns are considered potential reversal signals, especially when aligned with the macro trend direction.

  4. Fibonacci Levels: The strategy calculates multiple Fibonacci levels (0, 0.382, 0.5, 0.618, 0.786, 1) based on highest and lowest prices, as well as extended levels (1.618 and -0.618). These levels serve as potential support and resistance points, helping determine entry and exit points.

  5. McGinley Dynamic Indicator: Uses the McGinley Dynamic indicator with adaptive sensitivity (alpha parameter) as a smooth reference for price action. This indicator adapts to price changes faster than traditional moving averages, providing more accurate market direction indications.

  6. Moving Average Crossovers: The strategy employs a 32-period EMA and a 64-period MA, using their crossovers as potential exit signals.

  7. Risk Management: Integrates percentage-based stop-loss and take-profit mechanisms, allowing users to customize risk parameters. Default settings are 10% for both stop-loss and take-profit levels.

Strategy Advantages

  1. Trend Confirmation: By analyzing price action across two timeframes simultaneously, the strategy reduces the likelihood of false signals. Trading signals are only generated when engulfing patterns align with the identified market trend.

  2. Dynamic Adaptability: The use of the McGinley Dynamic indicator allows the strategy to adapt quickly to changing market conditions. Users can control the indicator's sensitivity by adjusting the alpha parameter to adapt to different market volatilities.

  3. Multi-Level Confirmation: The strategy requires multiple conditions to be met simultaneously to generate trading signals, including trend confirmation, engulfing patterns, and price breakouts. This multi-level confirmation helps filter out low-quality trading signals.

  4. Customizable Risk Management: Users can adjust stop-loss and take-profit parameters according to their risk preferences, making the strategy adaptable to different market environments and trading styles.

  5. Fibonacci-Based Support and Resistance: Dynamically calculated Fibonacci levels provide objective support and resistance points, helping traders execute trades near technically significant price levels.

  6. Visual Assistance: The strategy marks identified trends and engulfing patterns on the chart, as well as draws Fibonacci levels, providing traders with clear visual references.

Strategy Risks

  1. Parameter Sensitivity: Strategy performance heavily depends on correct parameter settings, such as alpha value, timeframe selection, and number of candles for trend definition. Inappropriate parameter settings may lead to overtrading or missing important trading opportunities.

  2. Backtest vs. Real Trading Differences: The strategy may perform well in backtests but face challenges in live trading, such as slippage, liquidity issues, and execution delays.

  3. Market Condition Limitations: The strategy performs best under specific market conditions, such as clear trending markets. In ranging or highly volatile markets, it may generate more false signals and losing trades.

  4. Signal Conflicts: When signals from different timeframes or indicators contradict each other, the strategy may fail to provide clear trading direction, leading to indecision or inconsistent trading decisions.

  5. Over-Reliance on Technical Indicators: The strategy is entirely based on technical analysis, not considering fundamental factors or market sentiment. This may lead to inaccurate signals during major news or economic events.

  6. Stop-Loss Risk: Fixed percentage stop-losses may be insufficient for sudden large market movements, such as price gaps or flash crashes, potentially causing stop-loss failures and larger-than-expected losses.

Strategy Optimization Directions

  1. Dynamic Stop-Loss Mechanism: The current strategy uses fixed percentage stop-losses; this could be improved to a volatility-based dynamic stop-loss mechanism. For example, using the Average True Range (ATR) to adjust stop-loss distance, setting wider stops during higher volatility and tighter stops during lower volatility.

  2. Signal Weighting System: Implement a signal weighting system based on the strength of multiple confirmation factors. For instance, increase signal weight when engulfing patterns are more pronounced (larger in size) or occur near key Fibonacci levels, thereby optimizing position sizing.

  3. Market State Filter: Add a market state identification component that distinguishes between trending and ranging markets, adjusting strategy parameters and trading logic based on different market states. This can be implemented using the Average Directional Index (ADX) or similar indicators.

  4. Time Filter: Integrate trading time filters to avoid trading during periods of low market volatility or poor liquidity, such as before and after market opens and closes for certain markets.

  5. Multi-Indicator Integration: Consider integrating other complementary indicators beyond the existing ones, such as the Relative Strength Index (RSI), stochastic oscillator, or Bollinger Bands, to gain a more comprehensive market perspective.

  6. Adaptive Parameters: Implement machine learning algorithms to dynamically adjust strategy parameters, automatically optimizing parameter values based on recent market conditions and strategy performance.

  7. Fundamental Integration: Consider adding simple fundamental filters, such as pausing trading before important economic data releases, to reduce risks from news shocks.

Summary
The "Multi-Timeframe Trend Following and Reversal Strategy Based on Fibonacci and McGinley Dynamic Indicator" is a sophisticated quantitative trading system that combines multiple technical analysis tools. It identifies potential trading opportunities by analyzing candlestick patterns, trend strength, and dynamic Fibonacci levels. The strategy's strengths lie in its multi-level confirmation mechanism, dynamic adaptability, and customizable risk management parameters. However, it also faces challenges such as parameter sensitivity, market condition limitations, and the inherent limitations of technical analysis.

By implementing the suggested optimization measures, such as dynamic stop-loss mechanisms, signal weighting systems, and market state filters, the strategy's robustness and performance could be significantly enhanced. In particular, combining the strategy with machine learning approaches could help it better adapt to changing market environments and reduce the risk of overfitting.

In conclusion, this is a well-designed quantitative strategy framework with the potential to adapt to various market conditions. As with all trading strategies, thorough backtesting and validation should be conducted before use, and parameters should be adjusted according to individual trading goals and risk tolerance.

Strategy source code

/*backtest
start: 2024-05-15 00:00:00
end: 2025-05-13 08:00:00
period: 2d
basePeriod: 2d
exchanges: [{"eid":"Futures_Binance","currency":"ETH_USDT"}]
*/

// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © beausti

//@version=6
strategy("7th Gate Open --- Complete", overlay=true)



// --- Parameters ---
TREND_CANDLES = 160  // Fixed: Trend detection based on timeframe
TIMEFRAME = input.timeframe("1440", title="Secondary Analysis Timeframe")  // Adjustable timeframe for analysis
alpha = input.float(0.7, title="Alpha", minval=0.1, maxval=5.0)  // McGinley Dynamic sensitivity
take_profit_pct = input.float(10.0, title="Take Profit (%)", minval=0.1)  // Take profit percentage
stop_loss_pct = input.float(10.0, title="Stop Loss (%)", minval=0.1)  // Stop loss percentage



// --- 16-Minute Trend Data (Baseline) ---
open_240 = request.security(syminfo.tickerid, "1440", open)
close_240 = request.security(syminfo.tickerid, "1440", close)



// Trend Detection Logic (Fixed on 16-Minute)
var int uptrend_count = 0
var int downtrend_count = 0



for i = 1 to TREND_CANDLES
    uptrend_count := (close_240[i] > open_240[i]) ? uptrend_count + 1 : 0
    downtrend_count := (close_240[i] < open_240[i]) ? downtrend_count + 1 : 0

trend_type = "Trending"
if (uptrend_count >= TREND_CANDLES)
    trend_type := "Uptrend"
    label.new(bar_index, close_240, "Uptrend", color=color.green, textcolor=color.black, size=size.small)
if (downtrend_count >= TREND_CANDLES)
    trend_type := "Downtrend"
    label.new(bar_index, close_240, "Downtrend", color=color.red, textcolor=color.black, size=size.small)

// --- Secondary Analysis Timeframe Data (User-Defined) ---
open_TF = request.security(syminfo.tickerid, TIMEFRAME, open)
close_TF = request.security(syminfo.tickerid, TIMEFRAME, close)
high_TF = request.security(syminfo.tickerid, TIMEFRAME, high)
low_TF = request.security(syminfo.tickerid, TIMEFRAME, low)



// --- Engulfing Candle Detection (Using User-Selected Timeframe) ---
engulfing_bullish = close_TF > open_TF[1] and open_TF < close_TF[1] and high_TF > high_TF[1] and low_TF > low_TF[1]
engulfing_bearish = close_TF < open_TF[1] and open_TF > close_TF[1] and high_TF < high_TF[1] and low_TF < low_TF[1]



// --- Plot Engulfing Candles ---
if engulfing_bullish
    label.new(bar_index, close_TF, "Bullish", color=color.green, textcolor=color.black, size=size.small)
if engulfing_bearish
    label.new(bar_index, close_TF, "Bearish", color=color.red, textcolor=color.black, size=size.small)

// --- Fibonacci Levels (Using User-Selected Timeframe) ---
var float fib_high = ta.highest(high_TF, TREND_CANDLES)
var float fib_low = ta.lowest(low_TF, TREND_CANDLES)



fib_0 = fib_high
fib_382 = fib_low + (fib_high - fib_low) * 0.382
fib_5 = fib_low + (fib_high - fib_low) * 0.5
fib_618 = fib_low + (fib_high - fib_low) * 0.618
fib_786 = fib_low + (fib_high - fib_low) * 0.786
fib_1 = fib_low
fib_n0618_up = fib_high + (fib_high - fib_low) * 0.618
fib_n0618_down = fib_low - (fib_high - fib_low) * 0.618







// --- McGinley Dynamic Calculation ---
var float md = na
if na(md[1])
    md := close
md := md[1] + (close - md[1]) / (alpha * close)
plot(md, color=color.blue, linewidth=2, title="McGinley Dynamic")



// --- Moving Averages (Using User-Selected Timeframe) ---
ema = ta.ema(close_TF,32)
ma = ta.sma(close_TF, 64)
plot(ema, color=color.orange, linewidth=2, title="EMA")
plot(ma, color=color.purple, linewidth=2, title="MA")



// --- EMA/MA Crossover for Take Profit (Using User-Selected Timeframe) ---
ema_cross_ma_up = ta.crossover(ma, ema)  // Bullish EMA cross
ema_cross_ma_down = ta.crossunder(ema, ma)  // Bearish EMA cross



//---Take Profit Logic---
take_profit_buy_level = strategy.position_avg_price * (1 - take_profit_pct / 100)
take_profit_sell_level = strategy.position_avg_price * (1 - take_profit_pct / 100)

stop_loss_buy_level = strategy.position_avg_price * (1 - stop_loss_pct / 100)
stop_loss_sell_level = strategy.position_avg_price * (1 - stop_loss_pct / 100)



// --- Trade Signals ---
if (engulfing_bullish and uptrend_count <= 16 and strategy.position_size <= 0)
    strategy.entry("Buy", strategy.long, qty=1)
    if ta.crossover(high, ta.highest(high, 1)[1])
        strategy.entry("Buy", strategy.long, qty = 1)
        if (downtrend_count <= 32 and engulfing_bearish)
            strategy.exit("Buy", from_entry="Sell", limit=take_profit_buy_level, stop = stop_loss_buy_level)
            if (strategy.position_size <= 0)
                strategy.exit("Trend is Sell", from_entry="Buy", limit=take_profit_buy_level)



if (engulfing_bearish and downtrend_count <= 16 and strategy.position_size > 0)
    strategy.entry("Sell", strategy.short, qty=1)
    if ta.crossover(low, ta.highest(low, 1)[1])   
        strategy.entry("Sell", strategy.short, qty = 1)
        if (uptrend_count <= 32 and engulfing_bullish)
            strategy.exit("Sell", from_entry="Buy", limit=take_profit_sell_level, stop = stop_loss_sell_level)
            if (strategy.position_size > 0)
                strategy.exit("Trend is Buy", from_entry="Sell", limit=take_profit_sell_level)















Enter fullscreen mode Exit fullscreen mode

Strategy parameters

Image description

The original address: Multi-Timeframe Trend Following and Reversal Strategy Based on Fibonacci and McGinley Dynamic Indicator

Comments 1 total

  • Rebecca Chow
    Rebecca ChowJun 17, 2025

    That’s like mixing a crystal ball with a physics textbook—either genius or chaotic neutral. Love the multi-timeframe approach, but will it survive when the market retraces 161.8% of your patience? Show us the backtest equity curve… ideally without the ‘Oops, forgot about spreads’ dip. Fibs are fun until the market says ‘Nope, that’s not a level, that’s a suggestion.’

Add comment