지연된 RSI 거래 전략


생성 날짜: 2023-10-07 15:38:56 마지막으로 수정됨: 2023-10-07 15:38:56
복사: 0 클릭수: 701
avatar of ChaoZhang ChaoZhang
1
집중하다
1617
수행원

개요

지연 RSI 거래 전략은 일반적인 RSI 지표를 사용하여 과매매 상황을 식별하고, 진입 신호가 나타나면 가짜 돌파구가 불필요한 손실을 초래하지 않도록 일정 기간 후에 다시 진입합니다. 이 전략의 주요 아이디어는 RSI 지표를 사용하여 시장의 과매매 현상을 판단하고, 이 판단의 기초에 따라, 지연 진입을 통해 더 정확한 진입 시간을 파악합니다.

전략 원칙

이 전략은 21주기 길이의 RSI 지표를 사용하여 과매매 상황을 판단한다. RSI 지표 위에 사용자가 설정한 과매매 라인을 통과했을 때 ((설정60)), 과매매라고 간주하고, RSI 지표 아래에 사용자가 설정한 과매 라인을 통과했을 때 ((설정40)), 과매매라고 간주한다.

오버 바이 오버 세 신호가 나타난 후, 전략은 즉시 입장이 되지 않고, 지연 주기를 계산하기 시작한다. 지연 주기의 수 (설정된 15주기) 가 충족되면, 오버 바이 신호에 따라 공백을 하고, 오버 세 신호를 더한다.

이 전략은 사용자가 다양한 진입 시점을 달성하기 위해 지연 주기를 조정할 수 있도록 한다. 지연 주기가 길어지면 더 많은 가짜 돌파구를 피할 수 있지만 더 나은 진입 지점을 놓칠 수도 있다. 사용자는 특정 품종에 따라 지연 주기 변수를 조정할 필요가 있다.

또한, 이 전략은 스톱, 스톱스, 역거래 등의 옵션을 구현한다. 사용자는 고정 스톱스, 추적 스톱스, 고정 스톱스 등의 방법으로 포지션을 관리할 수 있다. 또한 역거래 논리를 선택할 수 있다. 즉, 오버 바이 신호에 따라 더 많이 하고, 오버 판매 신호에 따라 공백한다.

전략적 이점

  1. RSI 지표를 사용하여 과매매를 판단하여 반전 기회를 정확하게 잡을 수 있습니다. RSI는 반전 기회를 효과적으로 식별 할 수있는보다 성숙한 과매매 지표입니다.

  2. 미루어진 입장은 가짜 돌파구가 손실을 초래하는 것을 방지한다. 많은 돌파구가 반드시 실질적인 반전을 나타내지 않으며, 미루어진 입장은 돌파구의 유효성을 검증할 수 있다.

  3. 조정 가능한 지연 사이클 수, 정확한 입구 시간을 파악한다. 사용자는 다양한 품종의 특성에 따라 지연 사이클을 조정하여 최적의 입구 지점을 달성할 수 있다.

  4. 스톱로스, 스톱 매니지먼트, 통제 가능한 위험. 전략은 여러 가지 스톱로스 스톱 방법을 제공하며, 지연 진입과 함께 위험을 제어 할 수 있습니다.

  5. 다양한 품종 특성에 맞는 역거래 옵션을 제공합니다. 사용자는 불확실성을 헤지하기 위해 직선 또는 역거래 논리를 선택할 수 있습니다.

전략적 위험

  1. RSI 신호는 항상 유효하지 않으며, 일부 시장 상황에서도 잘못된 신호가 발생할 수 있습니다.

  2. 너무 많이 지연하면 출입 시점을 놓칠 수 있다. 너무 긴 지연 주기를 설정하면 출입 시점을 놓칠 수 있다.

  3. 역거래는 손실의 위험을 증가시킨다. 역거래는 불확실성을 보호할 수 있지만, 전체 손실을 확대할 수도 있다.

  4. 추적 스톱은 에 의해 위험한다. 가격의 급격한 변화가 있을 때 추적 스톱은 현재 가격에 너무 가깝게 되어 가격이 을 뚫을 수 있다.

  5. 정지 예측은 수익이 적을 수 없습니다. 고정 정지은 최대 수익을 달성 할 수 없으며, 합리적인 예측이 필요합니다.

