Multi-Period ATR Adaptive SuperTrend Trading System

ATR supertrend STOP LOSS TAKE PROFIT TREND FOLLOWING DUAL LANGUAGE AUTOMATED TRADING
Created on: 2025-06-30 09:03:02 Modified on: 2025-06-30 09:03:02
Copy: 0 Number of hits: 350
avatar of ianzeng123 ianzeng123
2
Follow
319
Followers

 Multi-Period ATR Adaptive SuperTrend Trading System  Multi-Period ATR Adaptive SuperTrend Trading System

Overview

The Multi-Period ATR Adaptive SuperTrend Trading System is an intelligent trend-following strategy based on the Average True Range (ATR) indicator. This strategy utilizes changes in the SuperTrend indicator to identify market trend transition points and automatically executes long and short trades after trend confirmation. The system integrates independent take-profit parameters for both long and short positions and can close positions in real-time based on trend reversal signals, effectively improving win rates and capital efficiency.

Strategy Principles

The core of this strategy is based on the calculation logic and signal generation mechanism of the SuperTrend indicator. The SuperTrend indicator forms dynamic support and resistance levels by calculating the relationship between price and ATR. The specific implementation steps are as follows:

  1. ATR Calculation: The strategy provides two ATR calculation methods - standard ATR calculation and TR calculation based on Simple Moving Average (SMA). Users can choose the calculation method that better suits the current market environment.

  2. Upper and Lower Band Determination:

    • Upper Band = Price Source - ATR Multiplier × ATR Value
    • Lower Band = Price Source + ATR Multiplier × ATR Value
  3. Trend Determination Logic:

    • When the closing price breaks above the lower band, the trend turns upward (value 1)
    • When the closing price breaks below the upper band, the trend turns downward (value -1)
  4. Trade Signal Generation:

    • Buy Signal: Trend changes from -1 to 1
    • Sell Signal: Trend changes from 1 to -1
  5. Intelligent Position Management: The strategy automatically cancels all pending orders before executing new trades to ensure new signals can be executed smoothly. The system also determines whether a reverse trade is needed based on the current position direction.

  6. Risk Control Mechanism: The strategy sets independent take-profit parameters for long and short directions and uses a unified percentage stop-loss to control risk. Additionally, when the trend reverses, the system automatically closes positions to avoid larger losses.

Strategy Advantages

Through in-depth code analysis, this strategy has the following significant advantages:

  1. Adaptation to Market Volatility: By dynamically adjusting support and resistance levels through the ATR indicator, the strategy can adapt to different market volatility environments, reducing false signals.

  2. Flexible Parameter Configuration: The system provides a rich set of adjustable parameters, including ATR period, ATR multiplier, data source selection, etc., allowing users to perform personalized optimization based on different trading instruments and timeframes.

  3. Independent Take-Profit Settings for Long/Short: The strategy innovatively provides independent take-profit parameters for long and short directions, better aligning with the asymmetric nature of markets, allowing different profit targets for long and short directions.

  4. Automatic Position Closing on Trend Reversal: The system automatically closes positions when trends reverse, without waiting for take-profit or stop-loss triggers, effectively protecting existing profits and reducing potential losses.

  5. Visualization of Trading Signals: The strategy visually displays buy and sell signals, take-profit and stop-loss levels, and trend background colors on the chart, helping traders better understand and track the system’s operating status.

  6. Precise Signal Filtering: Through the trend confirmation mechanism, the strategy reduces false breakout signals in oscillating markets, improving trade quality.

Strategy Risks

