트래일링 스톱 로스로 슈퍼 트렌드 전략

저자:차오장, 날짜: 2023-11-28 14:56:59
태그:

img

전반적인 설명

이 전략은 평균 참 범위 (ATR) 표시를 기반으로 움직이는 스톱 로스 라인과 반전 라인을 설계합니다. 가격 움직임에 따라 스톱 로스를 추적합니다. 구체적으로, 가격 움직임이 1%를 초과하면 스톱 로스는 일정한 비율로 수익 방향으로 이동합니다. 가격이 스톱 로스 라인을 통과하면 포지션은 자동으로 닫힐 것입니다. 이것은 이익을 잠금하고 손실을 줄일 수 있습니다.

전략 논리

이 전략은 ATR 지표를 사용하여 스톱 로스 라인을 계산합니다. 구체적인 공식은 다음과 같습니다.

atr = multplierFactor * atr(barsBack)

longStop = hl2 - atr  
shortStop = hl2 + atr

여기서 multiplicerFactor는 ATR 곱셈자이고 barsBack는 ATR 기간입니다. ATR 값이 클수록 시장 변동이 커집니다.

롱 스톱 및 쇼트 스톱 스톱 손실 라인은 ATR 값에 따라 계산됩니다. 거래 신호는 가격이 이 두 라인을 초과하면 작동합니다.

또한 방향 변수를 도입하여 트렌드 방향을 결정합니다.

direction = 1 
direction := nz(direction[1], direction)
direction := direction == -1 and close > shortStopPrev ? 1 : direction == 1 and close < longStopPrev ? -1 : direction 

방향이 1이면 상승 추세를 나타냅니다. 방향이 -1이면 하락 추세를 나타냅니다.

방향 변수 값에 따라 다른 색상의 스톱 손실 라인이 그려집니다.

if (direction == 1)
    valueToPlot := longStop
    colorToPlot := color.green
else  
    valueToPlot := shortStop 
    colorToPlot := color.red  

이것은 현재 트렌드 방향과 스톱 로스 라인 위치를 명확히 보여줍니다.

후속 스톱 손실

이 전략의 핵심은 가격 움직임에 따라 실시간으로 스톱 로스 라인을 조정할 수 있는 후속 스톱 로스 메커니즘을 도입하는 것입니다.

구체적인 논리는 다음과 같습니다.

strategyPercentege = (close - updatedEntryPrice) / updatedEntryPrice * 100.00
rideUpStopLoss = hasOpenTrade() and strategyPercentege > 1 

if (rideUpStopLoss)
    stopLossPercent := stopLossPercent + strategyPercentege - 1.0
    newStopLossPrice = updatedEntryPrice + (updatedEntryPrice * stopLossPercent) / 100
    stopLossPrice := max(stopLossPrice, newStopLossPrice)
    updatedEntryPrice := stopLossPrice

만약 가격이 입시 가격에 비해 1% 이상 상승한다면, 스톱 로스는 상승할 것입니다. 조정 범위는 1%를 초과한 부분입니다.

이것은 손실을 줄이는 동시에 더 많은 이익을 얻을 수 있습니다.

이점 분석

전통적인 이동 스톱 손실 전략과 비교하면 이 전략의 가장 큰 장점은 시장 조건에 따라 스톱 손실 라인을 동적으로 조정할 수 있다는 것입니다. 구체적인 장점은 다음과 같습니다.

  1. 트렌딩 시장에서 더 높은 수익 체제를 달성

    트레일링 스톱 로스 메커니즘은 스톱 로스 라인이 수익 방향으로 계속 움직일 수 있도록 합니다. 시장이 계속 강화될 때 더 높은 수익을 얻을 수 있습니다.

  2. 범위를 제한하는 시장에서 스톱 로스 간격의 위험을 줄이십시오.

    시장 트렌드가 변할 때, 고정 이동 스톱 손실은 건너뛰는 경향이 있습니다. 이 전략의 스톱 손실 라인은 시장 변동성에 따라 계산되며, 이는 가격 변화를 합리적으로 추적하고 통합에서 건너뛰지 않도록 할 수 있습니다.

  3. 간단한 조작, 자동화하기 쉬운

    이 전략은 복잡한 트렌드 판단 논리가 없이 전체적으로 지표 계산에 기반하고 있습니다. 쉽게 자동화 될 수 있습니다.

  4. 각기 다른 제품에 적합한 사용자 정의 가능한 매개 변수

    ATR 기간, 곱셈 인수, 스톱 손실 비율과 같은 매개 변수는 사용자 정의 할 수 있습니다. 전략은 더 다재다능하게 만들기 위해 다른 제품에 최적화 될 수 있습니다.