위와 같은 위험들에 대한 최적화 제안은 다음과 같습니다.

  1. 다른 지표와 결합하여 RSI 신호를 필터링하여 신뢰성을 향상시킵니다. KDJ, MACD 등 지표.

  2. 다양한 품종의 역사 데이터 테스트에 따라 최적의 지연주기 파라미터를 는 것이 바람직하지 않다.

  3. 역거래 기능을 신중하게 사용하며, 트렌드 트레이딩과 같은 방법을 결합하는 것이 좋습니다.

  4. 스톱로스를 추적할 때 넓은 간격을 설정하여 현재 가격에 너무 가까이 가지 않도록하십시오.

  5. 다양한 정지배수를 테스트하여 최적의 변수를 찾는다. 동적 정지배도 고려할 수 있다.

최적화 방향

이 전략은 다음의 몇 가지 측면에서 더 개선될 수 있습니다.

  1. 여러 지표가 결합되어 진입 신호를 필터링한다. 예를 들어 KDJ, MACD 등의 지표가 RSI와 결합되어 더 신뢰할 수 있는 거래 신호를 형성할 수 있다.

  2. 동적으로 지연주기를 조정한다. 시장의 변동 정도에 따라 동적으로 지연주기를 변경할 수 있으며, 가짜 돌파구를 피하는 동시에 입금 정확도를 향상시킬 수 있다.

  3. 최적화 스톱 스톱 전략. 동적 스톱, 수익 회수 비율 스톱, 시간 스톱 등을 연구하여 스톱 스톱을 시장의 변동 특성에 더 적합하게 만들 수 있다.

  4. 트렌드 요소와 결합하여, 돌파 방향과 큰 트렌드 방향의 일치성을 판단할 수 있으며, 역전 거래를 피할 수 있다. 또한, 돌파 힘에 따라 지연 주기의 수를 조정할 수 있다.

  5. 기계 학습을 사용하여 최적의 파라미터 조합을 찾습니다. 많은 훈련과 피드백 데이터를 통해 기계 학습은 파라미터을 자동으로 조정하여 최적의 파라미터 조합을 얻을 수 있습니다.

종합적으로, 이 전략은 여전히 최적화 할 수있는 많은 공간이 있으며, 지표 조합, 동적 조정, 추세 판단과 같은 방법으로 전략을 더 안정적이고 신뢰할 수 있습니다. 기계 학습의 응용은 또한 향후 최적화 방향입니다.

요약하다

overall RSI 전략을 지연 RSI 지표를 사용하여 과매매 상황을 판단하고, 신호가 나타나면 특정 주기를 지연하여 재입장을 할 수 있으며, 가짜 브레이크로 인해 불필요한 손실을 방지 할 수 있습니다. 이 전략은 지표를 결정하는 정확도, 가짜 브레이크를 피하기 위해 진입을 지연하고, 지연 주기를 조정하고, 스톱 손실 관리를 구현하는 장점이 있습니다. 그러나 RSI 신호가 신뢰할 수 없으며, 너무 많은 놓친 기회를 지연하는 위험도 있습니다. 지표 조합을 통해 신호 정확성을 최적화하고, 지연 주기를 동적으로 조정하여 장점을 잡을 수 있으며, 스톱 손실 전략을 최적화 할 수 있습니다.

