Estrategia de tendencia dinámica a la absorción

El autor:¿ Qué pasa?, Fecha: 2024-02-29 11:24:18
Las etiquetas:

img

Resumen general

La estrategia de tendencia de engulfing dinámico es una estrategia comercial que toma posiciones largas o cortas basadas en patrones de engulfing en la dirección de la tendencia. Esta estrategia utiliza el rango verdadero promedio (ATR) para medir la volatilidad del mercado, el indicador de super tendencia para determinar la dirección de la tendencia del mercado, y entra en operaciones cuando los patrones de engulfing se alinean con la dirección de la tendencia.

Estrategia lógica

  1. Calcular el ATR para medir la volatilidad del mercado.
  2. Calcular el indicador Supertrend para identificar la tendencia del mercado.
  3. Definir las condiciones para la tendencia al alza y la tendencia a la baja.
  4. Identificar el engulfamiento alcista (en tendencia alcista) y el engulfamiento bajista (en tendencia bajista).
  5. Se calcularán los niveles de Stop Loss (SL) y Take Profit (TP) basados en los patrones de engulfing.
  6. Entrar en operaciones cuando los patrones de engulfamiento coinciden con la dirección de la tendencia.
  7. Las operaciones de salida cuando el precio alcanza los niveles SL o TP.
  8. Trace los patrones de engullida en la tabla.

Análisis de ventajas

Las ventajas de esta estrategia incluyen:

  1. Mejora de la calidad de la señal mediante la combinación de patrones de absorción con tendencia.
  2. Capacidad para identificar inversiones de tendencia para entradas precisas.
  3. Despeje señales largas/cortas para un mejor tiempo.
  4. La estrategia de detención de engulfing sigue la tendencia mientras gestiona los riesgos.
  5. Marco de código modular para la optimización fácil.

Análisis de riesgos

También hay algunos riesgos a tener en cuenta:

  1. Los patrones de ingestión pueden resultar ser falsos brotes.
  2. Es difícil determinar los parámetros óptimos como el tamaño del patrón, la duración, etc.
  3. La determinación de tendencias imperfecta puede llevar a señales falsas.
  4. Los niveles de stop loss y take profit dependen de discreciones y pueden ser subjetivos.
  5. El rendimiento depende del ajuste de parámetros basado en datos históricos.

Los riesgos pueden mitigarse mediante:

  1. Añadiendo filtros para eliminar señales falsas de fuga.
  2. Utilizando ATR adaptativo para cálculos de parámetros robustos.
  3. Mejorar la determinación de tendencias mediante el aprendizaje automático.
  4. Encontrar parámetros óptimos mediante algoritmos genéticos.
  5. Pruebas de retroceso durante períodos más largos para garantizar la robustez.

Direcciones de optimización

Hay margen para una mayor optimización:

  1. El aprendizaje automático puede mejorar la determinación de tendencias.
  2. Los nuevos métodos de reconocimiento de patrones pueden identificar mejor los patrones de absorción.
  3. Las últimas estrategias de stop loss / take profit pueden optimizar dinámicamente los niveles.
  4. Los datos de alta frecuencia pueden desarrollar un sistema a corto plazo.
  5. Ajuste de parámetros para diferentes instrumentos.

Conclusión

En resumen, la estrategia de tendencia de engulfing dinámico combina las señales de patrón de engulfing de alta calidad con la determinación de tendencia precisa para generar un sistema de negociación con entradas precisas y pérdidas de parada razonables y toma de ganancias.


