Dynamic Fibonacci Trend-Confirmed Crossover Engine Quantitative Strategy

EMA MA FIBONACCI McGinley Dynamic Trend TP SL
Created on: 2025-05-14 16:37:16 Modified on: 2025-05-14 16:37:16
Copy: 0 Number of hits: 309
avatar of ianzeng123 ianzeng123
2
Follow
319
Followers

 Dynamic Fibonacci Trend-Confirmed Crossover Engine Quantitative Strategy  Dynamic Fibonacci Trend-Confirmed Crossover Engine Quantitative Strategy

Overview

The Dynamic Fibonacci Trend-Confirmed Crossover Engine Quantitative Strategy is a price action-based quantitative trading system that combines multiple technical analysis indicators and filtering conditions. The strategy primarily identifies engulfing patterns as entry signals within specific market contexts, while utilizing macro trend confirmation and dynamic Fibonacci levels for filtering, ultimately managing positions through EMA/MA crossovers and adaptive stop mechanisms. The core feature of this strategy is the integration of traditional technical analysis methods with modern quantitative tools, enhancing trading signal reliability through multi-timeframe analysis. This system is particularly suited for capturing reversal points in clearly trending markets while offering flexible parameter adjustments to adapt to different trading styles and market environments.

Strategy Principles

The core principles of this strategy are based on a multi-layered market analysis framework, comprising the following key components:

  1. Trend Detection Mechanism: The strategy uses a fixed 160 candles to determine the macro trend direction. By continuously comparing opening and closing prices within a 1440-minute (daily) timeframe, it calculates the persistence of uptrends and downtrends to determine whether the market is in a defined uptrend, downtrend, or consolidation state.

  2. Engulfing Pattern Recognition: Within a user-defined timeframe (default: daily), the strategy identifies candle formations with engulfing characteristics. A bullish engulfing pattern requires the current closing price to be higher than the previous candle’s opening price, the current opening price lower than the previous candle’s closing price, and both the current high and low points to be higher than their respective points in the previous candle. Bearish engulfing patterns follow the opposite conditions.

  3. Dynamic Fibonacci Level Adjustment: The strategy calculates Fibonacci retracement and extension levels (0%, 38.2%, 50%, 61.8%, 78.6%, 100%, and extensions at -61.8% and 161.8%) based on the highest and lowest prices within the user-selected timeframe, providing a reference framework for price action analysis.

  4. McGinley Dynamic Indicator: This indicator is an improved moving average that offers more responsive price tracking capability through an adjustable alpha parameter (default 0.7), helping to confirm trend direction and strength.

  5. Moving Average Crossover System: The strategy incorporates crossover points between a 32-period Exponential Moving Average (EMA) and a 64-period Simple Moving Average (MA) as potential profit-taking or reversal signals.

  6. Entry and Management Mechanism:

    • When a bullish engulfing pattern is identified and the uptrend count doesn’t exceed 16, the strategy initiates a long position.
    • When the high point breaks above the previous high, it adds to the long position.
    • When the downtrend count doesn’t exceed 32 and a bearish engulfing pattern appears, it triggers take-profit or stop-loss exits.
    • The logic for bearish signals is similar but in the opposite direction.
  7. Risk Management: The strategy sets percentage-based take-profit and stop-loss levels (default: both at 10%), calculating absolute price levels dynamically based on the entry price.

Strategy Advantages

  1. Multi-layered Confirmation Mechanism: By combining trend analysis, candle patterns, and technical indicators, the strategy creates a multi-layered signal confirmation system that significantly reduces the possibility of false signals.

  2. Adaptive Market Framework: The strategy not only considers a fixed trend timeframe but also allows users to customize the secondary analysis timeframe, enhancing the strategy’s ability to adapt to different market cycles.

  3. Dynamic Reference Points: Through the combination of the McGinley Dynamic indicator and Fibonacci levels, the strategy provides more flexible reference points that better adapt to market volatility and non-linear characteristics.

  4. Incremental Position Building: At breakthrough points following confirmed signals, the strategy allows for position additions, optimizing capital management and enhancing profit potential.

  5. Comprehensive Exit Strategy: Combining technical indicator crossovers with fixed percentage take-profit/stop-loss points, the strategy establishes a comprehensive exit framework that balances profit-locking and risk control needs.

  6. Visual Feedback: The strategy provides visual feedback through labels and lines, helping traders understand the market environment and strategy decisions.

  7. Flexible Parameter Adjustment: Key parameters such as the McGinley Dynamic indicator sensitivity (alpha) and take-profit/stop-loss percentages can be adjusted according to user preferences and market conditions.

