RSI 인디케이터 긴 짧은 분리 거래 전략

저자:차오장, 날짜: 2024-02-26 13:49:25
태그:

img

전반적인 설명

이 전략은 거래 결정을 내리기 위해 RSI 지표를 통해 긴 짧은 분리 현상을 식별합니다. 핵심 아이디어는 가격이 새로운 최저치를 달성하지만 RSI 지표가 새로운 최고치를 달성할 때, 바닥이 형성되어 길어지고 있음을 나타내는 bullish 분리 신호가 생성된다는 것입니다. 가격이 새로운 최고치를 달성하지만 RSI 지표가 새로운 최저치를 달성할 때, 상위가 형성되어 짧아지고 있음을 나타내는 bearish 분리 신호가 생성됩니다.

전략 원칙

이 전략은 주로 RSI 지표를 사용하여 가격과 RSI 사이의 긴 짧은 분리를 식별합니다. 구체적인 방법은 다음과 같습니다.

  1. 소스 데이터로 13의 RSI 지표 매개 변수 및 폐쇄 가격을 사용
  2. 14일로 좌측 룩백 범위와 2일로 우측 룩백 범위를 정의합니다
  3. 하향 분리를 위한 왼쪽 룩백 범위는 47일, 오른쪽 룩백 범위는 1일로 정의합니다
  4. 가격이 낮은 최저치에 도달하지만 RSI가 높은 최저치를 달성하면 긴 신호를 생성하기 위해 긴 분리 조건이 충족됩니다.
  5. 가격이 높은 최고치를 기록하지만 RSI가 낮은 최고치를 기록하면 짧은 분리 조건이 충족되어 짧은 신호를 생성합니다.

가격과 RSI 사이의 긴 짧은 분리를 식별함으로써 무역 의사결정을 위해 가격 트렌드의 전환점을 사전에 파악 할 수 있습니다.

전략 의 장점

이 전략의 주요 장점은 다음과 같습니다.

  1. 가격/RSI 분리를 식별하면 트렌드 굴곡을 조기에 판단하여 거래 기회를 포착 할 수 있습니다.
  2. 지표 분석을 사용해서 감정에 덜 영향을 받습니다.
  3. 고정된 룩백 기간을 사용하여 분리를 식별하고 빈번한 매개 변수 조정을 피하십시오.
  4. 매일 RSI와 같은 추가 조건은 잘못된 신호를 감소시킵니다.

위험 과 해결책

여전히 몇 가지 위험이 있습니다.

  1. RSI의 분차는 즉각적인 반전을 의미하지는 않지만, 시간 지연이 발생할 수 있어 중단 손실 위험이 발생할 수 있습니다. 해결책은 분차 신호 확인을 위해 더 넓은 중지 시간을 허용하는 것입니다.

  2. 장기간의 분리 또한 위험을 증가시킵니다. 해결책은 필터 조건으로 더 장기적인 일일 또는 주간 RSI를 추가하는 것입니다.

  3. 작은 오차는 트렌드 반전을 확인하지 않을 수 있습니다. 더 중요한 RSI 오차를 찾기 위해 뷰백 기간을 확장해야합니다.

최적화 방향

이 전략은 다음과 같은 측면에서 개선될 수 있습니다.

  1. 가장 좋은 매개 변수 조합을 찾기 위해 RSI 매개 변수를 최적화

  2. 분리를 식별하기 위해 MACD, KD와 같은 다른 기술 지표를 시도하십시오.

  3. 흔들림 필터를 추가 하 고 불운 기간 동안 거짓 신호를 줄이십시오

  4. 가장 좋은 조합 신호를 찾기 위해 여러 시간 프레임에서 RSI를 결합

결론

RSI 긴 짧은 분리 거래 전략은 거래 신호를 생성하기 위해 가격과 RSI 사이의 분리를 식별하여 트렌드 굴곡을 판단합니다. 전략은 간단하고 실용적입니다. 매개 변수 및 필터를 추가하여 수익성을 높일 수 있습니다. 전반적으로 효과적인 양적 거래 전략입니다.