/*backtest
start: 2024-01-01 00:00:00
end: 2024-01-31 23:59:59
period: 1h
basePeriod: 15m
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/
// © Malikdrajat


//@version=4
strategy("Engulfing with Trend", overlay=true)

Periods = input(title="ATR Period", type=input.integer, defval=10)
src = input(hl2, title="Source")
Multiplier = input(title="ATR Multiplier", type=input.float, step=0.1, defval=3.0)
changeATR= input(title="Change ATR Calculation Method ?", type=input.bool, defval=true)
showsignals = input(title="Show Buy/Sell Signals ?", type=input.bool, defval=true)
highlighting = input(title="Highlighter On/Off ?", type=input.bool, defval=true)

atr2 = sma(tr, Periods)
atr= changeATR ? atr(Periods) : atr2

up=src-(Multiplier*atr)
up1 = nz(up[1],up)
up := close[1] > up1 ? max(up,up1) : up
dn=src+(Multiplier*atr)
dn1 = nz(dn[1], dn)
dn := close[1] < dn1 ? min(dn, dn1) : dn

trend = 1
trend := nz(trend[1], trend)
trend := trend == -1 and close > dn1 ? 1 : trend == 1 and close < up1 ? -1 : trend

upPlot = plot(trend == 1 ? up : na, title="Up Trend", style=plot.style_linebr, linewidth=2, color=color.green)
buySignal = trend == 1 and trend[1] == -1
plotshape(buySignal ? up : na, title="UpTrend Begins", location=location.absolute, style=shape.circle, size=size.tiny, color=color.green, transp=0)
plotshape(buySignal and showsignals ? up : na, title="Buy", text="Buy", location=location.absolute, style=shape.labelup, size=size.tiny, color=color.green, textcolor=color.white, transp=0)
dnPlot = plot(trend == 1 ? na : dn, title="Down Trend", style=plot.style_linebr, linewidth=2, color=color.red)
sellSignal = trend == -1 and trend[1] == 1
plotshape(sellSignal ? dn : na, title="DownTrend Begins", location=location.absolute, style=shape.circle, size=size.tiny, color=color.red, transp=0)
plotshape(sellSignal and showsignals ? dn : na, title="Sell", text="Sell", location=location.absolute, style=shape.labeldown, size=size.tiny, color=color.red, textcolor=color.white, transp=0)
mPlot = plot(ohlc4, title="", style=plot.style_circles, linewidth=0)
longFillColor = highlighting ? (trend == 1 ? color.green : color.white) : color.white
shortFillColor = highlighting ? (trend == -1 ? color.red : color.white) : color.white
fill(mPlot, upPlot, title="UpTrend Highligter", color=longFillColor)
fill(mPlot, dnPlot, title="DownTrend Highligter", color=shortFillColor)
alertcondition(buySignal, title="SuperTrend Buy", message="SuperTrend Buy!")
alertcondition(sellSignal, title="SuperTrend Sell", message="SuperTrend Sell!")
changeCond = trend != trend[1]
alertcondition(changeCond, title="SuperTrend Direction Change", message="SuperTrend has changed direction!")

// Define Downtrend and Uptrend conditions
downtrend = trend == -1
uptrend = trend == 1


// Engulfing 
boringThreshold = input(25, title="Boring Candle Threshold (%)", minval=1, maxval=100, step=1)
engulfingThreshold = input(50, title="Engulfing Candle Threshold (%)", minval=1, maxval=100, step=1)
stopLevel = input(200, title="Stop Level (Pips)", minval=1)


// Boring Candle (Inside Bar) and Engulfing Candlestick Conditions
isBoringCandle = abs(open[1] - close[1]) * 100 / abs(high[1] - low[1]) <= boringThreshold
isEngulfingCandle = abs(open - close) * 100 / abs(high - low) <= engulfingThreshold

// Bullish and Bearish Engulfing Conditions
bullEngulfing = uptrend and close[1] < open[1] and close > open[1] and not isBoringCandle and not isEngulfingCandle
bearEngulfing = downtrend and close[1] > open[1] and close < open[1] and not isBoringCandle and not isEngulfingCandle

// Stop Loss, Take Profit, and Entry Price Calculation
bullStop = close + (stopLevel * syminfo.mintick)
bearStop = close - (stopLevel * syminfo.mintick)
bullSL = low 
bearSL = high
bullTP = bullStop + (bullStop - low)
bearTP = bearStop - (high - bearStop)

// Entry Conditions
enterLong = bullEngulfing and uptrend
enterShort = bearEngulfing and downtrend

// Exit Conditions
exitLong = crossover(close, bullTP) or crossover(close, bullSL)
exitShort = crossover(close, bearTP) or crossover(close, bearSL)

// Check if exit conditions are met by the next candle
exitLongNextCandle = exitLong and (crossover(close[1], bullTP[1]) or crossover(close[1], bullSL[1]))
exitShortNextCandle = exitShort and (crossover(close[1], bearTP[1]) or crossover(close[1], bearSL[1]))

// Strategy Execution
strategy.entry("Buy", strategy.long, when=enterLong )
strategy.entry("Sell", strategy.short, when=enterShort )

// Exit Conditions for Long (Buy) Positions
if (bullEngulfing and not na(bullTP) and not na(bullSL))
    strategy.exit("Exit Long", from_entry="Buy", stop=bullSL, limit=bullTP)

// Exit Conditions for Short (Sell) Positions
if (bearEngulfing and not na(bearTP) and not na(bearSL))
    strategy.exit("Exit Short", from_entry="Sell", stop=bearSL, limit=bearTP)

// Plot Shapes and Labels
plotshape(bullEngulfing, style=shape.triangleup, location=location.abovebar, color=color.green)
plotshape(bearEngulfing, style=shape.triangledown, location=location.abovebar, color=color.red)

// Determine OP, SL, and TP
plot(bullEngulfing ? bullStop : na, title="Bullish Engulfing stop", color=color.red, linewidth=3, style=plot.style_linebr)
plot(bearEngulfing ? bearStop : na, title="Bearish Engulfing stop", color=color.red, linewidth=3, style=plot.style_linebr)
plot(bullEngulfing ? bullSL : na, title="Bullish Engulfing SL", color=color.red, linewidth=3, style=plot.style_linebr)
plot(bearEngulfing ? bearSL : na, title="Bearish Engulfing SL", color=color.red, linewidth=3, style=plot.style_linebr)
plot(bullEngulfing ? bullTP : na, title="Bullish Engulfing TP", color=color.green, linewidth=3, style=plot.style_linebr)
plot(bearEngulfing ? bearTP : na, title="Bearish Engulfing TP", color=color.green, linewidth=3, style=plot.style_linebr)



Más.