Multi-Level Dynamic Trend Tracking Quantitative Strategy: Intelligent Take-Profit and Stop-Loss System Based on Hull Moving Average

HMA 移动平均线 趋势跟踪 动态追踪止损 交叉信号 云层过滤 止损机制 风险管理 Hull Moving Average TREND FOLLOWING Dynamic Trailing Stop Crossover Signal Cloud Filter Stop-Loss Mechanism risk management
Created on: 2025-07-08 09:40:44 Modified on: 2025-07-08 09:40:44
Copy: 0 Number of hits: 218
avatar of ianzeng123 ianzeng123
2
Follow
319
Followers

 Multi-Level Dynamic Trend Tracking Quantitative Strategy: Intelligent Take-Profit and Stop-Loss System Based on Hull Moving Average  Multi-Level Dynamic Trend Tracking Quantitative Strategy: Intelligent Take-Profit and Stop-Loss System Based on Hull Moving Average

Overview

The Multi-Level Dynamic Trend Tracking Quantitative Strategy is an advanced trend following system based on Hull Moving Average (HMA), combining intelligent entry signal identification with dynamic take-profit and stop-loss mechanisms. The core of this strategy lies in utilizing HMA indicators of different periods (100, 200, 500, 1000) to construct entry signals, while employing a three-layer protection mechanism: hard stop-loss before trigger, intelligent trailing stop-loss after trigger, and trend direction filtering, forming a complete trading system. The strategy precisely captures the starting points of trends and intelligently locks in profits when the market reverses, achieving efficient capital management and risk control.

Strategy Principles

The core logic of this strategy can be divided into four key components:

  1. Entry Signal Generation Mechanism:

    • Long-term Trend Determination: Using HMA500 and HMA1000 to construct a “cloud layer,” where a bullish environment is identified when HMA500 is above HMA1000, and bearish otherwise
    • Entry Conditions: In a bullish environment, a long signal is triggered when HMA100 crosses above HMA200 and both are above HMA500; in a bearish environment, a short signal is triggered when HMA100 crosses below HMA200 and both are below HMA500
  2. Trigger Mechanism:

    • Set percentage trigger threshold (default 1.2%)
    • When price moves beyond the trigger threshold in the favorable direction from the entry point, the trailing stop-loss logic is activated
  3. Intelligent Trailing Stop-Loss Mechanism:

    • After triggering, the system continuously tracks new highs (for longs) or new lows (for shorts)
    • Dynamically sets stop-loss levels based on user-defined trailing margin (default 0.8%)
    • Automatically closes positions to lock in profits when price retraces beyond the set margin
  4. Hard Stop-Loss Protection:

    • Sets maximum loss percentage (default 2.5%) before the trailing stop is triggered
    • Forces position closure to protect capital if price moves adversely beyond the hard stop-loss setting before reaching the trigger point

The strategy employs strict single position control (no pyramiding), ensuring controllable risk. The system automatically records entry price, highest/lowest price, and trigger status, achieving fully automated capital management.

Strategy Advantages

Analyzing the code implementation of this strategy reveals the following significant advantages:

  1. Multi-level Trend Confirmation: The system formed by four HMA lines of different periods creates a strict multiple confirmation mechanism, significantly improving the reliability of entry signals and reducing losses from false breakouts.

  2. Adaptive Risk Management: The strategy features a two-stage stop-loss mechanism (hard stop-loss before trigger and trailing stop-loss after trigger), enabling timely loss-cutting in severely adverse markets while maximizing returns in trending markets, adapting to different market environments.

  3. Precise Profit Locking: The dynamic trailing stop-loss mechanism automatically tracks new price highs/lows, implementing the classic trading concept of “letting profits run” while locking in most profits without manual intervention.

  4. High Customizability: Three key parameters (trigger threshold, trailing margin, maximum loss) can be customized by users, adapting to different instruments, volatility levels, and risk preferences.

  5. Visual Support: The strategy includes built-in visualization of HMA indicators and trend cloud layers, allowing traders to intuitively understand current trend status and the rationality of entry points.

