ATR 기반 트렌드 추적 전략

저자:차오장, 날짜: 2024-01-05 16:28:48
태그:

img

전반적인 설명

이 전략은 평균 참 범위 (ATR) 를 기반으로 하는 트렌드 추적 전략이다. 이는 지표 값을 계산하고 가격 트렌드 방향을 결정하기 위해 ATR을 사용합니다. 이 전략은 또한 위험을 제어하기 위해 스톱 로스 메커니즘을 제공합니다.

전략 논리

이 전략은 세 가지 주요 매개 변수를 사용합니다. 기간, 증배자 및 입출점. 기본 매개 변수는 ATR의 14 기간과 4의 증배자입니다.

전략은 먼저 긴 평균 가격 (buyavg) 과 짧은 평균 가격 (sellavg) 을 계산하고, 그 다음 두 평균 사이의 가격 관계를 비교하여 현재 트렌드 방향을 결정합니다. 가격이 짧은 평균 가격보다 높으면 길고 가격이 긴 평균 가격보다 낮으면 짧다고 판단됩니다.

또한, 전략은 ATR을 통합하여 후속 스톱 손실을 설정합니다. 구체적으로, 그것은 스톱 손실 거리로 ATR의 14 기간 가중화 이동 평균을 곱한 배수자 (디폴트 4) 로 사용합니다. 이것은 스톱 손실 거리를 시장 변동성에 따라 조정 할 수 있습니다.

스톱 로스가 시작되면 전략은 이윤을 확보하기 위해 포지션을 닫습니다.

장점

  1. 트렌드 판단을 바탕으로, 이윤을 위해 지속적으로 트렌드를 따라갈 수 있습니다.
  2. ATR을 사용하여 동적으로 중지 손실 거리를 조정하고 위험을 효과적으로 제어합니다.
  3. 간단하고 직접적으로 입력 및 출구 포인트를 계산, 이해하기 쉽고 실행

위험 과 해결책

  1. 트렌드가 변할 때 큰 손실을 입을 수 있습니다.
    • ATR 기간과 멀티플리커를 합리적으로 조정하여 스톱 손실 거리를 최적화합니다.
  2. 다양한 시장에서 여러 개의 작은 손실을 발생시킬 것입니다
    • 시장의 범위를 피하기 위해 필터 조건을 추가
  3. 잘못된 매개 변수 설정은 전략 성능을 악화시킬 수 있습니다.
    • 최적을 찾기 위해 여러 매개 변수 최적화를 수행

최적화 방향

  1. 다양한 시장에서 포지션을 열지 않도록 필터링을 위한 다른 지표를 추가합니다.
  2. 정지 거리를 더 합리적으로 만들기 위해 ATR 기간과 곱셈 매개 변수를 최적화
  3. 시장 조건에 기반한 위치 사이즈 컨트롤 추가

결론

전체적으로 이것은 간단하고 실용적인 트렌드 추적 전략이다. 구현하기 위해 몇 가지 매개 변수만 필요하며, 위험을 효과적으로 제어하기 위해 스톱을 동적으로 조정하기 위해 ATR을 사용합니다. 필터링을위한 다른 보조 지표와 결합하면 추가로 최적화 될 수 있습니다. 일반적으로이 전략은 트렌드 추적 전략에 대해 배우고 싶은 사람들에게 적합하며 더 고급 전략의 기본 구성 요소로 사용될 수 있습니다.


/*backtest
start: 2022-12-29 00:00:00
end: 2024-01-04 00:00:00
period: 1d
basePeriod: 1h
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}]
*/

//@version=5
strategy('Trend Strategy by zdmre', shorttitle='Trend Strategy', overlay=true, pyramiding=0, currency=currency.USD, default_qty_type=strategy.percent_of_equity, initial_capital=10000, default_qty_value=100, commission_type=strategy.commission.percent, commission_value=0.005)
show_STOPLOSSprice = input(true, title='Show TrailingSTOP Prices')
src = input(close, title='Source')
out2 = ta.ema(src, 20)

buyavg = (close + high) / 2.02 - high * (1 - open / close) * (1 - low * open / (high * close))
sellavg = ((low + close) / 1.99 + low * (1 - low / open) * (1 - low * open / (close * high)) / 1.1 + out2 )/ 2

// === INPUT BACKTEST RANGE ===
fromMonth = input.int(defval=1, title='From Month', minval=1, maxval=12)
fromDay = input.int(defval=1, title='From Day', minval=1, maxval=31)
fromYear = input.int(defval=2021, title='From Year', minval=1970)
thruMonth = input.int(defval=1, title='Thru Month', minval=1, maxval=12)
thruDay = input.int(defval=1, title='Thru Day', minval=1, maxval=31)
thruYear = input.int(defval=2100, title='Thru Year', minval=1970)

// === INPUT SHOW PLOT ===
showDate = input(defval=true, title='Show Date Range')

// === FUNCTION EXAMPLE ===
start = timestamp(fromYear, fromMonth, fromDay, 00, 00)  // backtest start window
finish = timestamp(thruYear, thruMonth, thruDay, 23, 59)  // backtest finish window
window() => true


