Estratégia de ruptura de reversão do RSI

Autora:ChaoZhang, Data: 2023-11-08 12:11:03
Tags:

img

Resumo

Esta estratégia é baseada no indicador de Força Relativa (RSI) e utiliza os princípios de sobrecompra / sobrevenda do RSI para fazer negociações de ruptura.

Estratégia lógica

  1. Defina os parâmetros do indicador RSI com base na entrada do utilizador, incluindo o período RSI, o limiar de sobrecompra e o limiar de sobrevenda.

  2. Determine se o RSI está na zona de sobrecompra ou sobrevenda com base na sua posição em relação aos limiares.

  3. Quando o RSI sair da zona de sobrecompra/supervenda e cruzar a linha de limiar correspondente, faça negociações na direção oposta. Por exemplo, quando o RSI sair acima da linha de sobrecompra da zona de sobrecompra, o mercado é considerado invertido, vá longo neste ponto. Quando o RSI sair abaixo da linha de sobrevenda da zona de sobrevenda, o mercado é considerado invertido, vá curto aqui.

  4. Após a entrada, definir o stop loss e tomar as linhas de lucro, acompanhar SL/TP e fechar as posições quando desencadeado.

  5. A estratégia também fornece a opção de usar a EMA como filtro.

  6. Também permite a negociação apenas dentro de prazos específicos. As posições serão fechadas no final do prazo.

Análise das vantagens

  • Utiliza os princípios clássicos do RSI com bons resultados de backtest.

  • Definição flexível dos limiares de sobrecompra/supervenda adequados para diferentes produtos.

  • O filtro EMA opcional evita transacções excessivas.

  • Suporta SL/TP para melhorar a estabilidade.

  • Suporta o filtro de tempo para evitar períodos inadequados.

  • Apoia tanto o longo como o curto para aproveitar plenamente as flutuações de preços de duas vias.

Análise de riscos

  • A divergência do RSI ocorre com frequência, contando apenas com o RSI pode gerar sinais imprecisos.

  • As definições incorretas de limiares conduzem a operações demasiado frequentes ou em falta.

  • As configurações de SL/TP ruins causam agressividade ou conservadorismo excessivo.

  • As configurações de filtro EMA incorretas podem deixar de lado negociações válidas ou filtrar bons sinais.

Soluções de riscos:

  • Otimizar os parâmetros do RSI para diferentes produtos.

  • Combinar com indicadores de tendência para identificar a divergência.

  • Teste e otimize os parâmetros SL/TP.

  • Teste e otimize os parâmetros da EMA.

Orientações de otimização

A estratégia pode ser melhorada nos seguintes aspectos:

  1. Otimizar os parâmetros do RSI para encontrar as melhores configurações para diferentes produtos através de backtest exaustivo.

  2. Tente diferentes indicadores combinados com ou substituindo o RSI para gerar sinais mais robustos, por exemplo, MACD, KD, Bandas de Bollinger, etc.

  3. Otimize o stop loss e tome estratégias de lucro para melhorar a estabilidade.

  4. Otimize os parâmetros do filtro EMA ou experimente outros filtros para evitar melhor os whipssaws.

  5. Adicionar módulos de filtro de tendência para evitar a negociação contra a tendência primária.

  6. Teste diferentes prazos para encontrar as melhores sessões de negociação para esta estratégia.

Resumo

A estratégia de ruptura de reversão do RSI tem uma lógica clara baseada nos princípios clássicos de sobrecompra / sobrevenda. Tem como objetivo capturar a reversão média nos extremos com filtros de controle de risco adequados. Há um bom potencial para transformá-lo em uma estratégia estável através de ajuste de parâmetros e aprimoramentos modulares. Vale a pena otimizar e aplicar na negociação ao 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)
    



Mais.