동적 트레일링 스톱로스 전략


생성 날짜: 2023-12-29 10:42:27 마지막으로 수정됨: 2023-12-29 10:42:27
복사: 0 클릭수: 872
avatar of ChaoZhang ChaoZhang
1
집중하다
1617
수행원

동적 트레일링 스톱로스 전략

개요

동적 추적 스톱 로드 전략은 추적 스톱 로드 메커니즘을 이용한 양적 거래 전략이다. 이 전략은 트렌드 추적 이론에 기초하여, 추적 스톱 로드 라인을 설정하고, 스톱 로드 확인과 추적 스톱 로드 조정을 구현한다. 주로 단일 거래의 스톱 로드를 제어하고, 수익을 최대화하고, 거래 위험을 줄이는 데 사용됩니다.

전략 원칙

다이내믹 트래킹 스톱 로드 전략의 핵심은 3개의 핵심 파라미터를 설정하는 것이다: 초기 스톱 로드 거리, 트래킹 스톱 로드 거리, 그리고 트래킹 스톱 로드 트리거 거리. 구매 신호가 트리거되면, 구매 가격과 설정된 초기 스톱 로드 거리에 따라 초기 스톱 로드 가격이 계산된다. 이후 각 K 라인은 트래킹 스톱 로드 트리거 조건이 충족되었는지 판단하고, 충족되면 새로운 트래킹 스톱 로드 가격을 설정한다. 새로운 트래킹 스톱 로드 가격은 현재 종료 가격과 트래킹 스톱 로드 거리 계산에 기초한다.

이 전략은 동시에 낮은 스톱을 설정하고, 추적 스톱이 시작되었는지 여부에 관계없이, 가격이 낮은 스톱을 넘어간다면 직접 중단됩니다. 낮은 스톱은 갑작스러운 사건의 가격 점프를 방지하기 위해 사용됩니다. 따라서, 동적 추적 스톱 전략은 상하 쌍선 형태의 동적 스톱 메커니즘을 통해 스톱 라인을 자동으로 유리한 움직임을 추적 할 수있게하며, 과도한 손실을 방지합니다.

전략적 이점

  1. 스톱 손실을 추적하여 수익을 계속 고정하여 너무 많은 보상을 피하십시오.

  2. 상하의 쌍선 상쇄 구조를 사용하여 상쇄 라인이 적시에 따라갈 수 있도록 보장하고 과도한 손실을 방지합니다.

  3. 지속적인 판단 메커니즘을 사용하여 손해 조정, 작동은 간단하고 쉽게 구현한다.

  4. 시장 및 개별 주식의 특성에 따라 변수를 조정하여 손실을 막는 효과를 최적화 할 수 있습니다.

  5. 시장의 흐름을 예측할 필요 없이 트렌드를 따라가야 합니다.

전략적 위험

  1. 매개 변수 설정이 잘못되면 너무 느슨하거나 너무 긴박한 중지 손실이 발생할 수 있습니다. 너무 느슨하면 효율적인 중지 손실이 발생하지 않으며 너무 긴박하면 가격의 일반적인 변동에 의해 타격 될 수 있습니다.

  2. 갑작스러운 사건으로 인해 가격이 급등할 경우, 중단 손실이 무효로 이어질 수 있으며, 다른 보호 조치와 함께 수행되어야 합니다.

  3. 거래 수수료와 슬라이드 포인트는 스톱 라인이 촉발된 후의 실제 판매 가격에 영향을 미칠 수 있다.

  4. 적응력이 좋지 않고, 특정 단계에서, 예를 들어, 강진 기간 동안 효과가 좋지 않습니다.

대책:

  1. 재검토 및 실판 결과에 따라 계속 최적화하는 것이 좋습니다.
  2. 더 넓은 낮은 지점을 설정할 수 있다.
  3. 거래비와 슬라이드 포인트 영향을 고려하여 스톱로스 가격을 계산하십시오.
  4. 트렌드와 변동 판단 지표가 함께 사용될 수 있다.

