Breakout Trend Follower V2


생성 날짜: 2023-11-01 17:24:08 마지막으로 수정됨: 2023-11-01 17:24:08
복사: 0 클릭수: 746
avatar of ChaoZhang ChaoZhang
1
집중하다
1617
수행원

Breakout Trend Follower V2

개요

이 전략은 제가 이전에 사용한 다른 돌파 트렌드 추적자 전략의 변형입니다. 다른 전략에서는 이동 평균을 거래의 필터로 사용할 수 있습니다. 즉, 가격이 이동 평균보다 낮으면 더 많은 일을하지 않습니다. 더 높은 시간 프레임의 트렌드를 감지하는 도구를 만든 후, 이동 평균보다 더 나은 필터가 될 수 있는지보고 싶습니다.

따라서, 이 전략은 더 높은 시간 프레임의 트렌드를 볼 수 있습니다 (즉, 더 높은 고도와 더 낮은 저도가 있습니까? 만약 그렇다면, 이것은 상승 추세입니다). 당신은 트렌드 방향으로만 포지션합니다. 당신은 필터로 최대 두 가지의 트렌드를 선택할 수 있습니다.

저는 이 전략이 다른 전략에 비해 일반적으로 잘 작동하지 않는다는 것을 알았습니다. 하지만 실제로는 거래에 대해 더 신중한 것처럼 보입니다. 더 높은 승률과 더 나은 수익 요소를 보여줍니다.

전략 원칙

이 전략의 핵심 논리는 높은 시간 프레임을 뚫는 지지점과 저항점을 사용하여 트렌드를 식별하고 트렌드 방향에 따라 거래하는 것입니다.

특히, 다음과 같은 단계로 이루어집니다.

  1. 현재 시간 프레임 (예: 1시간 라인) 의 지지점과 저항점을 계산한다. 이것은 일정한 주기 내의 최고 가격과 최저 가격을 찾아서 이루어진다.

  2. 하나의 또는 더 높은 시간 프레임 (예: 4 시간선과 일선) 의 지지점과 저항점을 계산한다. 이는 현재 시간 프레임과 동일한 논리를 사용하여 구현된다.

  3. 이 지지점과 저항점의 수평선을 차트에 그리십시오. 가격이 이 수준을 넘으면 더 높은 시간 프레임의 추세가 바니다.

  4. 가격이 이러한 핵심 수준을 돌파했는지에 따라 트렌드 방향을 결정한다. 가격이 높은 곳을 돌파하면 상승 추세로 간주한다. 이전 낮은 곳을 돌파하면 하락 추세로 간주한다.

  5. 사용자가 1개 이상의 상위 시간 프레임의 트렌드를 필터링 조건으로 선택할 수 있습니다. 즉, 거래는 현재 시간 프레임의 트렌드 방향이 상위 시간 프레임의 트렌드 방향과 일치하는 경우에만 고려됩니다.

  6. 트렌드 필터 조건이 충족되고 현재 가격이 중요한 수준을 돌파했을 때 구매 또는 판매합니다. 정지 손실 수준은 이전 중요한 지원 또는 저항 수준으로 설정됩니다.

  7. 가격이 움직일 때, 새로운 고점이나 낮은 점이 형성되면, 이윤을 고정하고 추세를 추적하기 위해 새로운 낮은 곳으로 스톱로스를 이동합니다.

  8. 정지 손실이 발생하거나 중요한 지지/저항이 뚫렸을 때 평점으로 빠져나갑니다.

이 다중 시간 프레임의 트렌드 분석을 통해, 전략은 승리 가능성을 높이기 위해 강한 트렌드 방향으로만 거래를 시도합니다. 동시에, 중요한 수준은 명확한 입시 및 중단 신호를 제공합니다.

