Estrategia de supertendencia dinámica adaptativa de volatilidad de múltiples pasos

ATR SMA STD TP
Fecha de creación: 2024-11-29 16:57:19 Última modificación: 2024-11-29 16:57:19
Copiar: 0 Número de Visitas: 439
1
Seguir
1617
Seguidores

Estrategia de supertendencia dinámica adaptativa de volatilidad de múltiples pasos

Descripción general

La estrategia de supertrend de fluctuación automática en múltiples pasos es un sistema de negociación innovador que combina el canal de Vegas y los indicadores de SuperTrend. La estrategia se caracteriza por su capacidad para adaptarse dinámicamente a la volatilidad del mercado y por la adopción de un mecanismo de paradas en varios pasos para optimizar la relación riesgo-beneficio. La estrategia combina el análisis de la volatilidad del canal de Vegas con la función de seguimiento de tendencias de SuperTrend para ajustar automáticamente sus parámetros cuando cambian las condiciones del mercado, lo que proporciona una señal de negociación más precisa.

Principio de estrategia

La estrategia funciona en base a tres componentes centrales: cálculo de la vía de Vegas, detección de tendencias y mecanismo de paradas en varios pasos. La vía de Vegas utiliza un promedio móvil simple (SMA) y un diferencial estándar (STD) para definir el rango de fluctuación de los precios. El indicador SuperTrend determina la dirección de la tendencia en función de los valores de ATR ajustados.

Ventajas estratégicas

  1. Adaptabilidad dinámica: La estrategia puede adaptarse automáticamente a las diferentes condiciones del mercado mediante el ajuste de los factores de volatilidad.
  2. Gestión de riesgos: El mecanismo de detención de múltiples pasos ofrece una solución sistematizada y rentable.
  3. Personalización: ofrece varias opciones de configuración de parámetros para satisfacer diferentes estilos de negociación.
  4. La cobertura completa del mercado: soporte para el comercio de dos vías en múltiples espacios.
  5. Comentarios visuales: Proporciona una interfaz gráfica clara para facilitar el análisis y la toma de decisiones.

Riesgo estratégico

  1. Sensibilidad de parámetros: Diferentes combinaciones de parámetros pueden causar una gran diferencia en el rendimiento de la estrategia.
  2. Retraso: Hay un cierto retraso en los indicadores basados en promedios móviles.
  3. Riesgo de brecha falsa: puede generar señales erróneas en el mercado horizontal.
  4. El equilibrio de la parada: la parada prematura puede perder la tendencia, y la parada tardía puede perder la ganancia.

Dirección de optimización de la estrategia

  1. Introducción de filtros de entornos de mercado para ajustar los parámetros de la estrategia en diferentes condiciones de mercado.
  2. El objetivo es aumentar el análisis de tráfico y mejorar la fiabilidad de la señal.
  3. Desarrollar mecanismos de amortiguación adaptativos para ajustar el nivel de amortiguación en función de la dinámica de las fluctuaciones del mercado.
  4. Integración con otros indicadores técnicos para la confirmación de señales.
  5. Implementar gestión dinámica de posiciones, ajustando el tamaño de las transacciones según el riesgo del mercado.

Resumir

La estrategia de supertrend dinámica de adaptación a la volatilidad en varios pasos representa un método de negociación cuantitativa avanzado que ofrece a los operadores un sistema de negociación integral mediante la combinación de varios indicadores técnicos y un mecanismo de frenado innovador. Su adaptabilidad dinámica y sus funciones de gestión de riesgos lo hacen especialmente adecuado para operar en diferentes entornos de mercado, y tiene una buena escalabilidad y espacio de optimización.

Código Fuente de la Estrategia
/*backtest
start: 2024-10-01 00:00:00
end: 2024-10-31 23:59:59
period: 1h
basePeriod: 1h
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}]
*/

//@version=5
strategy("Multi-Step Vegas SuperTrend - strategy [presentTrading]", shorttitle="Multi-Step Vegas SuperTrend - strategy [presentTrading]", overlay=true, precision=3, commission_value=0.1, commission_type=strategy.commission.percent, slippage=1, currency=currency.USD)

// Input settings allow the user to customize the strategy's parameters.
tradeDirectionChoice = input.string(title="Trade Direction", defval="Both", options=["Long", "Short", "Both"]) // Option to select the trading direction
atrPeriod = input(10, "ATR Period for SuperTrend") // Length of the ATR for volatility measurement
vegasWindow = input(100, "Vegas Window Length") // Length of the moving average for the Vegas Channel
superTrendMultiplier = input(5, "SuperTrend Multiplier Base") // Base multiplier for the SuperTrend calculation
volatilityAdjustment = input.float(5, "Volatility Adjustment Factor") // Factor to adjust the SuperTrend sensitivity to the Vegas Channel width

// User inputs for take profit settings
useTakeProfit = input.bool(true, title="Use Take Profit", group="Take Profit Settings")
takeProfitPercent1 = input.float(3.0, title="Take Profit % Step 1", group="Take Profit Settings")
takeProfitPercent2 = input.float(6.0, title="Take Profit % Step 2", group="Take Profit Settings")
takeProfitPercent3 = input.float(12.0, title="Take Profit % Step 3", group="Take Profit Settings")
takeProfitPercent4 = input.float(21.0, title="Take Profit % Step 4", group="Take Profit Settings")

takeProfitAmount1 = input.float(25, title="Take Profit Amount % Step 1", group="Take Profit Settings")
takeProfitAmount2 = input.float(20, title="Take Profit Amount % Step 2", group="Take Profit Settings")
takeProfitAmount3 = input.float(10, title="Take Profit Amount % Step 3", group="Take Profit Settings")
takeProfitAmount4 = input.float(15, title="Take Profit Amount % Step 4", group="Take Profit Settings")

