브레이크아웃 트레일링 스톱을 기반으로 한 트렌드 전략


생성 날짜: 2023-09-14 20:34:02 마지막으로 수정됨: 2023-09-14 20:34:02
복사: 0 클릭수: 727
avatar of ChaoZhang ChaoZhang
1
집중하다
1617
수행원

이 글은 가격의 돌파구 입구와 스톱로드 퇴출을 추적하는 트렌드 트레이딩 전략에 대해 자세히 설명합니다. 이 전략은 가장 높은 지점을 돌파하여 다단위 포지션을 구축하고 변동의 낮은 지점을 사용하여 스톱로드를 추적합니다.

1 전략

이 전략의 주요 거래 논리는 다음과 같습니다.

  1. 진동 지표를 사용하여 최고 가격과 최저 가격의 변동점을 계산합니다.

  2. 가격의 최고점을 돌파할 때, 다중 입구로 입구합니다.

  3. 최근 낮은 변동이 급격한 정지점으로 사용되고 있습니다.

  4. 더 높은 변동의 낮은 지점이 발생했을 때, 중지 위치를 이동하여 추적 중지한다.

이렇게 함으로써, 가격이 상향 저항을 뚫고 강세를 보이는 트렌드 상황을 잡을 수 있다. 그리고 스톱포드의 지속적인 상승을 통해 이윤이 고정될 수 있다.

2 전략적 장점

이 전략의 주요 장점은 다음과 같습니다.

  1. 브레이크 엔트리는 트렌드의 시작 지점을 더 정확하게 파악할 수 있습니다.

  2. 동적으로 추적된 스톱로스는 수익을 최대화하고 회귀를 줄일 수 있습니다.

  3. 막힘 위치에는 막힘이 뚫리지 않도록 보호할 수 있는 완충구간이 있다.

  4. 또한, 역 동작을 방지하기 위해 일률적인 필터를 추가할 수 있다.

  5. 잠재적인 위험

그러나 이 전략에는 몇 가지 잠재적인 위험도 있습니다.

  1. 이 경우, 트렌드 초반의 기회를 놓칠 수 있는 돌파 신호가 뒤쳐질 수 있습니다.

  2. 너무 급진적이어서 불필요한 경기 중단으로 인해 손해가 발생할 수 있습니다.

  3. 하지만, 이 모든 것은,

네 가지 내용

이 글은 주로 가격 돌파구와 스톱로드를 추적하는 트렌드 전략에 대해 소개한다. 이는 트렌드를 효과적으로 추적하여 수익을 극대화 할 수 있지만 스톱로드가 돌파되는 위험을 예방하는 것도 필요하다. 종합적으로, 이 전략은 간단한 직관적인 트렌드 추적 방법을 제공한다.

전략 소스 코드
/*backtest
start: 2022-09-13 00:00:00
end: 2023-02-03 00:00:00
period: 1d
basePeriod: 1h
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}]
*/

//@version=4

// Revision:        1
// Author:          @millerrh
// Strategy:  Enter long when recent swing high breaks out, using recent swing low as stop level.  Move stops up as higher lows print to act
// as trailing stops.  Ride trend as long as it is there and the higher lows aren't breached.  
// Conditions/Variables 
//    1. Can place a user-defined percentage below swing low and swing high to use as a buffer for your stop to help avoid stop hunts
//    2. Can add a filter to only take setups that are above a user-defined moving average (helps avoid trading counter trend) 
//    3. Manually configure which dates to back test
//    4. Color background of backtested dates - allows for easier measuring buy & hold return of time periods that don't go up to current date    


// === CALL STRATEGY/STUDY, PROGRAMATICALLY ENTER STRATEGY PARAMETERS HERE SO YOU DON'T HAVE TO CHANGE THEM EVERY TIME YOU RUN A TEST ===
// (STRATEGY ONLY) - Comment out srategy() when in a study() 
strategy("Breakout Trend Follower", overlay=true, initial_capital=10000, currency='USD', 
   default_qty_type=strategy.percent_of_equity, default_qty_value=100, commission_type=strategy.commission.percent, commission_value=0.1)
// (STUDY ONLY) - Comment out study() when in a strategy() 
//study("Breakout Trend Follower", overlay=true)

// === BACKTEST RANGE ===
From_Year  = input(defval = 2019, title = "From Year")
From_Month = input(defval = 1, title = "From Month", minval = 1, maxval = 12)
From_Day   = input(defval = 1, title = "From Day", minval = 1, maxval = 31)
To_Year    = input(defval = 9999, title = "To Year")
To_Month   = input(defval = 1, title = "To Month", minval = 1, maxval = 12)
To_Day     = input(defval = 1, title = "To Day", minval = 1, maxval = 31)
Start  = timestamp(From_Year, From_Month, From_Day, 00, 00)  // backtest start window
Finish = timestamp(To_Year, To_Month, To_Day, 23, 59)        // backtest finish window

// A switch to control background coloring of the test period - Use for easy visualization of backtest range and manual calculation of 
// buy and hold (via measurement) if doing prior periods since value in Strategy Tester extends to current date by default
testPeriodBackground = input(title="Color Background - Test Period?", type=input.bool, defval=false)
testPeriodBackgroundColor = testPeriodBackground and (time >= Start) and (time <= Finish) ? #00FF00 : na
bgcolor(testPeriodBackgroundColor, transp=95)

