트래일링 스톱 손실 이중 이동 평균 전략

저자:차오장, 날짜: 2023-12-29 16:59:17
태그:

img

전반적인 설명

이 전략은 긴 포지션을 결정하기 위해 빠르고 느린 이동 평균 크로스오버를 사용합니다. 빠른 MA가 느린 MA를 넘어서고 빠른 MA가 느린 MA를 넘어서면 포지션을 닫습니다. 더 높은 수익을 추구하기 위해 전략은 후속 스톱 손실 메커니즘을 채택합니다. 긴 포지션을 열었을 때 엔트리 가격 바로 아래에 스톱 손실 가격을 설정하는 대신, 가격 하락이 스톱 손실 가격 한도를 달성할 때까지 가격 상승에 따라 상승하는 후속 스톱 손실 가격을 설정합니다.

어떻게 작동하는지

이 전략은 엔트리와 출구를 결정하기 위해 빠르고 느린 단순 이동 평균 (SMA) 라인을 사용합니다. 빠른 SMA가 느린 SMA를 넘을 때, 전략이 길게 갈 수 있도록 상승 추세를 신호합니다. 빠른 SMA가 느린 SMA 아래로 넘을 때, 트렌드 반전을 신호하여 전략이 포지션을 닫을 준비를합니다.

이 전략은 수익을 극대화하기 위해 트레일링 스톱 로스 메커니즘을 도입합니다. 긴 포지션을 열고 고정된 스톱 로스 가격을 사용하는 대신 가격 상승에 따라 상승하는 트레일링 스톱 로스 가격을 설정합니다. 가격이 특정 비율로 상승할 때마다 트레일링 스톱 로스 가격은 미리 정의된 비율로 조정됩니다. 가격이 뒤로 당기고 트레일링 스톱 로스 가격을 타면 포지션을 닫는 스톱 로스 주문을 유발합니다.

특히, 트레일링 스톱 로스 가격은 다음과 같이 계산됩니다.

소액액을 적립하는 경우, 소액액을 적립하는 경우

스톱 로스 트레일링 퍼센트는 전략 매개 변수 디비어션 %에 의해 정의됩니다. 전략은 매 바가 닫히는 순간 트레일링 스톱 로스 가격을 재 계산합니다. 새로운 트레일링 스톱 로스 가격은 이전 바보다 낮을 수 없습니다.

가격이 하락하고 마켓 오더가격에 도달하면 종료 신호가 발사되고 포지션은 마켓 오더로 종료됩니다.

장점

  • 좋은 백테스트 결과를 가진 트렌드 방향을 결정하기 위해 이중 이동 평균을 사용
  • 더 높은 수익을 추구하기 위해 후속 스톱 손실을 채택
  • 조정 가능한 이동평균 기간 및 스톱 로스 후속 비율
  • 트렌드가 올라갈 때 스톱 로스 라인은 계속 올라가고 대부분의 수익을 차단합니다.
  • 추세가 뒤집어지면 더 많은 손실을 피하기 위해 손해를 빠르게 중지합니다.

위험 과 해결책

  • 부적절한 이동 평균 교차 시기는 잘못된 신호를 일으킬 수 있습니다. 최적의 MA 조합을 찾기 위해 다른 매개 변수를 테스트하십시오.
  • 너무 공격적인 트레일링 스톱 손실은 조기에 중지 될 수 있습니다. 제대로 중지 손실 트레일링 비율 매개 변수를 조정
  • 가격 격차는 직접 스톱 로스 가격으로 침투 할 수 있습니다. 추세를 판단하고 범위 기간 동안 거래를 피하기 위해 다른 지표를 결합하는 것을 고려하십시오.

최적화 방향

  • 최적의 조합을 찾기 위해 다른 이동 평균 기간 매개 변수를 테스트
  • 최적 스톱 손실 수준을 찾기 위해 다른 스톱 손실 후속 비율 매개 변수를 테스트하십시오.
  • 다른 지표를 추가하여 간헐적인 사건의 영향을 피하기 위해 범위 기간 동안 거래를 중단하십시오.

결론

이 전략은 트렌드 방향을 판단하기 위해 움직이는 평균 지표와 트레일링 스톱 로스 메커니즘을 결합하여 수익을 잠금하고 훈련 데이터에 잘 수행합니다. 매개 변수를 최적화하고 위험을 제어함으로써 안정적인 수익을 얻을 수 있습니다. 그러나 어떤 전략도 손실을 완전히 피할 수 없습니다. 포지션 크기를 조정하고 다른 제품을 테스트하고 위험을 다양화하는 것이 좋습니다.


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

//@version=5
//
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ 
//  -----------------------------------------------------------------------------
//  Copyright 2022 Iason Nikolas | jason5480
//  Trailing Buy 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.1
//  Date:     24-Feb-2022
//
//  Description
//  =============================================================================
//  This strategy will go long if fast MA crosses over slow MA.
//  If the 'Enable Trailing` is checked then the strategy instead of exiting from the position
//  directly it will follow the price upwards (percentagewise) with small steps
//  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
//  Deviation % - The step to follow the price when the open position condition is met.
//  Source Exit Control - The source price to compare with the exit price to trigger the exit order when trailing.
//  
//  -----------------------------------------------------------------------------
//  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 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 Sell',
         shorttitle = 'TS',
         overlay = true,
         pyramiding = 0,
         default_qty_type = strategy.percent_of_equity,
         default_qty_value = 100,
         initial_capital = 100000)