numberOfSteps = input.int(4, title="Number of Take Profit Steps", minval=1, maxval=4, group="Take Profit Settings")

// Calculate the Vegas Channel using a simple moving average and standard deviation.
vegasMovingAverage = ta.sma(close, vegasWindow)
vegasChannelStdDev = ta.stdev(close, vegasWindow)
vegasChannelUpper = vegasMovingAverage + vegasChannelStdDev
vegasChannelLower = vegasMovingAverage - vegasChannelStdDev

// Adjust the SuperTrend multiplier based on the width of the Vegas Channel.
channelVolatilityWidth = vegasChannelUpper - vegasChannelLower
adjustedMultiplier = superTrendMultiplier + volatilityAdjustment * (channelVolatilityWidth / vegasMovingAverage)

// Calculate the SuperTrend indicator values.
averageTrueRange = ta.atr(atrPeriod)
superTrendUpper = hlc3 - (adjustedMultiplier * averageTrueRange)
superTrendLower = hlc3 + (adjustedMultiplier * averageTrueRange)
var float superTrendPrevUpper = na
var float superTrendPrevLower = na
var int marketTrend = 1

// Update SuperTrend values and determine the current trend direction.
superTrendPrevUpper := nz(superTrendPrevUpper[1], superTrendUpper)
superTrendPrevLower := nz(superTrendPrevLower[1], superTrendLower)
marketTrend := close > superTrendPrevLower ? 1 : close < superTrendPrevUpper ? -1 : nz(marketTrend[1], 1)
superTrendUpper := marketTrend == 1 ? math.max(superTrendUpper, superTrendPrevUpper) : superTrendUpper
superTrendLower := marketTrend == -1 ? math.min(superTrendLower, superTrendPrevLower) : superTrendLower
superTrendPrevUpper := superTrendUpper
superTrendPrevLower := superTrendLower

// Enhanced Visualization
// Plot the SuperTrend and Vegas Channel for visual analysis.
plot(marketTrend == 1 ? superTrendUpper : na, "SuperTrend Upper", color=color.green, linewidth=2)
plot(marketTrend == -1 ? superTrendLower : na, "SuperTrend Lower", color=color.red, linewidth=2)
plot(vegasChannelUpper, "Vegas Upper", color=color.purple, linewidth=1)
plot(vegasChannelLower, "Vegas Lower", color=color.purple, linewidth=1)

// Apply a color to the price bars based on the current market trend.
barcolor(marketTrend == 1 ? color.green : marketTrend == -1 ? color.red : na)

// Detect trend direction changes and plot entry/exit signals.
trendShiftToBullish = marketTrend == 1 and marketTrend[1] == -1
trendShiftToBearish = marketTrend == -1 and marketTrend[1] == 1

plotshape(series=trendShiftToBullish, title="Enter Long", location=location.belowbar, color=color.green, style=shape.labelup, text="Buy")
plotshape(series=trendShiftToBearish, title="Enter Short", location=location.abovebar, color=color.red, style=shape.labeldown, text="Sell")

// Define conditions for entering long or short positions, and execute trades based on these conditions.
enterLongCondition = marketTrend == 1
enterShortCondition = marketTrend == -1

// Check trade direction choice before executing trade entries.
if enterLongCondition and (tradeDirectionChoice == "Long" or tradeDirectionChoice == "Both")
    strategy.entry("Long Position", strategy.long)

if enterShortCondition and (tradeDirectionChoice == "Short" or tradeDirectionChoice == "Both")
    strategy.entry("Short Position", strategy.short)

// Close all positions when the market trend changes.
if marketTrend != marketTrend[1]
    strategy.close_all()

// Multi-Stage Take Profit Logic
if (strategy.position_size > 0)
    entryPrice = strategy.opentrades.entry_price(strategy.opentrades - 1)
    if numberOfSteps >= 1
        strategy.exit("Take Profit 1", from_entry="Long Position", qty_percent=takeProfitAmount1, limit=entryPrice * (1 + takeProfitPercent1 / 100))
    if numberOfSteps >= 2
        strategy.exit("Take Profit 2", from_entry="Long Position", qty_percent=takeProfitAmount2, limit=entryPrice * (1 + takeProfitPercent2 / 100))
    if numberOfSteps >= 3
        strategy.exit("Take Profit 3", from_entry="Long Position", qty_percent=takeProfitAmount3, limit=entryPrice * (1 + takeProfitPercent3 / 100))
    if numberOfSteps >= 4
        strategy.exit("Take Profit 4", from_entry="Long Position", qty_percent=takeProfitAmount4, limit=entryPrice * (1 + takeProfitPercent4 / 100))

if (strategy.position_size < 0)
    entryPrice = strategy.opentrades.entry_price(strategy.opentrades - 1)
    if numberOfSteps >= 1
        strategy.exit("Take Profit 1", from_entry="Short Position", qty_percent=takeProfitAmount1, limit=entryPrice * (1 - takeProfitPercent1 / 100))
    if numberOfSteps >= 2
        strategy.exit("Take Profit 2", from_entry="Short Position", qty_percent=takeProfitAmount2, limit=entryPrice * (1 - takeProfitPercent2 / 100))
    if numberOfSteps >= 3
        strategy.exit("Take Profit 3", from_entry="Short Position", qty_percent=takeProfitAmount3, limit=entryPrice * (1 - takeProfitPercent3 / 100))
    if numberOfSteps >= 4
        strategy.exit("Take Profit 4", from_entry="Short Position", qty_percent=takeProfitAmount4, limit=entryPrice * (1 - takeProfitPercent4 / 100))