전략적 이점

  • 여러 시간 프레임을 사용하여 트렌드를 판단하면 강력한 트렌드 방향을 더 정확하게 식별할 수 있으며 시장 소음으로 오해받지 않습니다.

  • 주요 트렌드 방향으로만 작동하면 승률을 크게 높일 수 있다. 테스트 결과에 따르면, 이 전략은 간단한 이동 평균 필터링에 비해 더 높은 승률과 더 나은 수익 위험 비율을 나타낸다.

  • 지원 및 저항 지점은 명확한 진입 및 중단 수준을 제공합니다. 특정 진입 지점 선택에 얽매이지 않아도됩니다.

  • 트렌드가 진행됨에 따라 스톱로스를 조정하여 최대 수익을 고정시킬 수 있습니다.

  • 전략 논리는 간단하고 명확하며, 이해하기 쉽고 조정하기 쉽습니다.

전략적 위험

  • 더 긴 선분에 의존하는 경향 판단은 트렌드 반전이 있을 때 쉽게 틀릴 수 있다. 트렌드를 판단하는 시기를 적절히 단축하거나, 다른 지표가 보조 판단을 사용한다.

  • 근본적인 측면의 영향을 고려하지 않고, 중요한 사건이 발생했을 때 주식 가격과 오차가 발생할 수 있습니다. ATM 이벤트 또는 수익 보고서 날짜와 같은 필터 조건을 추가 할 수 있습니다.

  • 위치 규모 제어 설정이 없습니다. 계정 자금 규모, 변동률 등의 요소에 따라 위치 크기를 설정할 수 있습니다.

  • 응답 시간 범위는 제한된다. 응답 시간 범위를 확장하여 다양한 시장 환경에서의 안정성을 테스트한다.

  • 거래 비용의 영향을 고려하지 않는다. 실장에서는 특정 거래 비용에 따라 전략 매개 변수를 조정해야 한다.

  • 긴 라인 거래만 고려한다. 다른 전략과 결합하여 짧은 라인 거래 신호를 개발하여 다주기 중매를 실현한다.

전략 최적화 방향

  • 필터 조건 추가:

    • 수익 보고, 뉴스 이벤트 등과 같은 기본 자료

    • 거래량, ATR 상쇄 등과 같은

  • 최적화 변수:

    • 지원/저항 비트 계산 주기 조정

    • 트렌드 판단을 조정하는 시간적 프레임

  • 전략의 폭을 넓히기 위해:

    • 단선거래 전략을 개발

    • 매각 기회를 고려하세요

    • 다종류 중도

  • 위험 관리:

    • 변동성 및 자본 규모에 따라 최적화된 포지션 크기

    • 이동식 상장, 상장 상장 등의 최적화된 상장 전략

    • 위험 보상 징계 제도를 도입합니다.

  • 실행 로직을 최적화합니다.

    • 출전 시점 변경

    • 일부 입장을 고려

    • 손해배상 이동 전략을 최적화

요약하다

이 전략은 다중 시간 프레임의 트렌드를 분석하여 보다 견고한 돌파구 시스템을 설계한다. 단순한 이동 평균과 같은 지표 필터링에 비해 더 높은 승률과 수익 위험 비율을 보여주고 있다. 그러나 또한 위험 관리 장치가 완벽하지 않고 기본 요소를 고려하지 않은 것과 같은 최적화 가능한 측면이 있다. 추가적으로 최적화하면 매우 실용적인 트렌드 추적 전략이 될 수 있다.