전략 최적화 방향

  1. 스톱 라인 추적을 백분율 변화 방식으로 조정하여, 다른 가격 수준에서 주식 가격 변화를 더 잘 추적할 수 있다.

  2. 변동률 지표를 추가하여 큰 변동이 있을 때 중지하고, 일반적인 변동이 중단되는 것을 피하십시오.

  3. 기계 학습 방법을 사용하여 자동으로 최적화 파라미터. 훈련 샘플은 최근 기간 동안의 파라미터 조합의 수익률을 선택한다.

  4. 포지션 개시 조건 판단을 늘리고, 트렌드, 지원 저항과 같은 지표와 결합하여, 충격적인 상황에서 포지션을 개시하는 것을 피하십시오.

요약하다

동적 추적 중지 전략은 쌍선 중지 메커니즘을 통해 추적 중지 라인을 설정하여 중지 확인 및 추적 중지 조정할 수 있습니다. 가격 변화에 따라 자동으로 중지 거리를 조정하여 수익을 잠금하고 회수 및 제어 손실을 줄일 수 있습니다. 이 전략은 작동이 간단하고 구현하기 쉽고, 시장 상황에 따라 최적화 된 파라미터를 구현할 수 있으며 다른 전략 조합과 함께 사용하는 효과는 더 좋습니다.

전략 소스 코드
/*backtest
start: 2023-11-28 00:00:00
end: 2023-12-17 00:00:00
period: 1h
basePeriod: 15m
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}]
*/

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Thumpyr
//@version=5

/////////////////////////////////////////////////////////////////////////////////////////////
// Comment out Strategy Line and remove // from Indicator line to turn into Indicator  //////
// Do same for alertConidction at bottom                                               //////
/////////////////////////////////////////////////////////////////////////////////////////////
strategy("PCT Trailing Stoploss-Strategy", shorttitle="PCT Trailing Stoploss- Strategy", overlay=true)
//indicator(title="PCT Trailing Stoploss- Indicator", shorttitle="PCT Trailing Stoploss - Indicator", timeframe="", timeframe_gaps=true, overlay=true)//

sellLow=input.float(.035, minval=0, title="Stop Loss Loss: 1% = .01", group="Sell Settings")
trailStopArm=input.float(.0065, minval=0, title="Trailing Stop Arm: 1%=.01", group="Sell Settings")
trailStopPct=input.float(.003, minval=0, title="Trailing Stop Trigger: 1%=.01 ", group="Sell Settings")

/////////////////////////////////////////////////
//               Indicators                    //
/////////////////////////////////////////////////
ema1Len = input.int(14, minval=1, title=" ema 1 Length", group="Trend Line Settings")
ema1Src = input(close, title="ema 1 Source", group="Trend Line Settings")
ema1 = ta.ema(ema1Src, ema1Len)
plot(ema1, title="EMA", color=color.blue)

ema2Len = input.int(22, minval=1, title=" ema 2 Length", group="Trend Line Settings")
ema2Src = input(close, title="ema 2 Source", group="Trend Line Settings")
ema2 = ta.ema(ema2Src, ema2Len)
plot(ema2, title="EMA", color=color.orange)

ema3Len = input.int(200, minval=1, title=" ema 3 Length", group="Trend Line Settings")
ema3Src = input(close, title="ema 2 Source", group="Trend Line Settings")
ema3 = ta.ema(ema3Src, ema3Len)
plot(ema3, title="EMA", color=color.gray)


/////////////////////////////
////   Buy Conditions    ////
/////////////////////////////

alertBuy = ta.crossover(ema1,ema2) and close>ema3

////////////////////////////////////////////////////////////////////
////   Filter redundant Buy Signals if Sell has not happened    ////
////////////////////////////////////////////////////////////////////
var lastsignal = 0
showAlertBuy = 0
if(alertBuy and lastsignal !=1)
    showAlertBuy  := 1
    lastsignal      := 1
buyAlert= showAlertBuy > 0


//////////////////////////////////////////////////////////////////
////          Track Conditions at buy Signal                  ////
//////////////////////////////////////////////////////////////////

alertBuyValue = ta.valuewhen(buyAlert, close,0)
alertSellValueLow = alertBuyValue - (alertBuyValue*sellLow)

////////////////////////////////////////////////////////////
/////            Trailing Stop                         /////
////////////////////////////////////////////////////////////
var TSLActive=0         //Check to see if TSL has been activated
var TSLTriggerValue=0.0 //Initial and climbing value of TSL
var TSLStop = 0.0       //Sell Trigger
var TSLRunning =0       //Continuously check each bar to raise TSL or not