Despite the strategy’s excellent design, the following potential risks still exist:

  1. Parameter Sensitivity: ATR multiplier and period settings significantly impact strategy performance, and inappropriate parameters may lead to overtrading or missing important signals. The solution is to find the optimal parameter combination through historical data backtesting.

  2. Trend Reversal Risk: At strong trend transition points, the market may experience large gaps, causing stop-losses to fail to execute effectively. It is recommended to adjust the ATR multiplier or add additional market volatility filtering conditions in high-volatility market environments.

  3. Single Indicator Dependency: The strategy mainly relies on the SuperTrend indicator without other auxiliary indicators for confirmation, which may generate incorrect signals in certain market environments. Consider adding other indicators for signal confirmation.

  4. Fixed Percentage Stop-Loss: The strategy uses a fixed percentage to set stop-losses without considering current market volatility, which may place stop-loss levels too close in high-volatility environments. Consider dynamically linking stop-loss levels with ATR values.

  5. Continuous Signal Processing: In oscillating markets, frequent trend transitions may occur, leading to overtrading and increased costs. Signal filtering mechanisms or time interval restrictions can be added to reduce trading frequency.

Strategy Optimization Directions

Based on code analysis, the strategy can be optimized in the following directions:

  1. Add Volume Confirmation: Combine volume indicators to confirm the validity of trend changes, executing trade signals only when volume increases, which can effectively reduce losses from false breakouts.

  2. Multi-Timeframe Analysis: Introduce a multi-timeframe analysis framework, trading only in the direction of larger timeframe trends, which can significantly improve system win rates. For example, execute hourly long signals only when the daily trend is upward.

  3. Dynamic ATR Multiplier: Dynamically adjust the ATR multiplier based on market volatility states, using larger multipliers in high-volatility environments and smaller multipliers in low-volatility environments, making the system more adaptive.

  4. Incorporate Market State Recognition: Develop a market state recognition module to distinguish between trending and oscillating markets, applying different trading strategies or parameter combinations in different market states.

  5. Optimize Take-Profit and Stop-Loss Strategies: Implement dynamic trailing stops that automatically adjust stop-loss positions as prices move in favorable directions, both protecting profits and giving prices enough breathing room.

  6. Add Trading Time Filters: Add specific trading session filters to avoid periods of high market volatility or poor liquidity, improving trade quality.

  7. Capital Management Optimization: Dynamically adjust position sizes based on signal strength and market volatility conditions, increasing positions on high-confidence signals and reducing positions on low-confidence signals.

Conclusion

The Multi-Period ATR Adaptive SuperTrend Trading System is a comprehensive trend-following strategy that combines technical analysis and risk management. By utilizing the SuperTrend indicator to capture market trend transition points and employing flexible take-profit and stop-loss mechanisms, this strategy can maintain stable performance across various market environments.

The core advantages of this strategy lie in its adaptability and flexible parameter configuration, allowing it to adapt to different trading instruments and market cycles. By setting independent take-profit parameters for long and short directions, the strategy can better adapt to the asymmetric nature of markets, improving overall profitability.

Despite risks such as parameter sensitivity and single indicator dependency, through the suggested optimization directions, especially multi-timeframe analysis and dynamic ATR multiplier adjustments, this strategy has the potential to further enhance its stability and profitability. Ultimately, this strategy provides traders with a reliable, systematic trading framework that can help reduce emotional interference and achieve more objective and disciplined trade execution.

Strategy source code
/*backtest
start: 2024-09-15 00:00:00
end: 2025-06-28 08:00:00
period: 1h
basePeriod: 1h
exchanges: [{"eid":"Futures_Binance","currency":"ETH_USDT","balance":50000000}]
*/

//@version=6
strategy("ZYTX SuperTrend V1", overlay=true, margin_long=100, margin_short=100, pyramiding=0)

// 输入参数
periods = input(title='ATR周期', defval=10)
src = input(hl2, title='数据源')
multiplier = input.float(title='ATR乘数', step=0.1, defval=3.0)
changeATR = input(title='改变ATR计算方法', defval=true)  // 已删除多余问号
stopLossPerc = input.float(title='止损 (%)', defval=1.0, step=0.1, minval=0, maxval=100) / 100
longTakeProfitPerc = input.float(title='多单止盈 (%)', defval=2.0, step=0.1, minval=0, maxval=100) / 100
shortTakeProfitPerc = input.float(title='空单止盈 (%)', defval=1.5, step=0.1, minval=0, maxval=100) / 100
enableLong = input.bool(title='启用做多交易', defval=true)
enableShort = input.bool(title='启用做空交易', defval=true)