//
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒
// FILTERS ==========================================================================================================

// INPUT ============================================================================================================
usefromDate = input.bool(defval = true, title = 'From', inline = "From Date", group = "Filters")
fromDate = input(defval = timestamp('01 Jan 2021 00:00 UTC'), title = '', inline = "From Date", group = 'Filters')
usetoDate = input.bool(defval = false, title = 'To ', inline = "To Date", group = "Filters")
toDate = input(defval = timestamp('31 Dec 2121 23:59 UTC'), title = '', inline = "To Date", group = 'Filters')

// LOGIC ============================================================================================================
isWithinPeriod() => true // create function "within window of time"

// PLOT =============================================================================================================
bgcolor(color = isWithinPeriod() ? color.new(color.gray, 90) : na, title = 'Period')

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

// INPUT ============================================================================================================
fastMALen = input.int(defval = 21, title = 'Fast/Slow SMA Length', inline = 'MA Length', group = 'Strategy')
slowMALen = input.int(defval = 49, title = '', tooltip = 'How many candles back to calculte the fast/slow SMA.', inline = 'MA Length', group = 'Strategy')

// LOGIC ============================================================================================================
fastMA = ta.sma(close, fastMALen)
slowMA = ta.sma(close, slowMALen)

bool openLongPosition = isWithinPeriod() and ta.crossover(fastMA, slowMA)
bool closeLongPosition = ta.crossunder(fastMA, slowMA)

// PLOT =============================================================================================================
var fastColor = color.new(#0056BD, 0)
plot(series = fastMA, title = 'Fast SMA', color = fastColor, linewidth = 1, style = plot.style_line)
var slowColor = color.new(#FF6A00, 0)
plot(series = slowMA, title = 'Slow SMA', color = slowColor, linewidth = 1, style = plot.style_line)

plotshape(series = closeLongPosition and strategy.position_size > 0 ? fastMA : na, title = 'Sell', text = 'Sell', style = shape.labeldown, location = location.absolute, color = color.new(color.red, 0), textcolor = color.new(color.white, 0), size = size.tiny)

//
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒
// EXIT ============================================================================================================

// INPUT ============================================================================================================
enableTrailing = input.bool(defval = true, title = 'Enable Trailing', tooltip = 'Enable or disable the trailing for exit position.', group = 'Exit')
devExitPerc = input.float(defval = 3.0, title = 'Deviation %', minval = 0.01, maxval = 100, step = 0.05, tooltip = 'The step to follow the price when the open position condition is met.', group = 'Exit') / 100
ctrLongExitSrc = input.source(defval = low, title = 'Source Exit Control', tooltip = 'The source price to compare with the exit price to trigger the exit order when trailing.', group = 'Exit')

// LOGIC ============================================================================================================
var bool exitLongPosition = false

int barsSinceOpenLong = nz(ta.barssince(openLongPosition), 999999)
int barsSinceCloseLong = nz(ta.barssince(closeLongPosition), 999999)
int barsSinceExitLong = nz(ta.barssince(exitLongPosition), 999999)
bool closeLongIsActive = barsSinceOpenLong >= barsSinceCloseLong
bool exitLongIsPending = barsSinceExitLong >= barsSinceCloseLong
bool tryExitLongPosition = isWithinPeriod() and closeLongIsActive and exitLongIsPending

float longExitPrice = na
longExitPrice := if closeLongPosition and strategy.position_size > 0
    close * (1 - devExitPerc)
else if tryExitLongPosition
    math.max(high * (1 - devExitPerc), nz(longExitPrice[1], 999999))
else
    na

exitLongPosition := enableTrailing ? isWithinPeriod() and ta.crossunder(closeLongPosition ? close : ctrLongExitSrc, longExitPrice) : closeLongPosition

// PLOT =============================================================================================================
var sellPriceColor = color.new(#e25141, 0)
plot(series = enableTrailing ? longExitPrice : na, title = 'Long Sell Price', color = sellPriceColor, linewidth = 1, style = plot.style_linebr)

//
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒
// POSITION ORDERS ==================================================================================================

// LOGIC ============================================================================================================
// getting into LONG position
strategy.entry(id = 'Long Entry', direction = strategy.long, when = openLongPosition, alert_message = 'Long(' + syminfo.ticker + '): Started')
// submit close order on trend reversal
strategy.close(id = 'Long Entry', when = exitLongPosition, comment = 'Close Long', alert_message = 'Long(' + syminfo.ticker + '): Closed at market price')

// PLOT =============================================================================================================
var posColor = color.new(color.white, 0)
plot(series = strategy.position_avg_price, title = 'Position', color = posColor, linewidth = 1, style = plot.style_linebr)

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

더 많은