Strategy Risks

Despite its sophisticated design, the strategy still has the following potential risks:

  1. Range-Bound Market Risk: In range-bound markets without clear trends, HMA crossover signals may generate frequent false signals, leading to consecutive stop-losses. The solution is to add additional filtering conditions, such as volatility indicators or trend strength confirmation.

  2. Parameter Sensitivity: Strategy performance highly depends on the settings of three key parameters. Inappropriate parameters may lead to premature stop-losses or missing most profits. It is recommended to optimize parameters for different instruments and time periods through historical backtesting.

  3. Slippage and Trading Cost Impact: In live trading environments, slippage and trading costs may significantly affect strategy performance, especially for settings with smaller trailing margins. These factors should be considered in backtesting, and parameters should be adjusted accordingly.

  4. Trend Reversal Point Delay: Although Hull Moving Averages react faster than traditional moving averages, they still have a certain lag, which may lead to larger drawdowns when trends suddenly reverse. Consider combining more sensitive short-term indicators to optimize exit timing.

  5. Single Technical Indicator Dependence: The strategy mainly relies on the HMA indicator series, lacking multidimensional market analysis. It may underperform under certain specific market conditions. It is recommended to cross-validate with other types of indicators such as momentum or volume indicators.

Strategy Optimization Directions

Based on strategy principles and risk analysis, optimization can be pursued in the following directions:

  1. Adaptive Parameter System:

    • Introduce dynamic parameter adjustment mechanisms based on market volatility, such as increasing trailing margin during high volatility periods and reducing trigger thresholds during low volatility periods
    • Implementation Principle: Can use the ATR (Average True Range) indicator to quantify market volatility and establish a functional relationship between parameters and ATR
  2. Multi-Timeframe Analysis:

    • Integrate trend information from larger timeframes, allowing entries only when the trend direction in larger timeframes is consistent
    • Implementation Method: Add checks for HMA status in larger periods (such as 1-hour, 4-hour), forming stricter trend filtering
  3. Volume Verification Mechanism:

    • Add volume confirmation conditions, requiring signals to be accompanied by increased volume
    • Specific Implementation: Can use relative volume indicators (such as OBV or relative volume change rate) as additional filtering conditions
  4. Intelligent Partial Profit-Taking:

    • Implement a partial profit-taking mechanism, closing part of the position when reaching the first target, with the remaining portion using trailing stops
    • Principle: This method balances certain returns with potential major trend returns, improving overall risk-reward ratio
  5. Machine Learning Optimization:

    • Use machine learning algorithms to dynamically identify optimal parameter combinations and market environments
    • Method: Can build classification models based on historical data to predict parameter settings suitable for the current market environment
  6. Counter-Trend Protection Mechanism:

    • Add reverse protection logic for extreme price volatility, taking special measures when abnormal price volatility occurs in the short term
    • Implementation: Can monitor short-term price change rates, temporarily adjusting stop-loss levels or directly closing positions when thresholds are exceeded

Summary

The Multi-Level Dynamic Trend Tracking Quantitative Strategy is an advanced quantitative trading strategy that combines multi-period Hull Moving Average indicators with an intelligent profit-taking and stop-loss system. It improves entry signal reliability through strict trend confirmation mechanisms while achieving a balance between capital protection and profit maximization through a multi-level risk control system (including hard stop-loss before trigger and dynamic trailing stop-loss after trigger).

The core advantages of this strategy lie in its adaptability and systematic profit management method, which can maintain relatively stable performance in different market environments. However, the strategy also has risks such as parameter sensitivity and single indicator dependence, requiring traders to optimize through methods such as adding auxiliary indicator verification, building adaptive parameter systems, and multi-timeframe analysis.

By reasonably setting parameters and combining market environment analysis, this strategy can serve as a core component of a medium to long-term trend following system, helping traders capture major trending opportunities while controlling risk, achieving steady capital growth.

