Estrategia de ruptura de reversión de los índices de volatilidad

El autor:¿ Qué pasa?, fecha: 2023-11-08 12:11:03
Las etiquetas:

img

Resumen general

Esta estrategia se basa en el indicador de fuerza relativa (RSI) y utiliza los principios de sobrecompra / sobreventa de RSI para realizar operaciones de ruptura.

Estrategia lógica

  1. Establecer los parámetros del indicador RSI basados en la información aportada por el usuario, incluido el período de RSI, el umbral de sobrecompra y el umbral de sobreventa.

  2. Determinar si el RSI se encuentra en la zona de sobrecompra o sobreventa en función de su posición con respecto a los umbrales.

  3. Cuando el RSI se rompe de la zona de sobrecompra / sobreventa y cruza la línea de umbral correspondiente, realice operaciones en la dirección opuesta. Por ejemplo, cuando el RSI se rompe por encima de la línea de sobrecompra de la zona de sobrecompra, el mercado se considera invertido, vaya largo en este punto. Cuando el RSI se rompe por debajo de la línea de sobreventa de la zona de sobreventa, el mercado se considera invertido, vaya corto aquí.

  4. Después de la entrada, establecer el stop loss y tomar las líneas de ganancia.

  5. La estrategia también proporciona la opción de utilizar la EMA como filtro. Solo tome señales comerciales cuando se cumplan tanto la señal RSI como la ruptura del precio contra la dirección de la EMA.

  6. También permite la negociación sólo dentro de plazos específicos.

Análisis de ventajas

  • Utiliza los principios clásicos de ruptura de RSI con buenos resultados de pruebas de retroceso.

  • Establecimiento de umbrales flexibles de sobrecompra/sobreventa adecuados para diferentes productos.

  • El filtro EMA opcional evita las operaciones excesivas con la sierra de golpe.

  • Apoya SL/TP para mejorar la estabilidad.

  • Soporta el filtro de marcos de tiempo para evitar períodos inadecuados.

  • Apoya tanto el largo como el corto para aprovechar al máximo las oscilaciones de precios en dos direcciones.

Análisis de riesgos

  • La divergencia del RSI ocurre con frecuencia, dependiendo únicamente del RSI puede generar señales inexactas.

  • La imposición incorrecta de umbrales conduce a operaciones demasiado frecuentes o no efectuadas.

  • Los malos ajustes SL / TP causan exceso de agresividad o exceso de conservadurismo.

  • Los ajustes incorrectos del filtro de la EMA pueden perder operaciones válidas o filtrar buenas señales.

Soluciones de riesgos:

  • Optimizar los parámetros del RSI para diferentes productos.

  • Combinar con indicadores de tendencia para identificar la divergencia.

  • Prueba y optimización de los parámetros SL/TP.

  • Prueba y optimiza los parámetros EMA.

Direcciones de optimización

La estrategia puede mejorarse en los siguientes aspectos:

  1. Optimizar los parámetros del RSI para encontrar los mejores ajustes para diferentes productos mediante pruebas de retroceso exhaustivas.

  2. Pruebe diferentes indicadores combinados con el RSI o reemplazándolos para generar señales más sólidas, por ejemplo, MACD, KD, bandas de Bollinger, etc.

  3. Optimice las estrategias de stop loss y de ganancias para mejorar la estabilidad.

  4. Optimice los parámetros del filtro EMA o experimente con otros filtros para evitar mejor los frenos.

  5. Añadir módulos de filtro de tendencia para evitar la negociación contra la tendencia primaria.

  6. Pruebe diferentes marcos de tiempo para encontrar las mejores sesiones comerciales para esta estrategia.

Resumen de las actividades

La estrategia de ruptura de reversión del RSI tiene una lógica clara basada en los principios clásicos de sobrecompra / sobreventa. Su objetivo es capturar la reversión media en los extremos con filtros adecuados de control de riesgos. Hay un buen potencial para convertirla en una estrategia estable a través del ajuste de parámetros y mejoras modulares. Vale la pena optimizar y aplicar en el comercio en vivo.