//  Check if a Buy has been triggered and set initial value for TSL //
if buyAlert
    TSLTriggerValue := alertBuyValue+(alertBuyValue*trailStopArm)
    TSLActive := 0
    TSLRunning :=1
    TSLStop := TSLTriggerValue - (TSLTriggerValue*trailStopPct)
    

//  Check that Buy has triggered and if Close has reached initial TSL//  
//  Keeps from setting Sell Signal before TSL has been armed w/TSLActive//
beginTrail=TSLRunning==1 and TSLActive==0 and close>alertBuyValue+(alertBuyValue*trailStopArm) and ta.crossover(close,TSLTriggerValue)
if beginTrail
    TSLTriggerValue :=close
    TSLActive :=1
    TSLStop :=TSLTriggerValue - (TSLTriggerValue*trailStopPct)
    
//  Continuously check if TSL needs to increase and set new value //    
runTrail= TSLActive==1 and (ta.crossover(close,TSLTriggerValue) or close>=TSLTriggerValue)
if runTrail
    TSLTriggerValue :=close
    TSLStop :=TSLTriggerValue - (TSLTriggerValue*trailStopPct)
    
//  Verify that TSL is active and trigger when close cross below TSL Stop//
TSL=TSLActive==1 and (ta.crossunder(close,TSLStop) or (close[1]>TSLStop and close<TSLStop)) 

// Plot point of inital arming of TSL//
TSLTrigger=TSLActive==1 and TSLActive[1]==0
plotshape(TSLTrigger, title='TSL Armed', location=location.abovebar, color=color.new(color.blue, 0), size=size.small, style=shape.cross, text='TSL Armed')


////////////////////////////////////////////////////////////
// Plots used for troubleshooting and verification of TSL //
////////////////////////////////////////////////////////////
//plot(TSLActive,"Trailing Stop", color=#f48fb1)
//plot(TSLRunning,"Trailing Stop", color=#f48fb1)
//plot(TSLTriggerValue,"Trailing Stop Trigger", color.new(color=#ec407a, transp = TSLRunning==1 ? 0 : 100))
//plot(TSLStop,"Trailing Stop", color.new(color=#f48fb1, transp = TSLRunning==1 ? 0 : 100))//


////////////////////////////////////////////////////////////
/////             Sell Conditions                    ///////
////////////////////////////////////////////////////////////
Sell1 = TSL
Sell2 = ta.crossunder(close,alertSellValueLow)

alertSell= Sell1 or Sell2
////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////
////        Remove Redundant Signals                    ////
////////////////////////////////////////////////////////////
showAlertSell = 0
if(alertSell and lastsignal != -1)
    showAlertSell := 1
    lastsignal      := -1
sellAlert= showAlertSell > 0

if sellAlert
    TSLActive :=0
    TSLRunning :=0

/////////////////////////////////////////
//  Plot Buy and Sell Shapes on Chart  //
/////////////////////////////////////////
plotshape(buyAlert, title='Buy', location=location.belowbar, color=color.new(color.green, 0), size=size.small, style=shape.triangleup, text='Buy')
plotshape(sellAlert, title='Sell', location=location.abovebar, color=color.new(color.red, 0), size=size.small, style=shape.triangledown, text='Sell')

/////////////////////////////////////////////////////////////////////////////////////////////
//                        Remove // to setup for Indicator                                 //
/////////////////////////////////////////////////////////////////////////////////////////////
//Alerts
//alertcondition(title='Buy Alert', condition=buyAlert, message='Buy Conditions are Met')
//alertcondition(title='Sell Alert', condition=sellAlert, message='Sell Conditions are Met')
/////////////////////////////////////////////////////////////////////////////////////////////


////////////////////////////////////////////////////////////
////  Comment out this section if setup as Indicator    ////
////////////////////////////////////////////////////////////
longCondition = buyAlert
if (longCondition)
    strategy.entry("Buy", strategy.long)
    alert(message='Buy', freq=alert.freq_once_per_bar_close)
    
shortCondition = sellAlert
if (shortCondition)
    strategy.close_all(sellAlert,"Sell")
    alert(message='Sell', freq=alert.freq_once_per_bar_close)
/////////////////////////////////////////////////////////////