Estratégia de negociação RSI-SRSI multi-tempo

Autora:ChaoZhang, Data: 2024-02-18 16:13:50
Tags:

img

Resumo

Esta estratégia de negociação combina os indicadores técnicos do Índice de Força Relativa (RSI) e do Índice de Força Relativa Estocástica (RSI) para gerar sinais de negociação.

Nome da estratégia

Estratégia de negociação RSI-SRSI multi-tempo

Estratégia lógica

A estratégia julga as condições de sobrecompra e sobrevenda com base nos valores do RSI. O RSI abaixo de 30 é considerado sinal de sobrevenda e o RSI acima de 70 é considerado sinal de sobrecompra. O indicador RSI estocástico observa a flutuação dos valores do RSI. O RSI estocástico abaixo de 5 é sobrevendo e o RSI estocástico acima de 50 é sobrecomprado.

A estratégia também incorpora a tendência de preço da criptomoeda em prazos mais altos (por exemplo, semanal). Somente quando o RSI de prazos mais altos está acima de um limiar (por exemplo, 45), os sinais longos são acionados. Isso filtra sinais de sobrevenda não persistentes quando a tendência geral está em baixa.

Os sinais de compra e venda devem ser confirmados durante vários períodos (por exemplo, 8 barras) antes de ser gerado um sinal de negociação real para evitar sinais falsos.

Vantagens

  • Método clássico de análise técnica que utiliza o RSI para identificar níveis de sobrecompra/supervenda
  • Incorpora o RSI estocástico para detectar reversões do RSI
  • Aplica técnicas de quadros de tempo múltiplos para filtrar sinais falsos e melhorar a qualidade

Riscos e soluções

  • RSI propenso a gerar falsos sinais
    • Combinar outros indicadores para filtrar sinais falsos
    • Aplicar técnicas de confirmação de tendências
  • Ajustes de limiar inadequados podem produzir muitos sinais
    • Optimize os parâmetros para encontrar a melhor combinação
  • Os sinais precisam de tempo de confirmação.
    • Períodos de confirmação do saldo - filtrar sinais falsos sem perder oportunidades

Áreas de melhoria

  • Teste mais combinações de indicadores para sinais mais fortes
    • Por exemplo, incorporar o indicador MACD
  • Utilize métodos de aprendizagem de máquina para encontrar parâmetros ideais
    • Por exemplo, algoritmos genéticos/algoritmos evolutivos para otimização automatizada
  • Adicionar estratégias de stop loss para controlar os riscos de negociação única
    • Estabelecer stop loss quando o preço ultrapassar o nível de suporte

Conclusão

A estratégia depende principalmente dos dois indicadores técnicos clássicos, RSI e RSI estocástico, para gerar sinais de negociação. Além disso, a introdução de confirmação de tendência a partir de prazos mais altos ajuda a filtrar sinais falsos de forma eficaz e melhora a qualidade do sinal. Uma melhoria adicional do desempenho pode ser alcançada por otimização de parâmetros, adição de stop loss e outros meios. A lógica é simples e fácil de entender.


/*backtest
start: 2023-02-11 00:00:00
end: 2024-02-17 00:00:00
period: 1d
basePeriod: 1h
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}]
*/

//@version=5
strategy("RSI and Stochatic Strategy", overlay=true, use_bar_magnifier = false)


/////// Inputs ///////////////

// RSI and SRSI
rsiLength = input(14, title="RSI Length") 
stochLength = input(14, title="Stochastic Length")
kSmooth = input(3, title="K Smooth")
dSmooth = input(3, title="D Smooth")


//////// thresholds ///////////////
st_low = input(5, title="Low SRSI") // stochastic RSI low -- prepare to sell
st_hi = input(50, title="High SRSI") // stochastic RSI high -- prepare to buy
diff = input(5, title="difference") // minimum change in RSI
// inval_diff = input(12, title="difference") // invalidation difference: change in the oposite direction that invalidates rsi falling/rising
rsi_low = input(30, title="Low RSI") // RSI considered low
rsi_hi = input(60, title="High RSI") // RSI considered high
rsi_ht_hi = input(45, title="High higher time frame RSI") // RSI in higher time frame considered high


/// buy trigger duration 
tr_dur = input(8, title="Trigger duration")
low_dur = input(20, title="Monitoring last low")


///////////////// Higher time frame trend ///////////////////
// higher time frame resolution
res2 = input.timeframe("W", title="Higher time-frame")
// Input for the ticker symbol, default is an empty string
// For instance we could monitor BTC higher time frame trend
symbol = input("BTC_USDT:swap", "Input Ticker (leave empty for current)")

// Determine the symbol to use
inputSymbol = symbol == "" ? syminfo.tickerid : symbol
//////////////////////////////////////////////////////////

// Calculate RSI //
rsi = ta.rsi(close, rsiLength)

// Calculate Stochastic RSI //
rsiLowest = ta.lowest(rsi, stochLength)
rsiHighest = ta.highest(rsi, stochLength)
stochRsi = 100 * (rsi - rsiLowest) / (rsiHighest - rsiLowest)

// Apply smoothing
K = ta.sma(stochRsi, kSmooth)
D = ta.sma(K, dSmooth)

// Higher time Frame RSI
cl2 = request.security(inputSymbol, res2, close)
rsi2 = ta.rsi(cl2, 14)

// SRSI BUY/SELL signals 
sell_stoch = (ta.lowest(K, tr_dur) < st_low) or (ta.highest(rsi, tr_dur) < rsi_low)
buy_stoch = ((ta.lowest(K, tr_dur) > st_hi) or (ta.lowest(rsi, tr_dur) > rsi_hi)) and (rsi2 > rsi_ht_hi)

 // valitation / invalidation sell signal
ll = ta.barssince(not sell_stoch)+1
sell_validation = (ta.highest(rsi, ll)>rsi[ll]+diff and rsi < rsi[ll]) or (rsi < rsi[ll]-diff)

// valitation / invalidation buy signal
llb = ta.barssince(not buy_stoch)+1
buy_validation = (ta.lowest(rsi, llb)<rsi[llb]-diff and rsi > rsi[llb]) or (rsi > rsi_hi and rsi - rsi[tr_dur] > 0)

sell_signal = sell_stoch and sell_validation
buy_signal = buy_stoch and buy_validation 

// Define the start date for the strategy
startYear = input(2019, "Start Year")
startMonth = input(1, "Start Month")
startDay = input(1, "Start Day")

// Convert the start date to Unix time
startTime = timestamp(startYear, startMonth, startDay, 00, 00)

// Define the end date for the strategy
endYear = input(2030, "End Year")
endMonth = input(1, "End Month")
endDay = input(1, "End Day")

// Convert the end date to Unix time
endTime = timestamp(endYear, endMonth, endDay, 00, 00)


if true
    if buy_signal
        strategy.entry("buy", strategy.long, comment = "Buy")
    if sell_signal
        strategy.close("buy", "Sell")

Mais.