후속 스톱 손실 전략

저자:차오장, 날짜: 2024-01-12 10:47:38
태그:

img

전반적인 설명

이 전략은 트렌드를 결정하기 위해 빠르고 느린 이동 평균을 계산합니다. 빠른 이동 평균이 느린 이동 평균을 넘을 때 길게 이동하고 가격이 특정 비율로 변하면 이익을 잠금하기 위해 동적 인 후속 스톱 손실을 설정합니다.

전략 논리

이 전략은 급속하고 느린 이동 평균의 황금 십자가를 사용하여 상승 추세의 시작을 결정합니다. 구체적으로, 특정 기간 동안 폐쇄 가격의 간단한 이동 평균을 계산하고, 빠른 이동 평균과 느린 이동 평균의 값을 비교하고, 빠른 이동 평균이 느린 것을 넘어서면 상승 추세의 시작을 판단합니다.

롱 포지션을 열고 나면 전략은 고정된 스톱 로스를 설정하지 않고, 수익을 잠금하기 위해 동적 트레일링 스톱 로스를 사용합니다. 스톱 로스 라인은: 최고 가격 * (1 - 스톱 로스 비율) 에 따라 설정됩니다. 이것은 스톱 로스 라인이 가격이 상승함에 따라 상승 할 수 있도록합니다. 가격이 특정 비율로 떨어지면 스톱 로스는 포지션을 종료하기 위해 트리거됩니다.

이 접근법의 장점은 상승 추세를 무제한적으로 추격할 수 있게 하고, 스톱 로스를 통해 특정 수준에 도달하면 수익을 확보할 수 있다는 것입니다.

이점 분석

이 트래일링 스톱 로스 전략의 주요 장점은 다음과 같습니다.

  1. 큰 움직임을 놓치지 않고 트렌드를 무제한적으로 추격 할 수 있습니다. 고정 스톱 손실은 종종 주요 트렌드의 시작에서 중단됩니다.

  2. 스톱 러스 비율을 설정하여 수익을 잠금합니다. 스톱 러스 없이 트렌드를 추격하는 것만으로도 트렌드가 끝나면 손실이 발생할 수 있습니다. 스톱 러스는 이윤을 잠금합니다.

  3. 고정 스톱 손실보다 더 유연합니다. 고정 스톱 손실은 한 가격에만 설정 될 수 있으며, 이 스톱 손실은 가장 높은 가격으로 움직입니다.

  4. 이 방식은 유가 상승률을 높이고, 유가 하락률을 높이고, 유가 하락률을 높이고, 유가 하락률을 높일 수 있다.

위험 분석

이 전략은 또한 몇 가지 위험을 안고 있습니다.

  1. 입력 신호에 사용되는 표시기는 불안정하고 잘못된 신호를 생성할 수 있습니다.

  2. 다른 요인을 고려하지 않고 단 하나의 스톱 로스 접근법이 있습니다. 시장의 큰 변화는 전략을 무효화 할 수 있습니다.

  3. 수익 목표가 없습니다. 단지 스톱 로스에 의존합니다. 비효율적인 스톱 로스는 큰 손실로 이어질 수 있습니다.

  4. 이동평균 기간과 같은 매개 변수들은 더 많은 최적화를 필요로 합니다.

최적화 방향

이 전략은 몇 가지 분야에서 개선될 수 있습니다.

  1. 더 많은 지표를 추가하여 입력 사항을 확인하고 잘못된 신호, 예를 들어 부피를 피합니다.

  2. 이윤이 일정 비율에 도달하면 이윤을 추가합니다.

  3. 예외적인 시장 현상에서 동적으로 정지 거리를 조정함으로써 정지 손실 안전성을 향상시킵니다.

  4. 거래 도구 및 거래 세션과 같은 매개 변수를 최적화합니다. 다른 제품과 세션은 매개 변수를 조정해야합니다.

  5. 기계 학습을 추가하여 매개 변수를 동적으로 조정하고 지표를 최적화하고 자동으로 손실 수준을 중지합니다.

요약

이 전략의 전반적인 논리는 건전하고 합리적입니다. 트렌드를 결정하기 위해 빠르고 느린 이동 평균을 사용하는 것은 고전적인 접근법입니다. 트레이링 스톱 로스는 수익을 잠금하고 위험을 줄이는 데도 효과적입니다. 그러나 전략이 지속적으로 수익성있게 만들기 위해 지표와 매개 변수에 대한 지속적인 테스트와 최적화가 필요합니다. 동시에 전략을 무효화 할 수있는 주요 시장 변화는 전반적인 논리와 프레임워크를 개선하고 보호 장치를 추가하여 보호해야합니다.


/*backtest
start: 2023-12-01 00:00:00
end: 2023-12-31 23:59:59
period: 4h
basePeriod: 15m
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}]
*/