Strategy Risks

  1. Parameter Sensitivity: The strategy relies on multiple fixed parameters (such as the 160 candles for trend detection, 32 periods for EMA, and 64 periods for MA), which may not be optimal in different market environments, leading to performance fluctuations. Solution: Implement adaptive parameter optimization mechanisms that dynamically adjust parameters based on market volatility.

  2. Frequent Trading Risk: In highly volatile markets, engulfing patterns may appear frequently but lack substantive significance, leading to overtrading and increased transaction costs. Solution: Add additional filtering conditions, such as volume confirmation or volatility thresholds.

  3. False Breakout Risk: Price may quickly retrace after breaking above/below previous highs/lows, making position-addition signals unreliable. Solution: Implement breakout confirmation mechanisms, such as requiring price to maintain a certain duration or magnitude after breakout.

  4. Fixed Stop-Loss Limitations: Using fixed percentage stop-losses may trigger too early in highly volatile markets or be too loose in low-volatility markets. Solution: Implement ATR-based adaptive stop-loss strategies that adjust stop levels according to actual market volatility.

  5. Trend Detection Delay: Trend detection based on historical data may lag behind actual market turning points. Solution: Integrate forward-looking trend indicators, such as Relative Strength Index (RSI) divergence or MACD signals.

  6. Timeframe Conflicts: Signals from different timeframes may contradict each other, causing strategy confusion. Solution: Establish a timeframe priority system or implement a multi-timeframe coordination mechanism.

  7. Market State Dependency: The strategy performs best in clearly trending markets but may underperform in consolidating, sideways markets. Solution: Add market state detection logic and employ different trading strategies for different market states.

Strategy Optimization Directions

  1. Adaptive Parameter System: Transform key parameters such as EMA/MA periods and trend detection windows into adaptive parameters that automatically adjust based on market volatility and recent trend strength. This can improve the strategy’s adaptability across different market environments while reducing curve-fitting risks.

  2. Enhanced Trend Detection: The existing trend detection is based on simple price comparisons and can be enhanced by integrating more complex trend strength indicators such as Directional Movement Index (DMI), Average Directional Index (ADX), or linear regression slopes. This will provide more accurate trend assessments and reduce false signals.

  3. Volume Confirmation Mechanism: Integrate volume analysis into the signal confirmation process, especially for engulfing patterns and breakout signals. Engulfing patterns with abnormally high volume typically have higher reliability and can serve as an additional filtering layer.

  4. Dynamic Position Sizing: The current strategy uses fixed unit position sizes and can implement dynamic position sizing based on market volatility or account risk proportion to optimize capital management and risk control.

  5. Refined Exit Strategy: More complex, staged profit-taking strategies can be developed, such as moving stop-losses to breakeven after reaching certain profit levels, or partially reducing positions based on key price levels, thereby locking in partial profits while maintaining upside potential.

  6. Volatility Adjustment Mechanism: Integrate market volatility (such as ATR or historical volatility) into the strategy logic to adjust entry conditions, stop-loss levels, and profit targets, enabling the strategy to maintain stable performance across different volatility environments.

  7. Machine Learning Enhancement: Utilize machine learning algorithms to optimize parameter selection and identify market environments most favorable for strategy execution, or even train models to predict the success probability of engulfing patterns and trend confirmations.

  8. Seasonality and Time Filters: Analyze the strategy’s performance across different market sessions, day-of-week, and monthly cycles, and potentially disable trading during historically underperforming time periods to improve overall stability.

Summary

The Dynamic Fibonacci Trend-Confirmed Crossover Engine Quantitative Strategy represents a comprehensive technical trading approach that successfully integrates traditional price action analysis (such as engulfing patterns) with modern quantitative tools (such as the McGinley Dynamic indicator and multi-timeframe analysis). The core strengths of this strategy lie in its multi-layered signal confirmation system and flexible parameter adjustment capabilities, enabling it to adapt to various market environments.

However, the strategy also faces risks related to parameter sensitivity, false signals, and market state dependency. By implementing the suggested optimization measures, particularly adaptive parameter systems, enhanced trend detection, and dynamic risk management, the strategy’s robustness and long-term performance can be significantly improved.

Overall, this strategy provides a solid quantitative trading foundation suitable for experienced traders to further customize and refine to match their specific risk preferences and trading objectives. Its comprehensive design considers both technical accuracy and practical applicability and scalability, making it a valuable component in the modern quantitative trading toolkit.

Strategy source code
/*backtest
start: 2024-05-14 00:00:00
end: 2024-12-02 00:00:00
period: 1d
basePeriod: 1d
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)