전략 소스 코드
/*backtest
start: 2023-01-01 00:00:00
end: 2023-10-06 00:00:00
period: 1d
basePeriod: 1h
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/
// © tweakerID and © BacktestRookies

// This strategy uses a 21 period RSI with an overbought (RSI indicator 
// is greater than) level of 60 (user defined) to determines long entries and an oversold 
// (RSI indicator is less than) level of 40 (user defined) for shorts. It introduces a bar delay that starts
// counting when the RSI < Oversold or RSI > Overbought conditions are true, delaying the entry with 
// the amount of bars determined by the user. The trading logic can be reversed, which seems to work better.

//@version=4
strategy("Delayed RSI Strategy", 
     overlay=false, 
     default_qty_type=strategy.percent_of_equity, 
     default_qty_value=100, 
     initial_capital=10000, 
     commission_value=0.04, 
     calc_on_every_tick=false, 
     slippage=0)
     
direction = input(0, title = "Strategy Direction", type=input.integer, minval=-1, maxval=1)
strategy.risk.allow_entry_in(direction == 0 ? strategy.direction.all : 
 (direction < 0 ? strategy.direction.short : strategy.direction.long))

// Bought and Sold Boolean Signal
bought = strategy.position_size > strategy.position_size[1] 
 or strategy.position_size < strategy.position_size[1]

/////////////////////// STRATEGY INPUTS ////////////////////////////////////////
title1=input(true, "-----------------Strategy Inputs-------------------")  

rsiLen=input(21, title="RSI Length")
i_OB = input(60, title="Overbought")
i_OS = input(40, title="Oversold")
i_delay = input(15, title="Entry Delay (# of Bars)")
i_Close= input(false, title="Use Strategy Close")

/////////////////////// BACKTESTER /////////////////////////////////////////////
title2=input(true, "-----------------General Inputs-------------------")  

// Backtester General Inputs
i_SL=input(true, title="Use Stop Loss and Take Profit")
TS=input(false, title="Use Trailing Stop")
i_SLType=input(defval="ATR Stop", title="Type Of Stop", options=["Strategy Stop", "Swing Lo/Hi", "ATR Stop"])
i_SPL=input(defval=10, title="Swing Point Lookback")
i_PercIncrement=input(defval=3, step=.1, title="Swing Point SL Perc Increment")*0.01
i_ATR = input(14, title="ATR Length")
i_ATRMult = input(3, step=.1, title="ATR Multiple")
i_TPRRR = input(2, step=.1, title="Take Profit Risk Reward Ratio")
DPR=input(false, "Allow Direct Position Reverse")
reverse=input(true, "Reverse Trades")

// Swing Points Stop and Take Profit
SwingStopProfit() =>
    LL=(lowest(i_SPL))*(1-i_PercIncrement)
    HH=(highest(i_SPL))*(1+i_PercIncrement)
    LL_price = valuewhen(bought, LL, 0)
    HH_price = valuewhen(bought, HH, 0)
    entry_LL_price = strategy.position_size > 0 ? LL_price : na 
    entry_HH_price = strategy.position_size < 0 ? HH_price : na 
    tp=strategy.position_avg_price + (strategy.position_avg_price - entry_LL_price)*i_TPRRR
    stp=strategy.position_avg_price - (entry_HH_price - strategy.position_avg_price)*i_TPRRR
    [entry_LL_price, entry_HH_price, tp, stp]

// ATR Stop
ATRStop() =>
    ATR=atr(i_ATR)*i_ATRMult
    ATRLong = ohlc4 - ATR
    ATRShort = ohlc4 + ATR
    ATRLongStop = valuewhen(bought, ATRLong, 0)
    ATRShortStop = valuewhen(bought, ATRShort, 0)
    LongSL_ATR_price = strategy.position_size > 0 ? ATRLongStop : na 
    ShortSL_ATR_price = strategy.position_size < 0 ? ATRShortStop : na 
    ATRtp=strategy.position_avg_price + (strategy.position_avg_price - LongSL_ATR_price)*i_TPRRR
    ATRstp=strategy.position_avg_price - (ShortSL_ATR_price - strategy.position_avg_price)*i_TPRRR
    [LongSL_ATR_price, ShortSL_ATR_price, ATRtp, ATRstp]
    
// Strategy Stop
StrategyStop(bought) =>
    float LongStop = na
    float ShortStop = na
    float StratTP = na
    float StratSTP = na
    [LongStop, ShortStop, StratTP, StratSTP]

//TrailingStop
TrailingStop(SL,SSL) =>
    dif=(valuewhen(strategy.position_size>0 and strategy.position_size[1]<=0, high,0))
     -strategy.position_avg_price
    trailOffset     = strategy.position_avg_price - SL
    var tstop = float(na)
    if strategy.position_size > 0
        tstop := high- trailOffset - dif
        if tstop<tstop[1]
            tstop:=tstop[1]
    else
        tstop := na
    StrailOffset     = SSL - strategy.position_avg_price
    var Ststop = float(na)
    Sdif=strategy.position_avg_price-(valuewhen(strategy.position_size<0 
     and strategy.position_size[1]>=0, low,0))
    if strategy.position_size < 0
        Ststop := low+ StrailOffset + Sdif
        if Ststop>Ststop[1]
            Ststop:=Ststop[1]
    else
        Ststop := na
    [tstop, Ststop]
  
//Stop Loss & Take Profit Switches  
SLTPLogic(LongStop, ShortStop, StratTP, StratSTP, LongSL_ATR_price, ShortSL_ATR_price, ATRtp, ATRstp,
 entry_LL_price, entry_HH_price, tp, stp) =>
    SL= i_SLType == "Swing Lo/Hi" ? entry_LL_price : i_SLType == "ATR Stop" ? LongSL_ATR_price : LongStop
    SSL= i_SLType == "Swing Lo/Hi" ? entry_HH_price : i_SLType == "ATR Stop" ? ShortSL_ATR_price : ShortStop
    TP= i_SLType == "Swing Lo/Hi" ? tp : i_SLType == "ATR Stop" ? ATRtp : StratTP
    STP= i_SLType == "Swing Lo/Hi" ? stp : i_SLType == "ATR Stop" ? ATRstp : StratSTP
    [SL, SSL, TP, STP]


/////////////////////// STRATEGY LOGIC /////////////////////////////////////////

rsi = rsi(close, rsiLen)
isOB= rsi > i_OB
isOS= rsi < i_OS
BarsSinceOB = barssince(not isOB)
BarsSinceOS = barssince(not isOS)

BUY = BarsSinceOS == i_delay
SELL = BarsSinceOB == i_delay

/////////////////////// FUNCTION CALLS /////////////////////////////////////////

// Stops and Profits
[entry_LL_price, entry_HH_price, tp, stp] = SwingStopProfit()
[LongSL_ATR_price, ShortSL_ATR_price, ATRtp, ATRstp] = ATRStop()
[LongStop, ShortStop, StratTP, StratSTP] = StrategyStop(bought)
[SL, SSL, TP, STP] = SLTPLogic(LongStop, ShortStop, StratTP, StratSTP, 
 LongSL_ATR_price, ShortSL_ATR_price, ATRtp, ATRstp, entry_LL_price, entry_HH_price, tp, stp)
[tstop, Ststop] = TrailingStop(SL,SSL)

// Entries
if reverse
    if not DPR
        strategy.entry("long", strategy.long, when=SELL and strategy.position_size == 0)
        strategy.entry("short", strategy.short, when=BUY and strategy.position_size == 0)
    else     
        strategy.entry("long", strategy.long, when=SELL)
        strategy.entry("short", strategy.short, when=BUY)
else
    if not DPR 
        strategy.entry("long", strategy.long, when=BUY and strategy.position_size == 0)
        strategy.entry("short", strategy.short, when=SELL and strategy.position_size == 0)
    else
        strategy.entry("long", strategy.long, when=BUY)
        strategy.entry("short", strategy.short, when=SELL)
// Exits
if i_SL
    strategy.exit("TP & SL", "long", limit=TP, stop=TS? tstop : SL)
    strategy.exit("TP & SL", "short", limit=STP, stop=TS? Ststop : SSL)
    
if i_Close
    strategy.close_all(when=cross(rsi, 50))

/////////////////////// PLOTS //////////////////////////////////////////////////

//Plots
rsiplot = plot(rsi, "RSI", color=#7E57C2)
band1 = hline(i_OB, "Upper Band", color=#787B86)
bandm = hline(50, "Middle Band", color=color.new(#787B86, 50))
band0 = hline(i_OS, "Lower Band", color=#787B86)
fill(band1, band0, color=color.rgb(126, 87, 194, 90), title="Background")
plot(rsi, "RSI", color=#7E57C2)
// OSOBCount = plot(isOB ? BarsSinceOB : isOS ? BarsSinceOS : na, transp=100)
// OSOBColor = color.from_gradient(isOB ? BarsSinceOB : BarsSinceOS, 0, 20, color.black, isOB ? color.red : isOS ? color.green : na)
// OBP = plot(rsi > i_OB ? rsi : na, color=color.white, display=display.none)
// fill(plot(i_OB, display=display.none), OBP, color=OSOBColor, transp=0, fillgaps=false)
// OSP = plot(rsi < i_OS ? rsi : na, color=color.white, display=display.none)
// fill(plot(i_OS, display=display.none), OSP, color=OSOBColor, transp=0, fillgaps=false)

// plotshape(BUY ? 1 : na, style=shape.arrowdown, location=location.bottom, 
//  color=color.green, title="Bullish Setup", size=size.normal)
// plotshape(SELL ? 1 : na, style=shape.arrowup, location=location.top, 
//  color=color.red, title="Bearish Setup", size=size.normal)