위험 분석

이 전략은 많은 장점을 가지고 있지만 다음과 같은 위험 요소를 주목해야 합니다.

  1. 트렌드 반전 지점을 결정할 수 없으므로 높은 가격에 구매하고 낮은 가격에 판매 할 위험이 있습니다.

    트렌드가 끝났는지 판단하는 이 전략에는 논리가 없습니다. 불 시장의 끝에서 높은 가격에 구매하고 낮은 가격에 판매하는 경향이 있습니다.

  2. 부적절한 매개 변수 설정은 손실을 증폭시킬 수 있습니다

    ATR 기간 매개 변수가 너무 짧게 설정되면, 스톱 로스 라인은 너무 민감하게 작용하고 오스실레이션 시장으로 인해 자주 발생할 수 있습니다.

  3. 바닥 낚시 리바운드에서 중단 될 위험

    이 전략은 중요한 포인트를 스톱 로스 지원으로 간주하지 않습니다. 따라서 단기 인하 시 시장에서 쫓겨날 수도 있습니다.

위의 위험을 해결하기 위해 최적화는 다음과 같은 측면에서 수행 할 수 있습니다.

  1. 트렌드 반전을 미리 예측하기 위해 트렌드 필터링 지표를 포함합니다.

  2. 최적의 매개 변수 조합을 선택하기 위한 매개 변수 최적화 테스트

  3. 특정 지원 수준 근처에서 중지 손실 범위를 확장

최적화 방향

이 전략은 더 이상 최적화 할 수 있습니다.

  1. 촛불 패턴 인식

    트렌드 반전 가능성을 판단하기 위해 분차와 내리는 별과 같은 몇 가지 전형적인 촛불 패턴을 식별하십시오. 이것은 높은 구매와 낮은 판매의 위험을 피할 수 있습니다.

  2. 후속 매개 변수의 동적 최적화

    ATR 기간과 곱셈 인수와 같은 매개 변수가 동적으로 변경되도록 허용하십시오. 크게 변동하는 시장에서 더 긴 ATR 기간과 더 넓은 스톱 로스 범위를 사용하십시오.

  3. 머신러닝 모델을 도입

    LSTM, RNN 및 다른 딥 러닝 모델을 사용하여 가능한 미래의 가격 범위를 예측하고 스톱 로스 거리를 동적으로 조정합니다.

요약

요약하자면, 이 전략은 ATR 지표를 활용하여 움직이는 스톱 로스 라인을 설계하고, 시장 변화에 따라 실시간으로 스톱 로스 위치를 조정할 수 있는 후속 스톱 로스 메커니즘을 도입한다. 이는 더 높은 수익 잠금과 동시에 위험을 줄여준다. 추가 최적화로, 이 전략은 다양한 시장 상황에 더 적응력을 갖추고 견고한 거래 전략으로 작용할 수 있다.


/*backtest
start: 2022-11-21 00:00:00
end: 2023-11-27 00:00:00
period: 1d
basePeriod: 1h
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}]
*/

//@version=4
//
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ 
//  -----------------------------------------------------------------------------
//  Copyright 2019 Mauricio Pimenta | exit490
//  SuperTrend with Trailing Stop Loss script may be freely distributed under the MIT license.
//
//  Permission is hereby granted, free of charge, 
//  to any person obtaining a copy of this software and associated documentation files (the "Software"), 
//  to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, 
//  publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, 
//  subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 
//  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 
//  DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//  -----------------------------------------------------------------------------
//
//  Authors:  @exit490
//  Revision: v1.0.0
//  Date:     5-Aug-2019
//
//  Description
//  ===========
//  SuperTrend is a moving stop and reversal line based on the volatility (ATR).
//  The strategy will ride up your stop loss when price moviment 1%.
//  The strategy will close your operation when the market price crossed the stop loss.
//  The strategy will close operation when the line based on the volatility will crossed
//
//  The strategy has the following parameters:
//
//  INITIAL STOP LOSS - Where can isert the value to first stop.
//  POSITION TYPE - Where can to select trade position.
//  ATR PERIOD - To select number of bars back to execute calculation
//  ATR MULTPLIER - To add a multplier factor on volatility
//  BACKTEST PERIOD - To select range.
//  
//  -----------------------------------------------------------------------------
//  Disclaimer:
//    1. I am not licensed financial advisors or broker dealers. I do not tell you 
//       when or what to buy or sell. I developed this software which enables you 
//       execute manual or automated trades multplierFactoriplierFactoriple trades using TradingView. The 
//       software allows you to set the criteria you want for entering and exiting 
//       trades.
//    2. Do not trade with money you cannot afford to lose.
//    3. I do not guarantee consistent profits or that anyone can make money with no 
//       effort. And I am not selling the holy grail.
//    4. Every system can have winning and losing streaks.
//    5. Money management plays a large role in the results of your trading. For 
//       example: lot size, account size, broker leverage, and broker margin call 
//       rules all have an effect on results. Also, your Take Profit and Stop Loss 
//       settings for individual pair trades and for overall account equity have a 
//       major impact on results. If you are new to trading and do not understand 
//       these items, then I recommend you seek education materials to further your
//       knowledge.
//
//    YOU NEED TO FIND AND USE THE TRADING SYSTEM THAT WORKS BEST FOR YOU AND YOUR 
//    TRADING TOLERANCE.
//
//    I HAVE PROVIDED NOTHING MORE THAN A TOOL WITH OPTIONS FOR YOU TO TRADE WITH THIS PROGRAM ON TRADINGVIEW.
//    
//    I accept suggestions to improve the script.
//    If you encounter any problems I will be happy to share with me.
//  -----------------------------------------------------------------------------
//
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ //

strategy(title = "SUPERTREND ATR WITH TRAILING STOP LOSS",
         shorttitle = "SUPERTREND ATR WITH TSL",
         overlay = true,
         precision = 8,
         calc_on_order_fills = true,
         calc_on_every_tick = true,
         backtest_fill_limits_assumption = 0,
         default_qty_type = strategy.percent_of_equity,
         default_qty_value = 100,
         initial_capital = 1000,
         currency = currency.USD,
         linktoseries = true)

//
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ //

// === BACKTEST RANGE ===
backTestSectionFrom = input(title = "═══════════════ FROM ═══════════════", defval = true, type = input.bool)

FromMonth       = input(defval = 1, title = "Month", minval = 1)
FromDay         = input(defval = 1, title = "Day", minval = 1)
FromYear        = input(defval = 2019, title = "Year", minval = 2014)

backTestSectionTo = input(title = "════════════════ TO ════════════════", defval = true, type = input.bool)
ToMonth         = input(defval = 31, title = "Month", minval = 1)
ToDay           = input(defval = 12, title = "Day", minval = 1)
ToYear          = input(defval = 9999, title = "Year", minval = 2014)

backTestPeriod() => (time > timestamp(FromYear, FromMonth, FromDay, 00, 00)) and (time < timestamp(ToYear, ToMonth, ToDay, 23, 59))

//
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ //

parameterSection = input(title = "═════════════ STRATEGY ═════════════", defval = true, type = input.bool)
// === INPUT TO SELECT POSITION ===
positionType = input(defval="LONG", title="Position Type", options=["LONG", "SHORT"])

// === INPUT TO SELECT INITIAL STOP LOSS
initialStopLossPercent = input(defval = 3.0, minval = 0.0, title="Initial Stop Loss")

// === INPUT TO SELECT BARS BACK
barsBack = input(title="ATR Period", defval=1)

// === INPUT TO SELECT MULTPLIER FACTOR 
multplierFactor = input(title="ATR multplierFactoriplier", step=0.1, defval=3.0)

//
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ //

// LOGIC TO FIND DIRECTION WHEN THERE IS TREND CHANGE ACCORDING VOLATILITY
atr = multplierFactor * atr(barsBack)

longStop = hl2 - atr
longStopPrev = nz(longStop[1], longStop)
longStop := close[1] > longStopPrev ? max(longStop, longStopPrev) : longStop

shortStop = hl2 + atr
shortStopPrev = nz(shortStop[1], shortStop)
shortStop := close[1] < shortStopPrev ? min(shortStop, shortStopPrev) : shortStop

direction = 1
direction := nz(direction[1], direction)
direction := direction == -1 and close > shortStopPrev ? 1 : direction == 1 and close < longStopPrev ? -1 : direction

longColor = color.blue
shortColor = color.blue

var valueToPlot = 0.0
var colorToPlot = color.white

if (direction == 1)
    valueToPlot := longStop
    colorToPlot := color.green
else
    valueToPlot := shortStop
    colorToPlot := color.red

//
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ //
//
// === GLOBAL VARIABLES AND FUNCTIONS TO STORE IMPORTANT CONDITIONALS TO TRAILING STOP
hasEntryLongConditional() => direction == 1
hasCloseLongConditional() => direction == -1

hasEntryShortConditional() => direction == -1
hasCloseShortConditional() => direction == 1

