다중 이동 평균 추세 추적 및 동적 변동성 필터링 전략

EMA TR ATR
생성 날짜: 2025-01-17 15:00:37 마지막으로 수정됨: 2025-01-17 15:00:37
복사: 3 클릭수: 303
avatar of ChaoZhang ChaoZhang
1
집중하다
1617
수행원

다중 이동 평균 추세 추적 및 동적 변동성 필터링 전략

개요

이 전략은 추세 추종과 변동성 필터링을 결합한 지능형 거래 시스템입니다. 지수 이동 평균(EMA)을 통해 시장 동향을 파악하고, True Range(TR)와 동적 변동성 필터를 사용하여 진입 시점을 결정하며, 변동성에 따라 동적 손절매 및 손절매 메커니즘으로 위험을 관리합니다. 이 전략은 스캘프와 스윙의 두 가지 거래 모드를 지원하며, 이는 다양한 시장 환경 및 거래 스타일에 따라 유연하게 전환할 수 있습니다.

전략 원칙

전략의 핵심 논리에는 다음과 같은 핵심 구성 요소가 포함됩니다.

  1. 추세 식별: 50기간 EMA를 추세 필터로 사용하고 가격이 EMA보다 높을 때만 롱 포지션을 취하고, 가격이 EMA보다 낮을 때만 숏 포지션을 취합니다.
  2. 변동성 필터링: 실제 범위(TR)의 EMA를 계산하고 조정 가능한 필터 계수(기본값 1.5)를 사용하여 시장 노이즈를 필터링합니다.
  3. 진입 조건: 3개의 연속된 K-라인에 대한 형태학적 분석과 결합하여, 가격 움직임은 지속적이고 가속적이어야 합니다.
  4. 이익실현 및 손절매: 단기 모드에서는 현재 TR을 기준으로 설정되고, 밴드 모드에서는 이전 최고가와 최저가를 기준으로 설정되어 역동적인 위험 관리를 달성합니다.

전략적 이점

  1. 강력한 적응성: 동적 변동성 필터링과 추세 추적을 결합하여 다양한 시장 환경에 적응할 수 있습니다.
  2. 완벽한 위험 관리: 두 가지 거래 모드에 대해 역동적인 손절매 및 손절매 메커니즘을 제공하여 시장 특성에 따라 유연하게 선택할 수 있습니다.
  3. 우수한 매개변수 조정성: 필터 계수, 추세 주기 등의 주요 매개변수를 거래 상품의 특성에 따라 최적화할 수 있습니다.
  4. 우수한 시각화 효과: 거래 모니터링을 용이하게 하기 위해 명확한 매수 및 매도 신호 표시와 손절매 및 손절매 포지션 표시를 제공합니다.

전략적 위험

  1. 추세 반전 위험: 추세 전환점에서 연속적인 정지가 발생할 수 있습니다.
  2. 거짓 돌파 위험: 변동성이 갑자기 증가하면 거짓 신호가 발생할 수 있습니다.
  3. 매개변수 민감도: 필터 계수를 잘못 설정하면 신호가 너무 많거나 너무 적을 수 있습니다.
  4. 슬리피지 영향: 빠른 시장에서는 큰 슬리피지가 발생할 수 있으며, 이는 전략 성과에 영향을 미칠 수 있습니다.

전략 최적화 방향

  1. 추세 강도 필터링 추가: ADX와 같은 지표를 도입하여 추세 강도를 평가하고 추세 추적 효과를 개선할 수 있습니다.
  2. 이익 실현 및 손절매 최적화: 더 많은 수익을 보호하기 위해 이동형 손절매 도입을 고려하세요.
  3. 스윙 트레이딩 모델 개선: 스윙 트레이딩에 특화된 판단 조건을 더 추가하여 중장기 보유 역량을 개선할 수 있습니다.
  4. 볼륨 분석 추가: 볼륨 변화를 결합하여 돌파구의 타당성을 확인합니다.

요약하다

이 전략은 추세 추적, 변동성 필터링, 동적 위험 관리를 유기적으로 결합하여 완전한 거래 시스템을 구축합니다. 이 전략의 장점은 매우 적응성이 뛰어나고 위험이 통제 가능하며, 최적화를 위한 넓은 여지를 제공한다는 점입니다. 매개변수를 합리적으로 설정하고 적절한 거래 모드를 선택하면, 이 전략은 다양한 시장 환경에서 안정적인 성과를 유지할 수 있습니다. 트레이더는 실제 사용에 앞서 충분한 백테스팅과 매개변수 최적화를 수행하고 특정 거래 상품의 특성에 따라 해당 조정을 하는 것이 좋습니다.

전략 소스 코드
/*backtest
start: 2024-12-17 00:00:00
end: 2025-01-15 08:00:00
period: 2h
basePeriod: 2h
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT","balance":49999}]
*/

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

//@version=5
strategy("Scalp Slayer (I)", overlay=true)

// Input Parameters
filterNumber = input.float(1.5, "Filter Number", minval=1.0, maxval=10.0, tooltip="Higher = More aggressive Filter, Lower = Less aggressive")
emaTrendPeriod = input.int(50, "EMA Trend Period", minval=1, tooltip="Period for the EMA used for trend filtering")
lookbackPeriod = input.int(20, "Lookback Period for Highs/Lows", minval=1, tooltip="Period for determining recent highs/lows")
colorTP = input.color(title='Take Profit Color', defval=color.orange)
colorSL = input.color(title='Stop Loss Color', defval=color.red)

// Inputs for visibility
showBuyLabels = input.bool(true, title="Show Buy Labels")
showSellLabels = input.bool(true, title="Show Sell Labels")

// Alert Options
alertOnCondition = input.bool(true, title="Alert on Condition Met", tooltip="Enable to alert when condition is met")

