Três médias móveis exponenciais e estratégia de negociação do índice de força relativa estocástico

Autora:ChaoZhang, Data: 2024-01-30 16:52:48
Tags:

img

Resumo

Esta é uma estratégia que combina a média móvel exponencial tripla (EMA) e o índice de força relativa estocástica (Stoch RSI) para gerar sinais de negociação.

Princípios

  1. Usar EMAs de 8, 14, 50 dias. Ir longo quando a EMA de 8 dias > 14 dias EMA > 50 dias EMA. Ir curto quando é o oposto.

  2. Use o RSI estocástico como indicador auxiliar. Calcule primeiro o RSI de 14 dias, em seguida, calcule o Stochastic no RSI, finalmente calcule a SMA de 3 dias como linha K e a SMA de 3 dias na linha K como linha D. O cruzamento de K sobre D dá sinal longo.

  3. Introdução de transacções longas quando o fechamento > 8 dias EMA em sinal longo Introdução de transacções curtas quando o fechamento < 8 dias EMA em sinal curto

  4. O valor da posição em risco deve ser calculado em função da posição em risco da posição em risco, em função da posição em risco.

Forças

  1. A EMA como indicador de base pode rastrear as tendências de forma eficaz.

  2. A adição de Stoch RSI pode filtrar sinais falsos e aumentar a precisão de entrada.

  3. O sistema de stop loss e take profit baseado no ATR pode rastrear dinamicamente a volatilidade do mercado, evitando colocações inadequadas.

  4. Esta estratégia tem parâmetros bem ajustados e tem um excelente desempenho durante os períodos de tendência.

Riscos

  1. A combinação de múltiplos indicadores aumenta o risco de Whipsaw. Sinais conflitantes entre EMA e Stoch RSI podem causar entrada em níveis ruins. A própria tendência de preços precisa de monitoramento em tais casos.

  2. As configurações conservadoras de stop loss e take profit podem ser violadas por enormes oscilações do mercado, causando saídas prematuras sem novas tendências.

  3. A configuração da EMA tripla tem certo atraso quando as linhas rápidas e médias se invertem.

  4. Esta estratégia favorece o mercado em tendência. Os mercados laterais não teriam um bom desempenho. Ajustar os períodos de MA ou adicionar outros indicadores auxiliares pode ajudar.

Melhorias

  1. Adicionar indicadores como o MACD para melhores entradas.

  2. Otimizar os parâmetros de teste longo/curto no ATR. Como ajustar a perda de parada de 1 ATR para 1,5 ATR, tirar lucro de 4 ATR para 3 ATR para melhores resultados.

  3. Remover o RSI do Stoch e manter apenas os MAs para filtrar ruídos e lucros mais estáveis.

  4. Adicionar mais critérios para avaliar a tendência, como volumes de negociação, para operar abaixo de níveis significativos.

Conclusão

Esta estratégia combina a EMA tripla e o Stoch RSI para determinar tendências. Sinais de entrada rígidos reduzem os negócios desnecessários. SL dinâmico e TP baseados no ATR tornam os parâmetros adaptáveis. Os backtests mostram ótimos resultados durante períodos de tendência com reduções menores e lucros consistentes.


/*backtest
start: 2023-12-01 00:00:00
end: 2023-12-31 23:59:59
period: 1h
basePeriod: 15m
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}]
*/

//              3ESRA
//              v0.2a

// Coded by Vaida Bogdan

// 3ESRA consists of a 3 EMA cross + a close above (for longs) the quickest EMA
// or below (for shorts). Note that I've deactivated the RSI Cross Over/Under
// (you can modify the code and activate it). The strategy also uses a stop loss
// that's at 1 ATR distance from the entry price and a take profit that's at
// 4 times the ATR distance from the entry price.

// Feedback:
// Tested BTCUSDT Daily
// 1. Stoch-RSI makes you miss opportunities.
// 2. Changing RR to 4:1 times ATR works better.

//@version=4
strategy(title="3 EMA + Stochastic RSI + ATR", shorttitle="3ESRA", overlay=true, pyramiding=1,
     process_orders_on_close=true, calc_on_every_tick=true,
     initial_capital=1000, currency = currency.USD, default_qty_value=10, 
     default_qty_type=strategy.percent_of_equity,
     commission_type=strategy.commission.percent, commission_value=0.1, slippage=2)

startDate = input(title="Start Date", type=input.integer,
     defval=1, minval=1, maxval=31, group="Backtesting range")
startMonth = input(title="Start Month", type=input.integer,
     defval=1, minval=1, maxval=12, group="Backtesting range")
startYear = input(title="Start Year", type=input.integer,
     defval=1900, minval=1800, maxval=2100, group="Backtesting range")