stopLossPercent = positionType == "LONG" ? initialStopLossPercent * -1 : initialStopLossPercent

var entryPrice = 0.0
var updatedEntryPrice = 0.0
var stopLossPrice = 0.0

hasOpenTrade() => strategy.opentrades != 0
notHasOpenTrade() => strategy.opentrades == 0

strategyClose() =>
    if positionType == "LONG"
        strategy.close("LONG", when=true)
    else 
        strategy.close("SHORT", when=true)

strategyOpen() =>
    if positionType == "LONG"
        strategy.entry("LONG", strategy.long, when=true)
    else 
        strategy.entry("SHORT", strategy.short, when=true)

isLong() => positionType == "LONG" ? true : false
isShort() => positionType == "SHORT" ? true : false


//
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ //
//
// === LOGIC TO TRAILING STOP IN LONG POSITION

if (isLong() and backTestPeriod())

    crossedStopLoss = close <= stopLossPrice
    terminateOperation = hasOpenTrade() and (crossedStopLoss or hasCloseLongConditional())

    if (terminateOperation)
        entryPrice := 0.0
        updatedEntryPrice := entryPrice
        stopLossPrice := 0.0
        strategyClose()
    
    startOperation = notHasOpenTrade() and hasEntryLongConditional()

    if(startOperation)
        entryPrice := close
        updatedEntryPrice := entryPrice
        stopLossPrice := entryPrice + (entryPrice * stopLossPercent) / 100
        strategyOpen()
        
    strategyPercentege = (close - updatedEntryPrice) / updatedEntryPrice * 100.00
    rideUpStopLoss = hasOpenTrade() and strategyPercentege > 1

    if (isLong() and rideUpStopLoss)
        stopLossPercent := stopLossPercent + strategyPercentege - 1.0
        newStopLossPrice = updatedEntryPrice + (updatedEntryPrice * stopLossPercent) / 100  
        stopLossPrice := max(stopLossPrice, newStopLossPrice)
        updatedEntryPrice := stopLossPrice

//
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ //
//
// === LOGIC TO TRAILING STOP IN SHORT POSITION

if (isShort() and backTestPeriod())

    crossedStopLoss = close >= stopLossPrice
    terminateOperation = hasOpenTrade() and (crossedStopLoss or hasCloseShortConditional())

    if (terminateOperation)
        entryPrice := 0.0
        updatedEntryPrice := entryPrice
        stopLossPrice := 0.0
        strategyClose()
    
    startOperation = notHasOpenTrade() and hasEntryShortConditional()

    if(startOperation)
        entryPrice := close
        updatedEntryPrice := entryPrice
        stopLossPrice := entryPrice + (entryPrice * stopLossPercent) / 100
        strategyOpen()
        
    strategyPercentege = (close - updatedEntryPrice) / updatedEntryPrice * 100.00
    rideDownStopLoss = hasOpenTrade() and strategyPercentege < -1

    if (rideDownStopLoss)
        stopLossPercent := stopLossPercent + strategyPercentege + 1.0
        newStopLossPrice = updatedEntryPrice + (updatedEntryPrice * stopLossPercent) / 100  
        stopLossPrice := min(stopLossPrice, newStopLossPrice)
        updatedEntryPrice := stopLossPrice

//
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ 
//
// === DRAWING SHAPES     

entryPricePlotConditinal = entryPrice == 0.0 ? na : entryPrice
trailingStopLossPlotConditional = stopLossPrice == 0.0  ? na : stopLossPrice

plotshape(entryPricePlotConditinal, title= "Entry Price", color=color.blue, style=shape.circle, location=location.absolute, size=size.tiny)
plotshape(trailingStopLossPlotConditional, title= "Stop Loss", color=color.red, style=shape.circle, location=location.absolute, size=size.tiny)

plot(valueToPlot == 0.0 ? na : valueToPlot, title="BuyLine", linewidth=2, color=colorToPlot)
plotshape(direction == 1 and direction[1] == -1 ? longStop : na, title="Buy", style=shape.labelup, location=location.absolute, size=size.normal, text="Buy", transp=0, textcolor = color.white, color=color.green, transp=0)
plotshape(direction == -1 and direction[1] == 1 ? shortStop : na, title="Sell", style=shape.labeldown, location=location.absolute, size=size.normal, text="Sell", transp=0, textcolor = color.white, color=color.red, transp=0)

alertcondition(direction == 1 and direction[1] == -1 ? longStop : na, title="Buy", message="Buy!")
alertcondition(direction == -1 and direction[1] == 1 ? shortStop : na, title="Sell", message="Sell!")

더 많은