// === TRAILING STOP LOSS === //

ATR_Period = input(14)
ATR_Mult = input(4.0)
var float ATR_TrailSL = na
var int pos = na
atr = ta.rma (ta.tr(true), 14)
xATR = ta.atr(ATR_Period)
nLoss = ATR_Mult * xATR

iff_1 = close > nz(ATR_TrailSL[1], 0) ? close - nLoss : close + nLoss
iff_2 = close < nz(ATR_TrailSL[1], 0) and close[1] < nz(ATR_TrailSL[1], 0) ? math.min(nz(ATR_TrailSL[1]), close + nLoss) : iff_1
ATR_TrailSL := close > nz(ATR_TrailSL[1], 0) and close[1] > nz(ATR_TrailSL[1], 0) ? math.max(nz(ATR_TrailSL[1]), close - nLoss) : iff_2

iff_3 = close[1] > nz(ATR_TrailSL[1], 0) and close < nz(ATR_TrailSL[1], 0) ? -1 : nz(pos[1], 0)
pos := close[1] < nz(ATR_TrailSL[1], 0) and close > nz(ATR_TrailSL[1], 0) ? 1 : iff_3

atr_color = pos == -1 ? color.green : pos == 1 ? color.red : color.aqua
atrtrend = plot(ATR_TrailSL, 'Trailing StopLoss', atr_color, linewidth=2)

// ===  Stop Loss === //
slGroup = 'Stop Loss'
useSL = input.bool(false, title='╔══════   Enable   ══════╗', group=slGroup, tooltip='If you are using this strategy for Scalping or Futures market, we do not recommend using Stop Loss.')
SLbased = input.string(title='Based on', defval='Percent', options=['ATR', 'Percent'], group=slGroup, tooltip='ATR: Average True Range\nPercent: eg. 5%.')
multiATR = input.float(10.0, title='ATR   Mult', group=slGroup, inline='atr')
lengthATR = input.int(14, title='Length', group=slGroup, inline='atr')
SLPercent = input.float(5, title='Percent', group=slGroup) * 0.01
Shortposenter = input.bool(false, title='ShortPosition')

longStop = 0.0
shortStop = 0.0

if SLbased == 'ATR'
    longStop := ta.valuewhen(pos == 1, low, 0) - ta.valuewhen(pos == 1, ta.rma(ta.tr(true), lengthATR), 0) * multiATR
    longStopPrev = nz(longStop[1], longStop)
    longStop := close[1] > longStopPrev ? math.max(longStop, longStopPrev) : longStop

    shortStop := ta.valuewhen(pos == -1, ta.rma(ta.tr(true), lengthATR), 0) * multiATR + ta.valuewhen(pos == -1, high, 0)
    shortStopPrev = nz(shortStop[1], shortStop)
    shortStop := close[1] > shortStopPrev ? math.max(shortStop, shortStopPrev) : shortStop
    shortStop
if SLbased == 'Percent'
    longStop := strategy.position_avg_price * (1 - SLPercent)
    shortStop := strategy.position_avg_price * (1 + SLPercent)
    shortStop
exitLong  = pos == -1 

// === PlotColor === //
buySignal = pos == 1 and pos[1] == -1
plotshape(buySignal, title="Long", location=location.belowbar, style=shape.labelup, size=size.normal, color=color.new(color.green,50), text='Buy', textcolor=color.white)
exitSignal = pos == -1 and pos[1] == 1
plotshape(exitSignal, title="Exit", location=location.abovebar, style=shape.labeldown, size=size.normal, color=color.new(color.red,50), text='Exit', textcolor=color.white)

hPlot = plot(ohlc4, title="", style=plot.style_circles, linewidth=0, editable = false)
longFill = (pos == 1 ? color.new(color.green,80) : na) 
shortFill = (pos == -1 ? color.new(color.red,80) : na)
fill(hPlot, atrtrend,color=longFill)
fill(hPlot,atrtrend, color=shortFill)

// === Strategy === //
strategy.entry('Long', strategy.long,limit = buyavg, when=window() and pos == 1,comment="Entry: "+str.tostring(buyavg))
strategy.close('Long', when=window() and exitLong , comment='Exit: '+str.tostring(sellavg) )

if Shortposenter
    strategy.entry('Short', strategy.short, when=window() and pos== -1,comment="Entry: "+str.tostring(close))
    strategy.close('Short', when=window() and pos == 1 , comment='Exit: ')

if useSL
    strategy.exit('Stop Loss', 'Long', stop=longStop)
    
// === Show StopLoss Price === //
if show_STOPLOSSprice
    if pos == -1
        label ShortStop = label.new(bar_index, na, 'SL: ' + str.tostring(ATR_TrailSL), color=color.green, textcolor=color.white, style=label.style_none, yloc=yloc.abovebar, size=size.small)
        label.delete(ShortStop[1])

    if pos == 1
        label LongStop = label.new(bar_index, na, 'SL: ' + str.tostring(ATR_TrailSL), color=color.red, textcolor=color.white, style=label.style_none, yloc=yloc.belowbar, size=size.small)
        label.delete(LongStop[1])

더 많은