슬라이딩 스톱 전략


생성 날짜: 2023-10-07 16:11:45 마지막으로 수정됨: 2023-10-07 16:11:45
복사: 0 클릭수: 445
1
집중하다
1230
수행원

개요

이 전략은 칼만 필터를 사용하여 가격을 추적하고 스톱 라인을 사용하여 스톱 포인트를 동적으로 조정하여 슬라이딩 스톱을 구현합니다.

원칙

이 전략은 칼만 필터를 사용하여 가격을 실시간으로 추적한다. 칼만 필터는 두 가지 방정식을 포함하고 있다:

예측 방정식:

smooth = kf[1] + dk * sqrt(gain / 10000 * 2)

이 방정식을 업데이트하세요.

kf = smooth + velo

그 중,dk는 예측 오류,gain은 칼만 이득, 결정 추적 민감도이다.

또한, 이 전략은 슬라이딩 스톱로스 라인을 사용하여 수익을 잠금합니다. 초기 스톱로스 거리는 스톱로스 비율로 설정됩니다. 예를 들어 2%입니다.

더 많이 할 때, 가격이 상승하면, 스톱 라인 또한 카르만 라인까지 점진적으로 올라갑니다. 단계의 길이는 downStep, 예를 들어 0.5%입니다. 가격이 떨어지면 스톱, 다시 포지션을 열고 초기 스톱 거리를 설정합니다.

이런 식으로 전략은 트렌드에 따라 수익을 점진적으로 고정시킬 수 있고, 더 나은 위험 관리를 할 수 있다.

장점

  1. 카르만 필터를 사용하여 실시간으로 가격을 추적하고 신속하게 반응하십시오.

  2. 슬라이딩 스톱 라인을 사용하여 수익을 고정하고, 위험 관리가 효과적입니다. 스톱 거리도 사용자 정의할 수 있습니다.

  3. 더 많은 공백을 하거나 단지 더 많은 공백을/공백을 하는 것에 대해 유연하게 선택할 수 있습니다.

  4. 동향에 따라 적극적으로 중지하거나 보수적으로 중지 할 수 있습니다.

  5. 필요에 따라 유연하게 설정할 수 있다.

위험

  1. 칼만 필터 파라미터를 잘못 설정하면 추적이 불안정해질 수 있다.

  2. 슬라이드 포인트는 스탠드 포인트가 먼저 트리플되는 것을 초래할 수 있다. 스탠드 거리도 적절히 완화할 수 있다.

  3. 강한 트렌드 시장은 슬라이드 스톱 전략을 채택하는 것이 바람직하지 않으며, 트렌드를 추적해야합니다.

  4. 흔들림 시장의 정지점은 자주 발동될 수 있다. 정지 거리를 적절히 완화하거나, 미끄러지는 정지를 사용하지 않는다.

최적화

  1. 트렌드 방향을 판단하는 더 많은 지표가 도입되어 포지션 개시 시기를 최적화 할 수 있습니다.

  2. 시장의 변동에 따라 스톱로드 라인의 이동 걸음 길이를 조정할 수 있다.

  3. 기계 학습 기술 훈련과 결합하여 최적의 손해 방지 파라미터를 얻을 수 있다.

  4. 더 많은 리스크 지표와 함께 포지션 관리를 동적으로 조정할 수 있다.

요약하다

슬라이딩 스톱 전략은 칼만 필터를 사용하여 가격 변화를 추적하고, 슬라이딩 스톱 라인을 사용하여 수익을 잠금하고, 수익을 보장하면서 위험을 제어하는 신뢰할 수 있고 쉽게 최적화 할 수있는 전략입니다. 트렌드 판단과 동적 포지션 관리 기술과 결합하면 더 나은 전략 효과를 얻을 수 있습니다.