// == FILTERING ==
// Inputs
useMaFilter = input(title = "Use MA for Filtering?", type = input.bool, defval = true)
maType = input(defval="SMA", options=["EMA", "SMA"], title = "MA Type For Filtering")
maLength   = input(defval = 50, title = "MA Period for Filtering", minval = 1)

// Declare function to be able to swap out EMA/SMA
ma(maType, src, length) =>
    maType == "EMA" ? ema(src, length) : sma(src, length) //Ternary Operator (if maType equals EMA, then do ema calc, else do sma calc)
maFilter = ma(maType, close, maLength)
plot(maFilter, title = "Trend Filter MA", color = color.green, linewidth = 3, style = plot.style_line, transp = 50)

// Check to see if the useMaFilter check box is checked, this then inputs this conditional "maFilterCheck" variable into the strategy entry 
maFilterCheck = if useMaFilter == true
    maFilter
else
    0

// === PLOT SWING HIGH/LOW AND MOST RECENT LOW TO USE AS STOP LOSS EXIT POINT ===
// Inputs
//pvtLenL       = input(3, minval=1, title="Pivot Length Left Hand Side") //use if you want to change this to an input
//pvtLenR       = input(3, minval=1, title="Pivot Length Right Hand Side") //use if you want to change this to an input
pvtLenL       = 3
pvtLenR       = 3

// Get High and Low Pivot Points
pvthi_ = pivothigh(high, pvtLenL, pvtLenR)
pvtlo_ = pivotlow(low, pvtLenL, pvtLenR)

// Force Pivot completion before plotting.
Shunt = 1 //Wait for close before printing pivot? 1 for true 0 for flase
maxLvlLen = 0 //Maximum Extension Length
pvthi = pvthi_[Shunt]
pvtlo = pvtlo_[Shunt]

// Count How many candles for current Pivot Level, If new reset.
counthi = barssince(not na(pvthi))
countlo = barssince(not na(pvtlo))
 
pvthis = fixnan(pvthi)
pvtlos = fixnan(pvtlo)
hipc = change(pvthis) != 0 ? na : color.maroon
lopc = change(pvtlos) != 0 ? na : color.green

// Display Pivot lines
plot((maxLvlLen == 0 or counthi < maxLvlLen) ? pvthis : na, color=hipc, transp=0, linewidth=1, offset=-pvtLenR-Shunt, title="Top Levels")
plot((maxLvlLen == 0 or countlo < maxLvlLen) ? pvtlos : na, color=lopc, transp=0, linewidth=1, offset=-pvtLenR-Shunt, title="Bottom Levels")
plot((maxLvlLen == 0 or counthi < maxLvlLen) ? pvthis : na, color=hipc, transp=0, linewidth=1, offset=0, title="Top Levels 2")
plot((maxLvlLen == 0 or countlo < maxLvlLen) ? pvtlos : na, color=lopc, transp=0, linewidth=1, offset=0, title="Bottom Levels 2")


// Stop Levels
stopBuff = input(0.0, minval=-2, title="Stop Loss Buffer off Swing Low (%)")
stopPerc = stopBuff*.01 // Turn stop buffer input into a percentage
stopLevel = valuewhen(pvtlo_, low[pvtLenR], 0) //Stop Level at Swing Low
stopLevel2 = stopLevel - stopLevel*stopPerc  // Stop Level with user-defined buffer to avoid stop hunts and give breathing room
plot(stopLevel2, style=plot.style_line, color=color.orange, show_last=1, linewidth=1, transp=50, trackprice=true)
buyLevel = valuewhen(pvthi_, high[pvtLenR], 0) //Buy level at Swing High
buyLevel2 = buyLevel + buyLevel*stopPerc // Buy-stop level with user-defined buffer to avoid stop hunts and give breathing room
plot(buyLevel2, style=plot.style_line, color=color.blue, show_last=1, linewidth=1, transp=50, trackprice=true)

// Conditions for entry and exit
buySignal = high > buyLevel2
buy = buySignal and time > Start and time < Finish and buyLevel2 > maFilterCheck // All these conditions need to be met to buy
sellSignal = low < stopLevel2 // Code to act like a stop-loss for the Study

// (STRATEGY ONLY) Comment out for Study
strategy.entry("Long", strategy.long, stop = buyLevel2, when = buyLevel2 > maFilterCheck)
strategy.exit("Exit Long", from_entry = "Long", stop=stopLevel2)

// == (STUDY ONLY) Comment out for Strategy ==
// Check if in position or not
inPosition = bool(na)
inPosition := buy[1] ? true : sellSignal[1] ? false : inPosition[1]
flat = bool(na)
flat := not inPosition
buyStudy = buy and flat
sellStudy = sellSignal and inPosition
//Plot indicators on chart and set up alerts for Study
plotshape(buyStudy, style = shape.triangleup, location = location.belowbar, color = #1E90FF, text = "Buy")
plotshape(sellStudy, style = shape.triangledown, location = location.abovebar, color = #EE82EE, text = "Sell")
alertcondition(buyStudy, title='Trend Change Follower Buy', message='Trend Change Follower Buy')

// Color background when trade active (for easier visual on what charts are OK to enter on)
tradeBackground = input(title="Color Background for Trades?", type=input.bool, defval=true)
tradeBackgroundColor = tradeBackground and inPosition ? #00FF00 : na
bgcolor(tradeBackgroundColor, transp=95)
noTradeBackgroundColor = tradeBackground and flat ? #FF0000 : na
bgcolor(noTradeBackgroundColor, transp=90)