/*backtest
start: 2023-10-08 00:00:00
end: 2023-11-07 00:00:00
period: 1h
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/
// © REV0LUTI0N

//@version=4

strategy("RSI Strategy", overlay=true, initial_capital = 10000, default_qty_value = 10000, default_qty_type = strategy.cash)

// Strategy Backtesting
startDate  = input(timestamp("2021-10-01T00:00:00"), type = input.time, title='Backtesting Start Date')
finishDate = input(timestamp("9999-12-31T00:00:00"), type = input.time, title='Backtesting End Date')

time_cond  = true
// Strategy

Length = input(12, minval=1)
src = input(close, title="Source")
overbought = input(70, minval=1)
oversold = input(30, minval=1)
xRSI = rsi(src, Length)
    
rsinormal = input(true, title="Overbought Go Long & Oversold Go Short")
rsiflipped = input(false, title="Overbought Go Short & Oversold Go Long")

// EMA Filter
noemafilter = input(true, title="No EMA Filter")
useemafilter = input(false, title="Use EMA Filter")
ema_length = input(defval=15, minval=1, title="EMA Length")
emasrc = input(close, title="Source")
ema = ema(emasrc, ema_length)
plot(ema, "EMA", style=plot.style_linebr, color=#cad850, linewidth=2)

//Time Restriction Settings
startendtime = input("", title='Time Frame To Enter Trades')
enableclose = input(false, title='Enable Close Trade At End Of Time Frame')
timetobuy = (time(timeframe.period, startendtime))
timetoclose = na(time(timeframe.period, startendtime))

// Stop Loss & Take Profit % Based
enablesl = input(false, title='Enable Stop Loss')
enabletp = input(false, title='Enable Take Profit')
stopTick = input(5.0, title='Stop Loss %', type=input.float, step=0.1) / 100
takeTick = input(10.0, title='Take Profit %', type=input.float, step=0.1) / 100

longStop = strategy.position_avg_price * (1 - stopTick)
shortStop = strategy.position_avg_price * (1 + stopTick)
shortTake = strategy.position_avg_price * (1 - takeTick)
longTake = strategy.position_avg_price * (1 + takeTick)

plot(strategy.position_size > 0 and enablesl ? longStop : na, style=plot.style_linebr, color=color.red, linewidth=1, title="Long Fixed SL")
plot(strategy.position_size < 0 and enablesl ? shortStop : na, style=plot.style_linebr, color=color.red, linewidth=1, title="Short Fixed SL")
plot(strategy.position_size > 0 and enabletp ? longTake : na, style=plot.style_linebr, color=color.green, linewidth=1, title="Long Take Profit")
plot(strategy.position_size < 0 and enabletp ? shortTake : na, style=plot.style_linebr, color=color.green, linewidth=1, title="Short Take Profit")

// Alert messages
message_enterlong  = input("", title="Long Entry message")
message_entershort = input("", title="Short Entry message")
message_closelong = input("", title="Close Long message")
message_closeshort = input("", title="Close Short message")

// Strategy Execution
if (xRSI > overbought and close > ema and time_cond and timetobuy and rsinormal and useemafilter)
    strategy.entry("Long", strategy.long, alert_message = message_enterlong)
    
if (xRSI < oversold and close < ema and time_cond and timetobuy and rsinormal and useemafilter)
    strategy.entry("Short", strategy.short, alert_message = message_entershort)
    
if (xRSI < oversold and close > ema and time_cond and timetobuy and rsiflipped and useemafilter)
    strategy.entry("Long", strategy.long, alert_message = message_enterlong)
    
if (xRSI > overbought and close < ema and time_cond and timetobuy and rsiflipped and useemafilter)
    strategy.entry("Short", strategy.short, alert_message = message_entershort)
    
if (xRSI > overbought and time_cond and timetobuy and rsinormal and noemafilter)
    strategy.entry("Long", strategy.long, alert_message = message_enterlong)
    
if (xRSI < oversold and time_cond and timetobuy and rsinormal and noemafilter)
    strategy.entry("Short", strategy.short, alert_message = message_entershort)
    
if (xRSI < oversold and time_cond and timetobuy and rsiflipped and noemafilter)
    strategy.entry("Long", strategy.long, alert_message = message_enterlong)
    
if (xRSI > overbought and time_cond and timetobuy and rsiflipped and noemafilter)
    strategy.entry("Short", strategy.short, alert_message = message_entershort)
    
if strategy.position_size > 0 and timetoclose and enableclose
    strategy.close_all(alert_message = message_closelong)
if strategy.position_size < 0 and timetoclose and enableclose
    strategy.close_all(alert_message = message_closeshort)
    
if strategy.position_size > 0 and enablesl and time_cond
    strategy.exit(id="Close Long", stop=longStop, limit=longTake, alert_message = message_closelong)
if strategy.position_size < 0 and enablesl and time_cond
    strategy.exit(id="Close Short", stop=shortStop, limit=shortTake, alert_message = message_closeshort)
    
if strategy.position_size > 0 and enabletp and time_cond
    strategy.exit(id="Close Long", stop=longStop, limit=longTake, alert_message = message_closelong)
if strategy.position_size < 0 and enabletp and time_cond
    strategy.exit(id="Close Short", stop=shortStop, limit=shortTake, alert_message = message_closeshort)
    



Más.