로프트 스톱 전략

저자:차오장, 날짜: 2023-10-07 16:11:45
태그:

전반적인 설명

이 전략은 가격을 추적하기 위해 칼만 필터를 사용하며 슬라이딩 스톱 손실을 달성하기 위해 스톱 손실 라인과 동적으로 스톱 손실 지점을 조정합니다.

원칙

이 전략은 칼만 필터를 사용하여 가격을 실시간으로 추적합니다. 칼만 필터는 두 개의 방정식을 포함합니다.

예측 방정식:

부드러운 = kf[1] + dk * sqrt(gain / 10000 * 2)

업데이트 방정식

kf = 부드럽고 가속

여기서 dk는 예측 오류이고, 이득은 추적 감도를 결정하는 Kalman 이득이다.

또한, 전략은 수익을 잠금하기 위해 슬라이딩 스톱 로스 라인을 사용합니다. 초기 스톱 로스 거리는 2%와 같은 스톱 로스 비율 설정입니다.

긴 경우, 가격이 상승하면, 스톱 로스 라인은 또한 0.5%와 같은 다운 스텝의 단계 크기로 칼만 라인에 접근하여 점차 상승합니다. 가격이 스톱 로스에 떨어지면 포지션을 다시 열고 초기 스톱 로스 거리를 설정합니다.

짧은 것은 비슷합니다.

따라서 전략은 좋은 위험 관리와 함께 트렌드에 따라 점차 수익을 확보할 수 있습니다.

장점

  1. 칼만 필터를 사용하여 빠른 응답으로 실시간으로 가격을 추적합니다.

  2. 슬라이딩 스톱 로스 라인으로 수익을 차단하여 좋은 리스크 관리를 달성합니다.

  3. 유연하게 길고 짧거나 길고 짧게 선택하세요.

  4. 트렌드를 기반으로 적극적으로 또는 보수적으로 손실을 중지합니다.

  5. 필요에 따라 유연하게 수익을 취하고 손실을 중지하십시오.

위험성

  1. Kalman 필터의 잘못된 매개 변수 설정은 불안정한 추적으로 이어질 수 있습니다.

  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")






더 많은