전략 소스 코드
/*backtest
start: 2023-10-24 00:00:00
end: 2023-10-26 00:00:00
period: 5m
basePeriod: 1m
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.  
// The difference between this one and the previous Breakout Trend Follower is that this one uses higher timeframe higher highs/higher lows as a filter instead 
// of an arbitrary Moving Average.  I wanted to test out whether waiting for longer term actual trend changes produced better stats than just the moving average.
// Conditions/Variables 
//    1. Manually configure which dates to back test
//    2. Can add a filter to only take setups that are above (or below for shorts) user-defined larger timeframe trends (helps avoid trading counter trend) 

// === 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 V2", 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 V2", overlay=true)

// === BACKTEST RANGE ===
Start = input(defval = timestamp("01 Jan 2019 06:00 +0000"), title = "Backtest Start Date", type = input.time, group = "Backtest Range")
Finish = input(defval = timestamp("01 Jan 2100 00:00 +0000"), title = "Backtest End Date", type = input.time, group = "Backtest Range")

// == USER INPUTS ==
tableLocation = input(defval="Top", options=["Top", "Bottom"], title = "Info Table Location", group = "Display",
  tooltip = "Place information table on the top of the pane or the bottom of the pane.")
lookback = input(defval = 3, title = "Pivot Lookback Period", group = "Pivot Points",
  tooltip = "Looks for pivot points within this number of bars both left and right.")
showPivotPoints = input(title = "Show Historical Pivot Points?", type = input.bool, defval = false, group = "Pivot Points",
  tooltip = "Toggle this on to see the historical pivot points that were used.  Change the Lookback Period to adjust the frequency of these points.
  The pivot points are only shown for the current chart timeframe - to see the Daily pivot pionts, use the Daily timeframe, etc.")
trendFilter = input(defval="1st Timeframe", options=["1st Timeframe", "Both Timeframes", "None"], title = "Use HTF Trend for Filtering?", group = "Higher Timeframe Levels",
  tooltip = "Signals will be ignored when price is not aligned with the higher timeframe trend(s).  The intent is to keep you out of bear periods and only buying when 
  price is showing strength and you are trading with the trend.")
twoSet = input(defval="D", title="1st High Timeframe", type=input.resolution, group = "Higher Timeframe Levels",
  tooltip = "Allows you to set two different time frames for looking at the trend.")
threeSet = input(defval="W", title="2nd High Timeframe", type=input.resolution, group = "Higher Timeframe Levels")
showMTFLevels = input(title = "Show Multiple Timeframe S/R Levels?", type = input.bool, defval = true, group = "Higher Timeframe Levels",
  tooltip = "Displays the pivot highs and lows of higher timeframes to use as support/resistance levels. When these levels break, the trend
  will change on these higher timeframes.")
currentColorS = input(color.new(color.orange,50), title = "Current Timeframe    Support", type = input.color, group = "Higher Timeframe Levels", inline = "MTF1")
currentColorR = input(color.new(color.blue,50), title = " Resistance", type = input.color, group = "Higher Timeframe Levels", inline = "MTF1")
oneColorS = input(color.new(color.yellow,50), title = "1st High Timeframe   Support", type = input.color, group = "Higher Timeframe Levels", inline = "MTF2")
oneColorR = input(color.new(color.yellow,50), title = " Resistance", type = input.color, group = "Higher Timeframe Levels", inline = "MTF2")
twoColorS = input(color.new(color.white,50), title = "2nd High Timeframe    Support", type = input.color, group = "Higher Timeframe Levels", inline = "MTF3")
twoColorR = input(color.new(color.white,50), title = " Resistance", type = input.color, group = "Higher Timeframe Levels", inline = "MTF3")

//  == DEFINE FUNCTIONS FOR USE IN MULTIPLE TIMEFRAMES (USING A TUPLE TO AVOID SO MANY SECURITY CALLS) ==  
f_getHTF() =>
    ph = pivothigh(high, lookback, lookback)
    pl = pivotlow(low, lookback, lookback)
    highLevel = valuewhen(ph, high[lookback], 0)
    lowLevel = valuewhen(pl, low[lookback], 0)
    barsSinceHigh = barssince(ph) + lookback
    barsSinceLow = barssince(pl) + lookback
    timeSinceHigh = time[barsSinceHigh]
    timeSinceLow = time[barsSinceLow]
    [ph, pl, highLevel, lowLevel, barsSinceHigh, barsSinceLow, timeSinceHigh, timeSinceLow]
    
[ph_01, pl_01, hL_01, lL_01, bsSH_01, bsSL_01, tSH_01, tSL_01] = security(syminfo.tickerid, "", f_getHTF())
[ph_02, pl_02, hL_02, lL_02, bsSH_02, bsSL_02, tSH_02, tSL_02] = security(syminfo.tickerid, twoSet, f_getHTF())
[ph_03, pl_03, hL_03, lL_03, bsSH_03, bsSL_03, tSH_03, tSL_03] = security(syminfo.tickerid, threeSet, f_getHTF())

// Plot historical pivot points for debugging and configuring the lookback period.
plot(showPivotPoints ? ph_01 : na, style=plot.style_cross, linewidth=3, color=color.new(color.yellow,50), offset=-lookback)
plot(showPivotPoints ? pl_01 : na, style=plot.style_cross, linewidth=3, color=color.new(color.yellow,50), offset=-lookback)

// == PLOT SUPPORT/RESISTANCE LINES ON THE HIGHER TIMEFRAMES ==
// Use a function to define the lines
f_line(x1, y1, y2, _color) =>
    var line id = na
    // line.delete(id)
    // id := line.new(x1, y1, time, y2, xloc.bar_time, extend.right, _color)

// 1st Timeframe
highLine1 = showMTFLevels ? f_line(tSH_01, hL_01, hL_01, currentColorR) : na
lowLine1 = showMTFLevels ? f_line(tSL_01, lL_01, lL_01, currentColorS) : na 
// 2nd Timeframe
highLine2 = showMTFLevels ? f_line(tSH_02, hL_02, hL_02, oneColorR) : na
lowLine2 = showMTFLevels ? f_line(tSL_02, lL_02, lL_02, oneColorS) : na
// 3rd Timeframe
highLine3 = showMTFLevels ? f_line(tSH_03, hL_03, hL_03, twoColorR) : na
lowLine3 = showMTFLevels ? f_line(tSL_03, lL_03, lL_03, twoColorS) : na

// == TREND CALCULATIONS (USING A TUPLE TO CONSOLIDATE REPETATIVE CODE AND GENERATE MULTIPE VARIABLES WITH ONE FUNCTION ==
f_signal(highLevel, lowLevel) =>
    uptrendSignal    = high > highLevel
    downtrendSignal  = low < lowLevel
    inUptrend        = bool(na)
    inDowntrend      = bool(na) 
    inUptrend       := uptrendSignal[1] ? true : downtrendSignal[1] ? false : inUptrend[1]
    inDowntrend     := not inUptrend
    [uptrendSignal, downtrendSignal, inUptrend, inDowntrend]

[uptrendSignal1, downtrendSignal1, inUptrend1, inDowntrend1] = f_signal(hL_01, lL_01)  // 1st Timeframe
[uptrendSignal2, downtrendSignal2, inUptrend2, inDowntrend2] = f_signal(hL_02, lL_02)  // 2nd Timeframe
[uptrendSignal3, downtrendSignal3, inUptrend3, inDowntrend3] = f_signal(hL_03, lL_03)  // 3rd Timeframe

// == TREND TABLE PLOTTING ==
tablePos = tableLocation == "Top" ? position.top_right : position.bottom_right
var table trendTable = table.new(tablePos, 3, 1, border_width = 3)
upColor = color.rgb(38, 166, 154)
downColor = color.rgb(240, 83, 80)

f_fillCell(_column, _row, _cellText, _c_color) =>
    table.cell(trendTable, _column, _row, _cellText, bgcolor = color.new(_c_color, 70), text_color = _c_color, width = 6)

if barstate.islast or barstate.islastconfirmedhistory
    f_fillCell(0, 0, inUptrend1 ? "▲" : "▼", inUptrend1 ? upColor : downColor)
    f_fillCell(1, 0, inUptrend2 ? "▲ " + twoSet : "▼ " + twoSet, inUptrend2 ? upColor : downColor)
    f_fillCell(2, 0, inUptrend3 ? "▲ " + threeSet : "▼ " + threeSet, inUptrend3 ? upColor : downColor)

// Conditions for entry and exit
buyConditions =  true
buySignal = high > hL_01 and buyConditions // Code to act like a stop-buy for the Study
sellSignal = low < lL_01 // Code to act like a stop-loss for the Study

// (STRATEGY ONLY) Comment out for Study
strategy.entry("Long", strategy.long, stop = hL_01, when = buyConditions)
// strategy.entry("Long", strategy.long, stop = buyLevel2, when = time > Start and time < Finish and high > maFilterCheck)
strategy.exit("Exit Long", from_entry = "Long", stop=lL_01)