Estrategia MACD - Negociación de salida de dos vías

El autor:¿ Qué pasa?, Fecha: 2023-12-12 12:44:50
Las etiquetas:

img

Resumen general

Esta estrategia utiliza el indicador de divergencia de convergencia media móvil (MACD) para generar señales largas y cortas y realiza operaciones de reversión en buenas condiciones de tendencia estableciendo dinámicamente puntos de salida para capturar ganancias.

Principios de estrategia

El núcleo de esta estrategia se basa en la cruz de oro del MACD para señales largas y la cruz de muerte para señales cortas.

En las señales de cruz dorada, vaya largo si el precio de cierre está por encima de la EMA; en las señales de cruz de muerte, vaya corto si el precio de cierre está por debajo de la EMA. Esto asegura la inversión de las operaciones bajo una tendencia al alza.

Después de ingresar posiciones, la estrategia utiliza stop loss y take profit para controlar dinámicamente las salidas. Específicamente, el stop loss para posiciones largas se establece en el precio de entrada * (1 - max drawdown); take profit se establece en el precio de entrada * (1 + TARGET_STOP_RATIO * max drawdown).

La ventaja de esta estrategia de stop dinámico es que puede ajustar el stop loss y la relación riesgo/recompensación en función de la volatilidad del mercado.

Ventajas

  1. El MACD es un indicador eficaz para identificar oportunidades de reversión.

  2. El filtro EMA asegura que las operaciones largas ocurran solo en un mercado de tendencia al alza.

  3. El sistema de control de salida dinámico maximiza las ganancias mientras gestiona eficazmente el riesgo.

  4. La velocidad rápida reduce el tiempo de monitoreo requerido, lo que lo hace adecuado para inversores ocupados.

Riesgos y soluciones

  1. El MACD oscila con frecuencia durante los mercados laterales, generando señales falsas.

  2. La volatilidad extrema puede hacer que el DYNAMIC STOP sea demasiado flojo.

  3. Los inversores necesitan cierta resistencia psicológica y compromiso de tiempo.

Direcciones de optimización

  1. Ajuste fino de los parámetros MACD basados en las características del símbolo para optimizar la calidad de la señal.

  2. Pruebe diferentes promedios móviles como filtro de tendencia para encontrar el óptimo.

  3. Prueba el cálculo de TARGET_STOP_RATIO y la definición de la extracción máxima para optimizar la estrategia de salida.

  4. Añadir otros factores como volumen, volatilidad, etc. para mejorar la calidad de la señal.

  5. Explorar modelos de aprendizaje automático para extraer más características y construir modelos multifactorial adaptativos para salidas más inteligentes.

Conclusión

Esta estrategia tiene un fuerte valor práctico en general. Con el MACD como señal comercial principal, los módulos adicionales de filtro de tendencia y control de salida dinámico pueden mejorar significativamente el rendimiento del MACD en sí mismo. El control de salida es esencial para la optimización de la estrategia y esta estrategia innova sustancialmente en esta área. Vale la pena investigar y aplicar más.


/*backtest
start: 2022-12-05 00:00:00
end: 2023-12-11 00:00:00
period: 1d
basePeriod: 1h
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/
// © maxencetajet

//@version=5
strategy("MACD Strategy", overlay=true, initial_capital=1000, slippage=25)

src = input(title="Source", defval=close)
target_stop_ratio = input.float(title='Risk/Reward', defval=2, minval=0.5, maxval=100)
risk = input.float(2, title="Risk per Trade %")

riskt = risk / 100 + 1

useDateFilter = input.bool(true, title="Filter Date Range of Backtest",
     group="Backtest Time Period")
backtestStartDate = input(timestamp("5 June 2022"), 
     title="Start Date", group="Backtest Time Period",
     tooltip="This start date is in the time zone of the exchange " + 
     "where the chart's instrument trades. It doesn't use the time " + 
     "zone of the chart or of your computer.")
backtestEndDate = input(timestamp("5 July 2022"),
     title="End Date", group="Backtest Time Period",
     tooltip="This end date is in the time zone of the exchange " + 
     "where the chart's instrument trades. It doesn't use the time " + 
     "zone of the chart or of your computer.")

inTradeWindow =  true
emaV = input.int(200, title="Length", group="EMA")
swingHighV = input.int(7, title="Swing High", group="number of past candles")
swingLowV = input.int(7, title="Swing Low", group="number of past candles")

ema = ta.ema(src, emaV)

fast_length = input(title="Fast Length", defval=12, group="MACD")
slow_length = input(title="Slow Length", defval=26, group="MACD")
signal_length = input.int(title="Signal Smoothing",  minval = 1, maxval = 50, defval = 9, group="MACD")
sma_source = input.string(title="Oscillator MA Type",  defval="EMA", options=["SMA", "EMA"], group="MACD")
sma_signal = input.string(title="Signal Line MA Type", defval="EMA", options=["SMA", "EMA"], group="MACD")

fast_ma = sma_source == "SMA" ? ta.sma(src, fast_length) : ta.ema(src, fast_length)
slow_ma = sma_source == "SMA" ? ta.sma(src, slow_length) : ta.ema(src, slow_length)
macd = fast_ma - slow_ma
signal = sma_signal == "SMA" ? ta.sma(macd, signal_length) : ta.ema(macd, signal_length)
hist = macd - signal

longcondition = close > ema and ta.crossover(macd, signal) and macd < 0
shortcondition = close < ema and ta.crossunder(macd, signal) and macd > 0

float risk_long = na
float risk_short = na
float stopLoss = na
float takeProfit = na
float entry_price = na

risk_long := risk_long[1]
risk_short := risk_short[1]

swingHigh = ta.highest(high, swingHighV)
swingLow = ta.lowest(low, swingLowV)

lotB = (strategy.equity*riskt-strategy.equity)/(close - swingLow)
lotS = (strategy.equity*riskt-strategy.equity)/(swingHigh - close)

if strategy.position_size == 0 and longcondition and inTradeWindow
    risk_long := (close - swingLow) / close
    strategy.entry("long", strategy.long, qty=lotB)
    
if strategy.position_size == 0 and shortcondition and inTradeWindow
    risk_short := (swingHigh - close) / close  
    strategy.entry("short", strategy.short, qty=lotS)

if strategy.position_size > 0

    stopLoss := strategy.position_avg_price * (1 - risk_long)
    takeProfit := strategy.position_avg_price * (1 + target_stop_ratio * risk_long)
    entry_price := strategy.position_avg_price
    strategy.exit("long exit", "long", stop = stopLoss, limit = takeProfit)
    
if strategy.position_size < 0

    stopLoss := strategy.position_avg_price * (1 + risk_short)
    takeProfit := strategy.position_avg_price * (1 - target_stop_ratio * risk_short)
    entry_price := strategy.position_avg_price
    strategy.exit("short exit", "short", stop = stopLoss, limit = takeProfit)
    
plot(ema, color=color.white, linewidth=2, title="EMA")
p_ep = plot(entry_price, color=color.new(color.white, 0), linewidth=2, style=plot.style_linebr, title='entry price')
p_sl = plot(stopLoss, color=color.new(color.red, 0), linewidth=2, style=plot.style_linebr, title='stopLoss')
p_tp = plot(takeProfit, color=color.new(color.green, 0), linewidth=2, style=plot.style_linebr, title='takeProfit')
fill(p_sl, p_ep, color.new(color.red, transp=85))
fill(p_tp, p_ep, color.new(color.green, transp=85))



Más.