endDate = input(title="End Date", type=input.integer,
     defval=1, minval=1, maxval=31, group="Backtesting range")
endMonth = input(title="End Month", type=input.integer,
     defval=1, minval=1, maxval=12, group="Backtesting range")
endYear = input(title="End Year", type=input.integer,
     defval=2040, minval=1800, maxval=2100, group="Backtesting range")

// Date range filtering
inDateRange = (time >= timestamp(syminfo.timezone, startYear, startMonth, startDate, 0, 0)) and
     (time < timestamp(syminfo.timezone, endYear, endMonth, endDate, 23, 59))
     
fast = input(8, minval=8, title="Fast EMA", group="EMAs")
medium = input(14, minval=8, title="Medium EMA", group="EMAs")
slow = input(50, minval=8, title="Slow EMA", group="EMAs")
src = input(close, title="Source")

smoothK = input(3, "K", minval=1, group="Stoch-RSI", inline="K&D")
smoothD = input(3, "D", minval=1, group="Stoch-RSI", inline="K&D")
lengthRSI = input(14, "RSI Length", minval=1, group="Stoch-RSI", inline="length")
lengthStoch = input(14, "Stochastic Length", minval=1, group="Stoch-RSI", inline="length")
rsiSrc = input(close, title="RSI Source", group="Stoch-RSI")

length = input(title="Length", defval=14, minval=1, group="ATR")
smoothing = input(title="Smoothing", defval="RMA", options=["RMA", "SMA", "EMA", "WMA"], group="ATR")

// EMAs
fastema = ema(src, fast)
mediumema = ema(src, medium)
slowema = ema(src, slow)

// S-RSI
rsi1 = rsi(rsiSrc, lengthRSI)
k = sma(stoch(rsi1, rsi1, rsi1, lengthStoch), smoothK)
d = sma(k, smoothD)
sRsiCrossOver = k[1] < d[1] and k > d
sRsiCrossUnder = k[1] > d[1] and k < d

// ATR
ma_function(source, length) =>
	if smoothing == "RMA"
		rma(source, length)
	else
		if smoothing == "SMA"
			sma(source, length)
		else
			if smoothing == "EMA"
				ema(source, length)
			else
				wma(source, length)
atr = ma_function(tr(true), length)

// Trading Logic
longCond1 = (fastema > mediumema) and (mediumema > slowema)
longCond2 = true
// longCond2 = sRsiCrossOver
longCond3 = close > fastema
longCond4 = strategy.position_size <= 0
longCond = longCond1 and longCond2 and longCond3 and longCond4 and inDateRange

shortCond1 = (fastema < mediumema) and (mediumema < slowema)
shortCond2 = true 
// shortCond2 = sRsiCrossUnder
shortCond3 = close < fastema
shortCond4 = strategy.position_size >= 0
shortCond = shortCond1 and shortCond2 and shortCond3 and shortCond4 and inDateRange

var takeProfit = float(na), var stopLoss = float(na)
if longCond and strategy.position_size <= 0
    takeProfit := close + 4*atr
    stopLoss := close - 1*atr
    // takeProfit := close + 2*atr
    // stopLoss := close - 3*atr

else if shortCond and strategy.position_size >= 0
    takeProfit := close - 4*atr
    stopLoss := close + 1*atr
    // takeProfit := close - 2*atr
    // stopLoss := close + 3*atr
    
// Strategy calls
strategy.entry("3ESRA", strategy.long, comment="Long", when=longCond and strategy.position_size <= 0)
strategy.entry("3ESRA", strategy.short, comment="Short", when=shortCond and strategy.position_size >= 0)
strategy.exit(id="TP-SL", from_entry="3ESRA", limit=takeProfit, stop=stopLoss)
if (not inDateRange)
    strategy.close_all()
    
// Plot EMAs
plot(fastema, color=color.purple, linewidth=2, title="Fast EMA")
plot(mediumema, color=color.teal, linewidth=2, title="Medium EMA")
plot(slowema, color=color.yellow, linewidth=2, title="Slow EMA")
// Plot S-RSI
// plotshape((strategy.position_size > 0) ? na : sRsiCrossOver, title="StochRSI Cross Over", style=shape.triangleup, location=location.belowbar, color=color.teal, text="SRSI", size=size.small)
// Plot trade
bgcolor(strategy.position_size > 0 ? color.new(color.green, 75) : strategy.position_size < 0 ? color.new(color.red,75) : color(na))
// Plot Strategy
plot((strategy.position_size != 0) ? takeProfit : na, style=plot.style_linebr, color=color.green, title="TP")
plot((strategy.position_size != 0) ? stopLoss : na, style=plot.style_linebr, color=color.red, title="SL")



Mais.