//@version=4
//
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ 
//  -----------------------------------------------------------------------------
//  Copyright 2021 Iason Nikolas | jason5480
//  Trainiling Take Profit 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:  @jason5480
//  Revision: v1.0.0
//  Date:     05-May-2021
//
//  Description
//  =============================================================================
//  This strategy will go long if fast MA crosses over slow MA.
//  The strategy will exit from long position when the price increases by a fixed percentage.
//  If the trailing take profit is checked then the strategy instead of setting a limit order in a predefined price (based on the percentage)
//  it will follow the price with small steps (percentagewise)
//  If the price drops by this percentage then the exit order will be executed
//
//  The strategy has the following parameters:
//
//  Fast SMA Length - How many candles back to calculte the fast SMA.
//  Slow SMA Length - How many candles back to calculte the slow SMA.
//  Enable Trailing - Enable or disable the trailing.
//  Stop Loss % - The percentage of the price decrease to set the stop loss price target for long positions.
//  
//  -----------------------------------------------------------------------------
//  Disclaimer:
//    1. I am not licensed financial advisors or broker dealer. I do not tell you 
//       when or what to buy or sell. I developed this software which enables you 
//       execute manual or automated 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.
//  -----------------------------------------------------------------------------
//
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒
// SETUP ============================================================================================================
strategy(title = "Trailing Stop Loss",
         shorttitle = "TSL",
         overlay = true,
         pyramiding = 0,
         calc_on_every_tick = true,
         default_qty_type = strategy.cash,
         default_qty_value = 100000,
         initial_capital = 100000)

//
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒
// INPUTS ===========================================================================================================

// STRATEGY INPUT ===================================================================================================
fastMALen = input(defval = 21, title = "Fast SMA Length", type = input.integer, group = "Strategy", tooltip = "How many candles back to calculte the fast SMA.")
slowMALen = input(defval = 49, title = "Slow SMA Length", type = input.integer, group = "Strategy", tooltip = "How many candles back to calculte the slow SMA.")

enableStopLossTrailing = input(defval = true, title = "Enable Trailing", type = input.bool, group = "Strategy", tooltip = "Enable or disable the trailing for stop loss.")
longTrailingStopLossPerc = input(defval = 7.5, title = 'Long Stop Loss %', type = input.float, minval = 0.1, maxval = 100, step = 0.1, inline = "Trailing Stop Loss Perc", group = "Strategy") / 100

// BACKTEST PERIOD INPUT ============================================================================================
fromDate = input(defval = timestamp("01 Jan 2021 00:00 UTC"), title = "From Date", type = input.time, minval = timestamp("01 Jan 1970 00:00 UTC"), group = "Backtest Period") // backtest start date
toDate   = input(defval = timestamp("31 Dec 2121 23:59 UTC"), title = "To Date",   type = input.time, minval = timestamp("01 Jan 1970 00:00 UTC"), group = "Backtest Period") // backtest finish date

isWithinBacktestPeriod() => true

// SHOW PLOT INPUT ==================================================================================================
showDate = input(defval = true, title = "Show Backtest Range", type = input.bool, group = "Plot", tooltip = "Gray out the backround of the backtest period.")

//
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒
// STRATEGY LOGIC ===================================================================================================

fastMA = sma(close, fastMALen)
slowMA = sma(close, slowMALen)

bool startLongDeal = crossover(fastMA, slowMA)

bool longIsActive = startLongDeal or strategy.position_size > 0

// determine trailing stop loss price
float longTrailingStopLossPrice = na
longTrailingStopLossPrice := if (longIsActive)
    stopValue = high * (1 - longTrailingStopLossPerc)
    max(stopValue, nz(longTrailingStopLossPrice[1]))
else
    na

//
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒
// STRATEGY EXECUTION ===============================================================================================

if (isWithinBacktestPeriod())
    // getting into LONG position
    strategy.entry(id = "Long Entry", long = strategy.long, when = startLongDeal, alert_message = "Long(" + syminfo.ticker + "): Started")
    // submit exit orders for trailing stop loss price
    strategy.exit(id = "Long Stop Loss", from_entry = "Long Entry", stop = longTrailingStopLossPrice, when = longIsActive, alert_message = "Long(" + syminfo.ticker + "): Stop Loss activated")


//
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒
// PLOT DATE POSITION MA AND TRAILING TAKE PROFIT STOP LOSS =========================================================

bgcolor(color = showDate and isWithinBacktestPeriod() ? color.gray : na, transp = 90)

plot(series = fastMA, title = "Fast SMA", color = #0056BD, linewidth = 2, style = plot.style_line)
plot(series = slowMA, title = "Slow SMA", color = #FF6A00, linewidth = 2, style = plot.style_line)
plotshape(series = isWithinBacktestPeriod() and startLongDeal and strategy.position_size <= 0 ? fastMA : na, title = "UpTrend Begins", style = shape.circle, location = location.absolute, color = color.green, transp = 0, size = size.tiny)
plotshape(series = isWithinBacktestPeriod() and startLongDeal and strategy.position_size <= 0 ? fastMA : na, title = "Buy", text = "Buy", style = shape.labelup, location = location.absolute, color = color.green, textcolor = color.black, transp = 0, size = size.tiny)

plot(series = strategy.position_avg_price, title = "Position", color = color.blue, linewidth = 2, style = plot.style_linebr, offset = 1)
plot(series = longTrailingStopLossPrice, title = "Long Trail Stop", color = color.fuchsia, linewidth = 2, style = plot.style_linebr, offset = 1)

// ==================================================================================================================

더 많은