Tres promedios móviles exponenciales y estrategia de negociación del índice de fuerza relativa estocástico

El autor:¿ Qué pasa?, fecha: 2024-01-30 16:52:48
Las etiquetas:

img

Resumen general

Esta es una estrategia de seguimiento de tendencia que combina la media móvil exponencial triple (EMA) y el índice de fuerza relativa estocástica (Stoch RSI) para generar señales de negociación. Va largo cuando la EMA rápida cruza por encima de la EMA media y la EMA media cruza por encima de la EMA lenta. Va corto cuando sucede lo contrario. La estrategia también utiliza el Stoch RSI como indicador auxiliar.

Principios

  1. Utilice las EMA de 8, 14, 50 días. Ir largo cuando la EMA de 8 días > la EMA de 14 días > la EMA de 50 días. Ir corto cuando es lo contrario.

  2. Utilice el RSI estocástico como indicador auxiliar. Calcule primero el RSI de 14 días, luego calcule el Estocástico en el RSI, finalmente calcule el SMA de 3 días como línea K y el SMA de 3 días en la línea K como línea D. El cruce de K sobre D da una señal larga.

  3. Las operaciones largas se registran cuando el cierre es > 8 días de EMA en señal larga.

  4. Se establecerá un stop loss a una distancia ATR por debajo/por encima del precio de entrada y se obtendrá un beneficio a una distancia ATR de 4 por encima/por debajo del precio de entrada.

Los puntos fuertes

  1. El EMA como indicador base puede realizar un seguimiento eficaz de las tendencias.

  2. Agregar Stoch RSI puede filtrar señales falsas y aumentar la precisión de entrada.

  3. El sistema de stop loss y take profit basado en ATR puede realizar un seguimiento dinámico de la volatilidad del mercado, evitando la colocación inadecuada.

  4. Esta estrategia tiene parámetros bien ajustados y tiene un gran rendimiento durante los períodos de tendencia.

Los riesgos

  1. La combinación de múltiples indicadores aumenta el riesgo de whipsaw. Las señales conflictivas entre EMA y Stoch RSI pueden causar una entrada en niveles malos.

  2. Los parámetros de stop loss y take profit conservadores podrían verse violados por enormes oscilaciones del mercado, causando salidas prematuras que faltan nuevas tendencias.

  3. La configuración de la EMA triple tiene cierto retraso cuando las líneas rápidas y medianas se invierten.

  4. Esta estrategia favorece la tendencia del mercado. Los mercados laterales no se desempeñarían bien. Ajustar los períodos de MA o agregar otros indicadores auxiliares puede ayudar.

Mejoras

  1. Añadir indicadores como el MACD para mejores entradas.

  2. Optimización de los parámetros de prueba largo / corto en ATR. Por ejemplo, ajustar la pérdida de parada de 1 ATR a 1.5 ATR, obtener beneficios de 4 ATR a 3 ATR para obtener mejores resultados.

  3. Eliminar el índice de rentabilidad de Stoch y mantener solo los MA para filtrar ruidos y obtener ganancias más estables.

  4. Añadir más criterios para juzgar la tendencia, como los volúmenes comerciales, para operar por debajo de niveles significativos.

Conclusión

Esta estrategia combina triple EMA y Stoch RSI para determinar tendencias. Las señales de entrada estrictas reducen las operaciones innecesarias. SL dinámico y TP basado en ATR hace que los parámetros adaptables. Las pruebas de retroceso muestran grandes resultados durante los períodos de tendencia con reducciones más pequeñas y ganancias 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")



Más.