// Trade Mode Toggle
tradeMode = input.bool(false, title="Trade Mode (ON = Swing, OFF = Scalp)", tooltip="Swing-mode you can use your own TP/SL.")

// Calculations
tr = high - low
ema = filterNumber * ta.ema(tr, 50)
trendEma = ta.ema(close, emaTrendPeriod)  // Calculate the EMA for the trend filter

// Highest and lowest high/low within lookback period for swing logic
swingHigh = ta.highest(high, lookbackPeriod)
swingLow = ta.lowest(low, lookbackPeriod)

// Variables to track the entry prices and SL/TP levels
var float entryPriceLong = na
var float entryPriceShort = na
var float targetPriceLong = na
var float targetPriceShort = na
var float stopLossLong = na
var float stopLossShort = na
var bool tradeActive = false

// Buy and Sell Conditions with Trend Filter
buyCondition = close > trendEma and  // Buy only if above the trend EMA
      close[2] > open[2] and close[1] > open[1] and close > open and 
      (math.abs(close[2] - open[2]) > math.abs(close[1] - open[1])) and 
      (math.abs(close - open) > math.abs(close[1] - open[1])) and 
      close > close[1] and close[1] > close[2] and tr > ema

sellCondition = close < trendEma and  // Sell only if below the trend EMA
       close[2] < open[2] and close[1] < open[1] and close < open and 
       (math.abs(close[2] - open[2]) > math.abs(close[1] - open[1])) and 
       (math.abs(close - open) > math.abs(close[1] - open[1])) and 
       close < close[1] and close[1] < close[2] and tr > ema

// Entry Rules
if (buyCondition and not tradeActive)
    entryPriceLong := close  // Track entry price for long position
    stopLossLong := tradeMode ? ta.lowest(low, lookbackPeriod) : swingLow  // Scalping: recent low, Swing: lowest low of lookback period
    targetPriceLong := tradeMode ? close + tr : swingHigh  // Scalping: close + ATR, Swing: highest high of lookback period
    tradeActive := true

if (sellCondition and not tradeActive)
    entryPriceShort := close  // Track entry price for short position
    stopLossShort := tradeMode ? ta.highest(high, lookbackPeriod) : swingHigh  // Scalping: recent high, Swing: highest high of lookback period
    targetPriceShort := tradeMode ? close - tr : swingLow  // Scalping: close - ATR, Swing: lowest low of lookback period
    tradeActive := true

// Take Profit and Stop Loss Logic
signalBuyTPPrint = (not na(entryPriceLong) and close >= targetPriceLong)
signalSellTPPrint = (not na(entryPriceShort) and close <= targetPriceShort)

signalBuySLPrint = (not na(entryPriceLong) and close <= stopLossLong)
signalSellSLPrint = (not na(entryPriceShort) and close >= stopLossShort)

if (signalBuyTPPrint or signalBuySLPrint)
    entryPriceLong := na  // Reset entry price for long position
    targetPriceLong := na  // Reset target price for long position
    stopLossLong := na  // Reset stop-loss for long position
    tradeActive := false

if (signalSellTPPrint or signalSellSLPrint)
    entryPriceShort := na  // Reset entry price for short position
    targetPriceShort := na  // Reset target price for short position
    stopLossShort := na  // Reset stop-loss for short position
    tradeActive := false

// Plot Buy and Sell Labels with Visibility Conditions
plotshape(showBuyLabels and buyCondition, "Buy", shape.labelup, location=location.belowbar, color=color.green, text="BUY", textcolor=color.white, size=size.tiny)
plotshape(showSellLabels and sellCondition, "Sell", shape.labeldown, location=location.abovebar, color=color.red, text="SELL", textcolor=color.white, size=size.tiny)

// Plot Take Profit Flags
plotshape(showBuyLabels and signalBuyTPPrint, title="Take Profit (buys)", text="TP", style=shape.flag, location=location.abovebar, color=colorTP, textcolor=color.white, size=size.tiny)
plotshape(showSellLabels and signalSellTPPrint, title="Take Profit (sells)", text="TP", style=shape.flag, location=location.belowbar, color=colorTP, textcolor=color.white, size=size.tiny)

// Plot Stop Loss "X" Marker
plotshape(showBuyLabels and signalBuySLPrint, title="Stop Loss (buys)", text="X", style=shape.xcross, location=location.belowbar, color=colorSL, textcolor=color.white, size=size.tiny)
plotshape(showSellLabels and signalSellSLPrint, title="Stop Loss (sells)", text="X", style=shape.xcross, location=location.abovebar, color=colorSL, textcolor=color.white, size=size.tiny)

// Alerts

alertcondition(buyCondition and alertOnCondition, title="Buy Alert", message='{"content": "Buy {{ticker}} at {{close}}"}')
alertcondition(sellCondition and alertOnCondition, title="Sell Alert", message='{"content": "Sell {{ticker}} at {{close}}"}')
alertcondition(signalBuyTPPrint and alertOnCondition, title="Buy TP Alert", message='{"content": "Buy TP {{ticker}} at {{close}}"}')
alertcondition(signalSellTPPrint and alertOnCondition, title="Sell TP Alert", message='{"content": "Sell TP {{ticker}} at {{close}}"}')
alertcondition(signalBuySLPrint and alertOnCondition, title="Buy SL Alert", message='{"content": "Buy SL {{ticker}} at {{close}}"}')
alertcondition(signalSellSLPrint and alertOnCondition, title="Sell SL Alert", message='{"content": "Sell SL {{ticker}} at {{close}}"}')

if buyCondition
    strategy.entry("Enter Long", strategy.long)
else if sellCondition
    strategy.entry("Enter Short", strategy.short)