Indicateur RSI Stratégie de négociation de séparation longue courte

Auteur:ChaoZhang est là., Date: le 26 février 2024 à 13h49h25
Les étiquettes:

img

Résumé

Cette stratégie identifie les phénomènes de séparation longue courte à travers l'indicateur RSI pour prendre des décisions commerciales. L'idée de base est que lorsque les prix atteignent de nouveaux bas mais que l'indicateur RSI atteint de nouveaux sommets, un signal de séparation haussière est généré, indiquant que le bas s'est formé et va long. Lorsque les prix atteignent de nouveaux sommets mais que l'indicateur RSI atteint de nouveaux sommets, un signal de séparation baissière est généré, indiquant que le haut s'est formé et va court.

Principes de stratégie

La stratégie utilise principalement l'indicateur RSI pour identifier la longue séparation courte entre les prix et l'indicateur RSI.

  1. Utiliser les paramètres de l'indicateur RSI de 13 et les prix de clôture comme données sources
  2. Définir la fourchette à gauche pour la séparation haussière comme 14 jours et la fourchette à droite comme 2 jours
  3. Définir la fourchette de rétrospective gauche pour la séparation baissière comme 47 jours et la fourchette de rétrospective droite comme 1 jour
  4. Lorsque les prix atteignent des niveaux inférieurs mais que l'indice de volatilité atteint des niveaux plus bas, la condition de séparation longue est remplie pour générer des signaux longs.
  5. Lorsque les prix atteignent des sommets plus élevés, mais que l'indice RSI atteint des sommets plus bas, la condition de séparation courte est remplie pour générer des signaux courts.

En identifiant la longue séparation courte entre les prix et l'ISR, il peut capturer les points d'inflexion des tendances des prix à l'avance pour la prise de décision commerciale.

Les avantages de la stratégie

Les principaux avantages de cette stratégie sont les suivants:

  1. L'identification de la séparation prix/RSI peut permettre de juger des inflexions de tendance tôt pour saisir les opportunités de trading
  2. Utilisez l' analyse des indicateurs pour être moins affecté par les émotions
  3. Utilisez des périodes de repérage fixes pour identifier la séparation, en évitant de régler fréquemment les paramètres
  4. Des conditions supplémentaires telles que l'indice de résistance quotidien réduisent les faux signaux.

Risques et solutions

Il y a encore des risques:

  1. La divergence du RSI ne signifie pas nécessairement un renversement immédiat, il peut exister un décalage temporel entraînant un risque de perte d'arrêt.

  2. La solution consiste à ajouter des conditions de filtrage quotidiennes ou hebdomadaires à plus long terme.

  3. Une petite divergence peut ne pas confirmer un renversement de tendance, il faut élargir les périodes de rétrospective pour trouver une divergence plus significative de l'ISR.

Directions d'optimisation

La stratégie peut être améliorée dans les domaines suivants:

  1. Optimiser les paramètres RSI pour trouver les meilleures combinaisons

  2. Essayez d'autres indicateurs techniques comme MACD, KD pour identifier la séparation

  3. Ajouter des filtres d'oscillation pour réduire les faux signaux dans les périodes agitées

  4. Combinez les RSI à partir de plusieurs délais pour trouver les meilleurs signaux de combinaison

Conclusion

La stratégie de trading de séparation longue courte du RSI juge les inflexions de tendance en identifiant la divergence entre le prix et le RSI pour générer des signaux de trading.


/*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


Plus de