ADX + RSI Estratégia

Autora:ChaoZhang, Data: 2023-09-27 16:27:39
Tags:

Resumo

Esta é uma estratégia de tendência que combina os indicadores ADX e RSI. Ele usa o RSI para identificar os níveis de sobrecompra e sobrevenda para gerar sinais de negociação, e o ADX para determinar a tendência para filtrar os negócios quando a tendência não é clara, evitando assim flutuações em mercados de faixa.

Estratégia lógica

  1. Utilize o RSI de 7 períodos para identificar os níveis de sobrecompra e sobrevenda
  • O RSI abaixo de 30 é considerado sobrevendido
  • O RSI acima de 70 é considerado sobrecomprado
  1. Use o ADX para determinar a tendência
  • ADX acima de 30 sugere uma forte tendência
  • ADX abaixo de 30 sugere nenhuma tendência
  1. Regras de entrada
  • O valor da posição em risco deve ser calculado em função do valor da posição em risco
  • Caso o RSI > 70 e o ADX > 30
  1. Tirar lucro e parar de perder
  • Métodos opcionais de captação de lucro e de stop loss - baseados em close-out ou baseados em swing
  • Preços de fechamento de utilizações próximas
  • Utilizações baseadas no balanço (swing-based uses) recentes altas/baixas do balanço

Análise das vantagens

  1. O RSI identifica eficazmente os níveis de sobrecompra e sobrevenda para evitar armadilhas de compra/venda

  2. ADX filtra mercados de gama limitada para evitar whipsaws

  3. Métodos opcionais de captação de lucro/stop loss ajudam a controlar melhor os riscos

  4. Simples e fácil de entender, bom para iniciantes a aprender algoritmo de negociação

  5. Muito espaço para otimização e refinamento de parâmetros

Análise de riscos

  1. O RSI sobrecomprado/sobrevendido pode ter retrações e reversões

  2. A determinação da tendência do ADX tem atrasos, pode perder pontos de virada da tendência

  3. A colocação incorreta de um stop loss pode levar a perdas

  4. Risco de otimização excessiva devido à simplicidade

  5. Optimização de parâmetros necessária para um melhor desempenho

Orientações de otimização

  1. Otimizar os parâmetros do RSI e os níveis de sobrecompra/supervenda

  2. Teste diferentes períodos de ADX para encontrar a configuração ideal

  3. Teste diferentes métodos de captação de lucro/stop loss

  4. Adicionar filtro de tendência para evitar negociações contra-tendência

  5. Combinar com outros indicadores para melhorar o desempenho

Resumo

Esta estratégia combina os pontos fortes dos indicadores clássicos RSI e ADX para identificar tendências e evitar problemas. Tem muito espaço para otimização para alcançar um melhor desempenho.


/*backtest
start: 2023-09-19 00:00:00
end: 2023-09-26 00:00:00
period: 15m
basePeriod: 5m
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/
// © tweakerID

// This is a strategy that uses the 7 Period RSI to buy when the indicator is shown as oversold (OS) and sells when 
// the index marks overbought (OB). It also uses the ADX to determine whether the trend is ranging or trending
// and filters out the trending trades. Seems to work better for automated trading when the logic is inversed (buying OB 
// and selling the OS) wihout stop loss.

//@version=4
strategy("ADX + RSI Strat", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=100, initial_capital=100, commission_value=0.04, calc_on_every_tick=false)

direction = input(0, title = "Strategy Direction", type=input.integer, minval=-1, maxval=1)
strategy.risk.allow_entry_in(direction == 0 ? strategy.direction.all : (direction < 0 ? strategy.direction.short : strategy.direction.long))


//SL & TP Inputs
i_SL=input(false, title="Use Swing Lo/Hi Stop Loss & Take Profit")
i_SwingLookback=input(20, title="Swing Lo/Hi Lookback")
i_SLExpander=input(defval=0, step=.2, title="SL Expander")
i_TPExpander=input(defval=0, step=.2, title="TP Expander")
i_reverse=input(true, title="Reverse Trades")

//SL & TP Calculations
SwingLow=lowest(i_SwingLookback)
SwingHigh=highest(i_SwingLookback)
bought=strategy.position_size != strategy.position_size[1]
LSL=valuewhen(bought, SwingLow, 0)-((valuewhen(bought, atr(14), 0))*i_SLExpander)
SSL=valuewhen(bought, SwingHigh, 0)+((valuewhen(bought, atr(14), 0))*i_SLExpander)
lTP=strategy.position_avg_price + (strategy.position_avg_price-(valuewhen(bought, SwingLow, 0))+((valuewhen(bought, atr(14), 0))*i_TPExpander))
sTP=strategy.position_avg_price - (valuewhen(bought, SwingHigh, 0)-strategy.position_avg_price)-((valuewhen(bought, atr(14), 0))*i_TPExpander)
islong=strategy.position_size > 0
isshort=strategy.position_size < 0
SL= islong ? LSL : isshort ? SSL : na
TP= islong ? lTP : isshort ? sTP : na

//RSI Calculations
RSI=rsi(close, 7)
OS=input(30, step=5)
OB=input(80, step=5)

//ADX Calculations
adxlen = input(14, title="ADX Smoothing")
dilen = input(14, title="DI Length")
dirmov(len) =>
	up = change(high)
	down = -change(low)
	plusDM = na(up) ? na : (up > down and up > 0 ? up : 0)
	minusDM = na(down) ? na : (down > up and down > 0 ? down : 0)
	truerange = rma(tr, len)
	plus = fixnan(100 * rma(plusDM, len) / truerange)
	minus = fixnan(100 * rma(minusDM, len) / truerange)
	[plus, minus]
adx(dilen, adxlen) =>
	[plus, minus] = dirmov(dilen)
	sum = plus + minus
	adx = 100 * rma(abs(plus - minus) / (sum == 0 ? 1 : sum), adxlen)
sig = adx(dilen, adxlen)
adxlevel=input(30, step=5)


//Entry Logic
BUY = sig < adxlevel and (RSI < OS) 
SELL = sig < adxlevel and (RSI > OB) 

//Entries
strategy.entry("long", strategy.long, when=i_reverse?SELL:BUY)
strategy.entry("short", strategy.short, when=not i_reverse?SELL:BUY)
//Exits
if i_SL
    strategy.exit("longexit", "long", stop=SL, limit=TP)
    strategy.exit("shortexit", "short", stop=SL, limit=TP)

//Plots
plot(i_SL ? SL : na, color=color.red, style=plot.style_cross, title="SL")
plot(i_SL ? TP : na, color=color.green, style=plot.style_cross, title="TP")
plotshape(BUY ? 1 : na, style=shape.triangleup, location=location.belowbar, color=color.green, title="Bullish Setup")
plotshape(SELL ? 1 : na, style=shape.triangledown, location=location.abovebar, color=color.red, title="Bearish Setup")

Mais.