전략 소스 코드
/*backtest
start: 2023-09-06 00:00:00
end: 2023-10-06 00:00:00
period: 2h
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/
// © BigCoinHunter

//@version=5
// strategy(title='Loft Strategy V1', overlay=true, 
//      pyramiding=0, default_qty_type=strategy.fixed, 
//      default_qty_value=100, initial_capital=100000, 
//      currency=currency.USD, commission_value=0.05, 
//      commission_type=strategy.commission.percent, 
//      process_orders_on_close=true)

//-------------- fetch user inputs ------------------
gain = input.float(title="Kalman Gain:", defval=1.0, minval=1.0, maxval=5000.0, step=100.0)
src = input(defval=close, title='Source:')

stopPercentMax = input.float(title='Beginning Approach(%):', defval=2.0, minval=0.1, maxval=30.0, step=0.1)
stopPercentMin = input.float(title='Final Approach(%):    ', defval=0.5, minval=0.1, maxval=30.0, step=0.1)
downStep = input.float(title='Approach Decrease Step:', defval=0.005, minval=0.0, maxval = 5, step=0.005)

tp = input.float(title="Take Profit:", defval=1.5, minval=0.0, maxval=100.0, step=0.1) * 0.01
sl = input.float(title="Stop Loss:  ", defval=0.0, minval=0.0, maxval=100.0, step=0.1) * 0.01

longEntry = input.bool(defval=true, title= 'Long Entry', inline="11")
shortEntry = input.bool(defval=true, title='Short Entry', inline="11")

//---------- backtest range setup ------------
fromDay   = input.int(defval = 1, title = "From Day", minval = 1, maxval = 31)
fromMonth = input.int(defval = 1, title = "From Month", minval = 1, maxval = 12)
fromYear  = input.int(defval = 2021, title = "From Year", minval = 2010)
toDay     = input.int(defval = 30, title = "To Day", minval = 1, maxval = 31)
toMonth   = input.int(defval = 12, title = "To Month", minval = 1, maxval = 12)
toYear    = input.int(defval = 2022, title = "To Year", minval = 2010)


//------------ time interval setup -----------
start     = timestamp(fromYear, fromMonth, fromDay, 00, 00)  // backtest start window
finish    = timestamp(toYear, toMonth, toDay, 23, 59)        // backtest finish window
window()  => true // create function "within window of time"

//------- define the global variables ------
enterLongComment = "ENTER LONG"
exitLongComment = "EXIT LONG"

enterShortComment = "ENTER SHORT"
exitShortComment = "EXIT SHORT"

longTPSL = "Long TP/SL"
longTP = "Long TP"
longSL = "Long SL"
shortTPSL = "Short TP/SL"
shortTP = "Short TP"
shortSL = "Short SL"

var bool long = true
var bool stoppedOutLong = false
var bool stoppedOutShort = false
var float kf = 0.0
var float velo = 0.0

//------ kalman filter calculation --------
dk = src - nz(kf[1], src)
smooth = nz(kf[1], src) + dk * math.sqrt(gain / 10000 * 2)
velo := nz(velo[1], 0) + gain / 10000 * dk
kf := smooth + velo

//--------- calculate the loft stopLoss line ---------
var stopPercent = stopPercentMax
var stopLoss = kf - kf * (stopPercent /100)

if long == true
    stopLoss := kf - (kf * (stopPercent / 100))
    
    if long[1] == true and stopLoss <= stopLoss[1]
        stopLoss := stopLoss[1]
    else if (long[1] == true)
        stopPercent := stopPercent - downStep
        if(stopPercent < stopPercentMin)
            stopPercent := stopPercentMin
    
    if(kf < stopLoss)
        long := false
        stopPercent := stopPercentMax
        stopLoss := kf + (kf * (stopPercent / 100))
        
else
    stopLoss := kf + (kf * (stopPercent / 100))
    
    if long[1] == false and stopLoss >= stopLoss[1]
        stopLoss := stopLoss[1]
    else if(long[1] == false)
        stopPercent := stopPercent - downStep
        if(stopPercent < stopPercentMin)
            stopPercent := stopPercentMin
            
    if(kf > stopLoss)
        long := true
        stopPercent := stopPercentMax
        stopLoss := kf - (kf * (stopPercent / 100))
        
//--------- calculate the input/output points -----------
longProfitPrice  = strategy.position_avg_price * (1 + tp)     // tp -> take profit percentage
longStopPrice = strategy.position_avg_price * (1 - sl)        // sl -> stop loss percentage

shortProfitPrice  = strategy.position_avg_price * (1 - tp)
shortStopPrice = strategy.position_avg_price * (1 + sl)

//------------------- determine buy and sell points ---------------------
buySignall = window() and long  and (not stoppedOutLong)
sellSignall = window() and (not long)  and (not stoppedOutShort)

//---------- execute the strategy -----------------
if(longEntry and shortEntry)
    if long 
        strategy.entry("LONG", strategy.long, when = buySignall, comment = enterLongComment)
        stoppedOutLong := true
        stoppedOutShort := false
    else 
        strategy.entry("SHORT", strategy.short, when = sellSignall, comment = enterShortComment)
        stoppedOutLong  := false
        stoppedOutShort := true

else if(longEntry)
    strategy.entry("LONG", strategy.long,  when = buySignall, comment = enterLongComment)
    strategy.close("LONG", when = sellSignall, comment = exitLongComment)
    if long 
        stoppedOutLong := true
    else
        stoppedOutLong  := false

else if(shortEntry)
    strategy.entry("SHORT", strategy.short, when = sellSignall, comment = enterShortComment)
    strategy.close("SHORT", when = buySignall, comment = exitShortComment)
    if not long
        stoppedOutShort := true
    else
        stoppedOutShort := false
    

//----------------- take profit and stop loss -----------------
if(tp>0.0 and sl>0.0)
    if ( strategy.position_size > 0 )
        strategy.exit(id="LONG", limit=longProfitPrice, stop=longStopPrice, comment = longTPSL)

    else if ( strategy.position_size < 0 )
        strategy.exit(id="SHORT", limit=shortProfitPrice, stop=shortStopPrice, comment = shortTPSL)

else if(tp>0.0)
    if ( strategy.position_size > 0 )
        strategy.exit(id="LONG", limit=longProfitPrice, comment = longTP)

    else if ( strategy.position_size < 0 )
        strategy.exit(id="SHORT", limit=shortProfitPrice, comment = shortTP)
        
else if(sl>0.0)
    if ( strategy.position_size > 0 )
        strategy.exit(id="LONG",  stop=longStopPrice, comment = longSL)

    else if ( strategy.position_size < 0 )
        strategy.exit(id="SHORT",  stop=shortStopPrice, comment = shortSL)
        
//------------- plot charts ---------------------
lineColor1 = long ? color.green : color.red
lineColor2 = long ? color.aqua : color.fuchsia

kalmanLine = plot(kf, color=lineColor1, linewidth=3, title = "Kalman Filter")
stopLine = plot(stopLoss, color=lineColor2, linewidth=2, title = "Stop Loss Line")