// 超级趋势计算
atr2 = ta.sma(ta.tr, periods)
atr = changeATR ? ta.atr(periods) : atr2
up = src - multiplier * atr
up1 = nz(up[1], up)
up := close[1] > up1 ? math.max(up, up1) : up
dn = src + multiplier * atr
dn1 = nz(dn[1], dn)
dn := close[1] < dn1 ? math.min(dn, dn1) : dn

// 趋势判断
trend = 1
trend := nz(trend[1], trend)
trend := trend == -1 and close > dn1 ? 1 : trend == 1 and close < up1 ? -1 : trend

// 交易信号
buySignal = trend == 1 and trend[1] == -1
sellSignal = trend == -1 and trend[1] == 1

// 可视化
plot(trend == 1 ? up : na, '上升趋势', style=plot.style_linebr, linewidth=2, color=color.new(color.green, 0))
plot(trend == 1 ? na : dn, '下降趋势', style=plot.style_linebr, linewidth=2, color=color.new(color.red, 0))

// 策略逻辑
var float entryPrice = na

if buySignal and enableLong
    strategy.cancel("多单止盈")
    strategy.cancel("多单止损")
    strategy.cancel("空单止盈")
    strategy.cancel("空单止损")
    
    if strategy.position_size <= 0
        strategy.entry("多单", strategy.long)
        entryPrice := close
        
        // 多单止盈使用独立参数
        if longTakeProfitPerc > 0
            strategy.exit("多单止盈", "多单", limit=entryPrice * (1 + longTakeProfitPerc), comment="多单止盈")
        
        if stopLossPerc > 0
            strategy.exit("多单止损", "多单", stop=entryPrice * (1 - stopLossPerc), comment="多单止损")

if sellSignal and enableShort
    strategy.cancel("多单止盈")
    strategy.cancel("多单止损")
    strategy.cancel("空单止盈")
    strategy.cancel("空单止损")
    
    if strategy.position_size >= 0
        strategy.entry("空单", strategy.short)
        entryPrice := close
        
        // 空单止盈使用独立参数
        if shortTakeProfitPerc > 0
            strategy.exit("空单止盈", "空单", limit=entryPrice * (1 - shortTakeProfitPerc), comment="空单止盈")
        
        if stopLossPerc > 0
            strategy.exit("空单止损", "空单", stop=entryPrice * (1 + stopLossPerc), comment="空单止损")

// 趋势反转平仓
if (trend == 1 and strategy.position_size < 0) or (trend == -1 and strategy.position_size > 0)
    strategy.close_all(comment="趋势反转平仓")

// 信号标记
plotshape(buySignal and enableLong, title='买入信号', text='买入', location=location.belowbar, 
          style=shape.labelup, size=size.small, color=color.new(color.green, 0), textcolor=color.new(color.white, 0))
plotshape(sellSignal and enableShort, title='卖出信号', text='卖出', location=location.abovebar, 
          style=shape.labeldown, size=size.small, color=color.new(color.red, 0), textcolor=color.new(color.white, 0))

// 止盈线可视化(多空独立)
plot(strategy.position_size > 0 and longTakeProfitPerc > 0 ? entryPrice * (1 + longTakeProfitPerc) : na, 
     "多单止盈线", style=plot.style_linebr, color=color.new(color.blue, 0), linewidth=1)
plot(strategy.position_size < 0 and shortTakeProfitPerc > 0 ? entryPrice * (1 - shortTakeProfitPerc) : na, 
     "空单止盈线", style=plot.style_linebr, color=color.new(color.blue, 0), linewidth=1)

// 趋势背景色
bgcolor(trend == 1 ? color.new(color.green, 90) : trend == -1 ? color.new(color.red, 90) : na, title="趋势背景")