/*backtest
start: 2024-01-01 00:00:00
end: 2024-01-31 23:59:59
period: 3h
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/
// © Nextep

//@version=4
strategy(title="RSI top&bottom destroy ", overlay=false, pyramiding=4, default_qty_value=2, default_qty_type=strategy.fixed, initial_capital=10000, currency=currency.USD)







// INPUT Settings --------------------------------------------------------------------------------------------------------------------------------------------------
len = input(title="RSI Period", minval=1, defval=13)
src = input(title="RSI Source", defval=close)





// defining the lookback range for shorts
lbRshort = input(title="Short Lookback Right", defval=1)
lbLshort = input(title="Short Lookback Left", defval=47)

// defining the lookback range for longs
lbRlong = input(title="Long Lookback Right", defval=2)
lbLlong = input(title="Long Lookback Left", defval=14)


rangeUpper = input(title="Max of Lookback Range", defval=400)
rangeLower = input(title="Min of Lookback Range", defval=1)

// take profit levels
takeProfitLongRSILevel = input(title="Take Profit at RSI Level", minval=0, defval=75)
takeProfitShortRSILevel = input(title="Take Profit for Short at RSI Level", minval=0, defval=25)




// Stop loss settings
longStopLossType = input("PERC", title="Long Stop Loss Type", options=['ATR','PERC', 'FIB', 'NONE'])
shortStopLossType = input("PERC", title="Short Stop Loss Type", options=['ATR','PERC', 'FIB', 'NONE'])
longStopLossValue = input(title="Long Stop Loss Value", defval=14, minval=0)
shortStopLossValue = input(title="Short Stop Loss Value", defval=5, minval=-10)








// PLOTTING THE CHARTS --------------------------------------------------------------------------------------------------------------------------------------------------
// Plotting the Divergence
plotBull = input(title="Plot Bullish", defval=true)
plotBear = input(title="Plot Bearish", defval=true)
bearColor = color.orange
bullColor = color.green
textColor = color.white
noneColor = color.new(color.white, 100)

// Adding the RSI oscillator
osc = rsi(src, len)
ma_len = 14 // Length for the moving average
rsi_ma = sma(osc, ma_len) // Calculate the moving average of RSI
plot(osc, title="RSI", linewidth=1, color=color.purple)
plot(rsi_ma, color=color.blue, title="RSI MA") // Plot the RSI MA

// Adding the lines of the RSI oscillator
plot(osc, title="RSI", linewidth=1, color=color.purple)
hline(50, title="Middle Line", linestyle=hline.style_dotted)
obLevel = hline(75, title="Overbought", linestyle=hline.style_dotted)
osLevel = hline(25, title="Oversold", linestyle=hline.style_dotted)
fill(obLevel, osLevel, title="Background", color=color.purple, transp=80)


atrLength = input(14, title="ATR Length (for Trailing stop loss)")
atrMultiplier = input(3.5, title="ATR Multiplier (for Trailing stop loss)")







// RSI PIVOTS --------------------------------------------------------------------------------------------------------------------------------------------------
// Define a condition for RSI pivot low
isFirstPivotLowlong = not na(pivotlow(osc, lbLlong, lbRlong))
// Define a condition for RSI pivot high
isFirstPivotHighlong = not na(pivothigh(osc, lbLlong, lbRlong))
// Define a condition for the first RSI value
firstPivotRSIValuelong = isFirstPivotLowlong ? osc[lbRlong] : na
// Define a condition for the second RSI value
secondPivotRSIValuelong = isFirstPivotLowlong ? valuewhen(isFirstPivotLowlong, osc[lbRlong], 1) : na


// Define a condition for RSI pivot low
isFirstPivotLowshort = not na(pivotlow(osc, lbLshort, lbRshort))
// Define a condition for RSI pivot high
isFirstPivotHighshort = not na(pivothigh(osc, lbLshort, lbRshort))
// Define a condition for the first RSI value
firstPivotRSIValueshort = isFirstPivotLowshort ? osc[lbRshort] : na
// Define a condition for the second RSI value
secondPivotRSIValueshort = isFirstPivotLowshort ? valuewhen(isFirstPivotLowshort, osc[lbRshort], 1) : na

_inRange(cond) =>
    bars = barssince(cond == true)
    rangeLower <= bars and bars <= rangeUpper









// ADDITIONAL ENTRY CRITERIA --------------------------------------------------------------------------------------------------------------------------------------------------
// RSI crosses RSI MA up by more than 2 points and subsequently down
rsiUpCross = crossover(osc, rsi_ma + 1)
rsiDownCross = crossunder(osc, rsi_ma - 1)

// Calculate the daily RSI
rsiDaily = security(syminfo.ticker, "D", rsi(src, 14))





// BULLISH CONDITIONS --------------------------------------------------------------------------------------------------------------------------------------------------

// LOWER LOW PRICE & HIGHER LOW OSC

// Price: Lower Low
priceLL = na(isFirstPivotLowlong[1]) ? false : (low[lbRlong] < valuewhen(isFirstPivotLowlong, low[lbRlong], 1))
// Osc: Higher Low
oscHL = na(isFirstPivotLowlong[1]) ? false : (osc[lbRlong] > valuewhen(isFirstPivotLowlong, osc[lbRlong], 1) and _inRange(isFirstPivotLowlong[1]))



// BULLISH PLOT
bullCond = plotBull and priceLL and oscHL and isFirstPivotLowlong
plot(
     isFirstPivotLowlong ? osc[lbRlong] : na,
     offset=-lbRlong,
     title="Regular Bullish",
     linewidth=2,
     color=(bullCond ? bullColor : noneColor),
     transp=0
     )

plotshape(
     bullCond ? osc[lbRlong] : na,
     offset=-lbRlong,
     title="Regular Bullish Label",
     text=" Bull ",
     style=shape.labelup,
     location=location.absolute,
     color=bullColor,
     textcolor=textColor,
     transp=0
     )









// BEARISH CONDITIONS --------------------------------------------------------------------------------------------------------------------------------------------------

// HIGHER HIGH PRICE & LOWER LOW OSC
// Osc: Lower High
oscLH = na(isFirstPivotHighshort[1]) ? false : (osc[lbRshort] < valuewhen(isFirstPivotHighshort, osc[lbRshort], 1) and _inRange(isFirstPivotHighshort[1]))
// Price: Higher High
priceHH = na(isFirstPivotHighshort[1]) ? false : (high[lbRshort] > valuewhen(isFirstPivotHighshort, high[lbRshort], 1))


// BEARISH PLOT
bearCond = plotBear and priceHH and oscLH and isFirstPivotHighshort

plot(
     isFirstPivotHighshort ? osc[lbRshort] : na,
     offset=-lbRshort,
     title="Regular Bearish",
     linewidth=2,
     color=(bearCond ? bearColor : noneColor),
     transp=0
     )

plotshape(
     bearCond ? osc[lbRshort] : na,
     offset=-lbRshort,
     title="Regular Bearish Label",
     text=" Bear ",
     style=shape.labeldown,
     location=location.absolute,
     color=bearColor,
     textcolor=textColor,
     transp=0
     )




// ENTRY CONDITIONS --------------------------------------------------------------------------------------------------------------------------------------------------

longCondition = false
shortCondition = false

// Entry Conditions
longCondition := bullCond
shortCondition := bearCond

// Conditions to prevent entering trades based on daily RSI
longCondition := longCondition and rsiDaily >= 23
shortCondition := shortCondition and rsiDaily <= 80




// STOPLOSS CONDITIONS --------------------------------------------------------------------------------------------------------------------------------------------------
// Stoploss Conditions
long_sl_val = 
      longStopLossType == "ATR" ? longStopLossValue * atr(atrLength) 
      : longStopLossType == "PERC" ? close * longStopLossValue / 100 : 0.00
long_trailing_sl = 0.0
long_trailing_sl := strategy.position_size >= 1 ? max(low - long_sl_val, nz(long_trailing_sl[1])) : na

// Calculate Trailing Stop Loss for Short Entries
short_sl_val = 
      shortStopLossType == "ATR" ? 1 - shortStopLossValue * atr(atrLength) 
      : shortStopLossType == "PERC" ? close * (shortStopLossValue / 100) : 0.00 //PERC = shortstoplossvalue = -21300 * 5 / 100 = -1065
short_trailing_sl = 0.0
short_trailing_sl := strategy.position_size <= -1 ? max(high + short_sl_val, nz(short_trailing_sl[1])) : na






// RSI STOP CONDITION
 
rsiStopShort = (strategy.position_avg_price != 0.0 and close <= strategy.position_avg_price * 0.90) or (strategy.position_avg_price != 0.0 and rsi(src, 14) >= 75)
 
rsiStopLong = (strategy.position_avg_price != 0.0 and close >= strategy.position_avg_price * 1.10) or (strategy.position_avg_price != 0.0 and rsi(src, 14) <= 25)


// LONG CONDITIONS --------------------------------------------------------------------------------------------------------------------------------------------------
strategy.entry(id="RSIDivLELong", long=true, when=longCondition)

strategy.entry(id="RSIDivLEShort", long=false, when=shortCondition)







// Close Conditions
shortCloseCondition = bullCond // or cross(osc, takeProfitShortRSILevel)
strategy.close(id="RSIDivLEShort", comment="Close All="+tostring(-close + strategy.position_avg_price, "####.##"), when=abs(strategy.position_size) <= -1 and shortStopLossType == "NONE" and shortCloseCondition )
strategy.close(id="RSIDivLEShort", comment="TSL="+tostring(-close + strategy.position_avg_price, "####.##"), when=abs(strategy.position_size) >= -1 and ((shortStopLossType == "PERC" or shortStopLossType == "ATR") and cross(short_trailing_sl,high))) // or rsiStopShort)// or rsiStopShort)


longCloseCondition = bearCond
strategy.close(id="RSIDivLELong", comment="Close All="+tostring(close - strategy.position_avg_price, "####.##"), when=abs(strategy.position_size) >= 1 and longStopLossType == "NONE" and longCloseCondition)
strategy.close(id="RSIDivLELong", comment="TSL="+tostring(close - strategy.position_avg_price, "####.##"), when=abs(strategy.position_size) >= 1 and ((longStopLossType == "PERC" or longStopLossType == "ATR") and cross(long_trailing_sl,low)))  //or rsiStopLong


더 많은