Strategy source code
/*backtest
start: 2025-01-01 00:00:00
end: 2025-07-04 08:00:00
period: 1h
basePeriod: 1h
exchanges: [{"eid":"Futures_Binance","currency":"ETH_USDT"}]
*/

//@version=5
strategy("Samil Dogru SmartTrailing v1.1", overlay=true, pyramiding=0,
     default_qty_type=strategy.percent_of_equity, default_qty_value=100)

// === PARAMETRELER ===
triggerPerc     = input.float(1.2,  "Tetikleme Eşiği (%)", step=0.1)
trailPerc       = input.float(0.8,  "Trailing Marj (%)", step=0.1)
hardStopPerc    = input.float(2.5,  "Maksimum Zarar (%) (Tetiklenmeden önce)", step=0.1)

// === HMA'lar (giriş için referans) ===
hma100 = ta.hma(close, 100)
hma200 = ta.hma(close, 200)
hma500 = ta.hma(close, 500)
hma600 = ta.hma(close, 600)

isBull = hma500 > hma600
longCond  = ta.crossover(hma100, hma200) and isBull and hma100 > hma500 and hma200 > hma500
shortCond = ta.crossunder(hma100, hma200) and not isBull and hma100 < hma500 and hma200 < hma500

// === GİRİŞLER ===
if (longCond)
    strategy.entry("Long", strategy.long)
if (shortCond)
    strategy.entry("Short", strategy.short)

// === DURUM DEĞİŞKENLERİ ===
var float entryPrice    = na
var float maxSinceEntry = na
var bool  triggered     = false

// === POZİSYON AÇILDIĞINDA BAŞLAT ===
if strategy.opentrades > 0
    if na(entryPrice)
        entryPrice := strategy.position_avg_price
        maxSinceEntry := close
        triggered := false
    else
        // Güncel zirve/dip güncellemesi
        if strategy.position_size > 0
            maxSinceEntry := math.max(maxSinceEntry, close)
        if strategy.position_size < 0
            maxSinceEntry := math.min(maxSinceEntry, close)

        // Tetikleme kontrolü
        longTriggerPrice  = entryPrice * (1 + triggerPerc / 100)
        shortTriggerPrice = entryPrice * (1 - triggerPerc / 100)

        if strategy.position_size > 0 and close >= longTriggerPrice
            triggered := true
        if strategy.position_size < 0 and close <= shortTriggerPrice
            triggered := true

        // Çıkış kontrolü (trailing)
        if triggered
            if strategy.position_size > 0
                trailStop = maxSinceEntry * (1 - trailPerc / 100)
                if close <= trailStop
                    strategy.close("Long", comment="TRAIL EXIT LONG")
            if strategy.position_size < 0
                trailStop = maxSinceEntry * (1 + trailPerc / 100)
                if close >= trailStop
                    strategy.close("Short", comment="TRAIL EXIT SHORT")
        else
            // Tetiklenmeden önce sert zarar çıkışı (hard stop)
            if strategy.position_size > 0 and close <= entryPrice * (1 - hardStopPerc / 100)
                strategy.close("Long", comment="HARD STOP LONG")
            if strategy.position_size < 0 and close >= entryPrice * (1 + hardStopPerc / 100)
                strategy.close("Short", comment="HARD STOP SHORT")

// === POZİSYON KAPANDIĞINDA RESET ===
if strategy.opentrades == 0
    entryPrice := na
    maxSinceEntry := na
    triggered := false

// === GÖRSEL ===
plot(hma100,  title="HMA 100",  color=color.white,  linewidth=2)
plot(hma200,  title="HMA 200",  color=color.yellow, linewidth=3)
p1 = plot(hma500,  title="HMA 500",  color=color.green, linewidth=2)
p2 = plot(hma600, title="HMA 600", color=color.red,   linewidth=2)
fill(p1, p2, color=isBull ? color.new(color.green, 70) : color.new(color.red, 70), title="HMA Cloud")