Estrategia de negociación piramidal dinámica de supertendencia multiperiodo

ATR ST SL
Fecha de creación: 2025-01-06 17:02:35 Última modificación: 2025-01-06 17:02:35
Copiar: 0 Número de Visitas: 460
1
Seguir
1617
Seguidores

Estrategia de negociación piramidal dinámica de supertendencia multiperiodo

Descripción general

Esta es una estrategia de trading piramidal basada en múltiples indicadores Supertrend. Identifica oportunidades comerciales de alta probabilidad configurando el indicador Supertrend con tres períodos y multiplicadores diferentes. La estrategia adopta un método dinámico de adición de posiciones piramidales, permite hasta tres entradas y combina stop loss dinámico y condiciones de salida flexibles para lograr la maximización de ganancias y el control de riesgos.

Principio de estrategia

La estrategia utiliza el indicador Supertrend con tres configuraciones de parámetros diferentes: rápido, medio y lento. La señal de entrada se basa en la intersección de estos tres indicadores y la dirección de la tendencia, utilizando un estilo de pirámide de tres capas para agregar posiciones: la primera capa ingresa al mercado cuando el indicador rápido está hacia abajo, el indicador medio está hacia arriba y el indicador lento está hacia arriba. El indicador de velocidad media está en baja; el segundo nivel ingresa al mercado cuando el indicador rápido está en alza. Ingrese al mercado a través de un avance cuando el indicador de velocidad media y el indicador de velocidad media se mueven hacia abajo juntos; el tercer nivel ingresa al mercado a través de un avance cuando El mercado alcanza un nuevo máximo. La salida adopta múltiples mecanismos como el stop loss dinámico, el stop loss de precio promedio y la reversión general de la tendencia.

Ventajas estratégicas

  1. El mecanismo de confirmación múltiple mejora la precisión de las transacciones
  2. La piramidización puede aumentar significativamente las ganancias en mercados con tendencia
  3. El mecanismo dinámico de stop loss protege las ganancias y al mismo tiempo otorga a las tendencias un amplio margen para desarrollarse.
  4. Un mecanismo de salida flexible puede hacer frente mejor a diferentes entornos de mercado
  5. Utilice el control de posición porcentual para adaptarse a diferentes tamaños de fondos

Riesgo estratégico

  1. En mercados volátiles pueden producirse señales falsas frecuentes
  2. La piramidización puede llevar a mayores caídas cuando la tendencia se invierte repentinamente
  3. Múltiples indicadores pueden causar retraso en la señal
  4. La optimización de parámetros tiene el riesgo de sobreajuste Se recomienda utilizar una gestión estricta del dinero y realizar pruebas retrospectivas para controlar estos riesgos.

Dirección de optimización de la estrategia

  1. Añadir un mecanismo de filtrado del entorno de mercado para ajustar dinámicamente los parámetros en diferentes entornos de volatilidad
  2. Optimizar el intervalo entre la adición de posiciones y la proporción de asignación de posiciones
  3. Introducir más indicadores técnicos para filtrar señales falsas
  4. Desarrollar mecanismos de parámetros adaptativos para adaptarse a los cambios del mercado.
  5. Mejore el mecanismo de salida, puede considerar agregar objetivos de ganancias y pérdidas de parada de tiempo.

Resumir

Esta estrategia captura oportunidades de tendencia a través de múltiples indicadores de supertendencia y métodos de adición de pirámides, y controla los riesgos con stop-loss dinámicos y mecanismos de salida flexibles. Aunque existen ciertas limitaciones, a través de la optimización continua y un estricto control de riesgos, esta estrategia tiene un buen valor de aplicación práctica.

Código Fuente de la Estrategia
/*backtest
start: 2019-12-23 08:00:00
end: 2025-01-04 08:00:00
period: 1d
basePeriod: 1d
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}]
*/

//@version=6
strategy('4Vietnamese 3x Supertrend', overlay=true, max_bars_back=1000, initial_capital = 10000000000, slippage = 2, commission_type = strategy.commission.percent, commission_value = 0.013, default_qty_type=strategy.percent_of_equity, default_qty_value = 33.33, pyramiding = 3, margin_long = 0, margin_short = 0)

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Inputs

// Supertrend Settings
STATRLENGTH1 = input.int(10, title='Fast Supertrend ATR Length', group='SUPERTREND SETTINGS')
STATRMULT1 = input.float(1, title='Fast Supertrend ATR Multiplier', group='SUPERTREND SETTINGS')
STATRLENGTH2 = input.int(11, title='Medium Supertrend ATR Length', group='SUPERTREND SETTINGS')
STATRMULT2 = input.float(2, title='Medium Supertrend ATR Multiplier', group='SUPERTREND SETTINGS')
STATRLENGTH3 = input.int(12, title='Slow Supertrend ATR Length', group='SUPERTREND SETTINGS')
STATRMULT3 = input.float(3, title='Slow Supertrend ATR Multiplier', group='SUPERTREND SETTINGS')

isUseHighestOf2RedCandleSetup = input.bool(false, group = "Setup Filters")


///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Calculations 
[superTrend1, dir1] = ta.supertrend(STATRMULT1, STATRLENGTH1)
[superTrend2, dir2] = ta.supertrend(STATRMULT2, STATRLENGTH2)
[superTrend3, dir3] = ta.supertrend(STATRMULT3, STATRLENGTH3)

// directionST1 = dir1 == 1 and dir1[1] == 1 ? false : dir1 == -1 and dir1[1] == -1 ? true : false
// directionST2 = dir2 == 1 and dir2[1] == 1 ? false : dir2 == -1 and dir2[1] == -1 ? true : false
// directionST3 = dir3 == 1 and dir3[1] == 1 ? false : dir3 == -1 and dir3[1] == -1 ? true : false


///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Calculate highest from supertrend1 uptrend
var float highestGreen = 0
if dir1 < 0 and highestGreen == 0 and (isUseHighestOf2RedCandleSetup ? close < open : true)
    highestGreen := high
if highestGreen > 0 and (isUseHighestOf2RedCandleSetup ? close < open : true)
    if high > highestGreen
        highestGreen := high
if dir1 >= 0
    highestGreen := 0


///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Entry SL
var entrySL4Long1 = false
var entrySL4Long2 = false
var entrySL4Long3 = false

isUseEntrySL = input.bool(true, group = "Entry SL Option")
dataToCalculate = input.source(low, group = "Entry SL Option")

if isUseEntrySL and (dir1 > 0 and dir2 < 0 and dir3 < 0)
    if strategy.opentrades >= 1
        if dataToCalculate > strategy.opentrades.entry_price(0)
            entrySL4Long1 := true
        else 
            entrySL4Long1 := false

        if entrySL4Long1 and close > strategy.opentrades.entry_price(0)
            strategy.exit('exit1', from_entry = 'long1', stop = strategy.opentrades.entry_price(0))

    if strategy.opentrades >= 2 
        if dataToCalculate > strategy.opentrades.entry_price(1)
            entrySL4Long2 := true
        else 
            entrySL4Long2 := false
    
        if entrySL4Long2 and close > strategy.opentrades.entry_price(1)
            strategy.exit('exit2', from_entry = 'long2', stop = strategy.opentrades.entry_price(1))   

    if strategy.opentrades >= 3 
        if dataToCalculate > strategy.opentrades.entry_price(2) 
            entrySL4Long3 := true
        else 
            entrySL4Long3 := false
    
        if entrySL4Long3 and close >  strategy.opentrades.entry_price(2)
            strategy.exit('exit3', from_entry = 'long3', stop = strategy.opentrades.entry_price(2))

if strategy.closedtrades > strategy.closedtrades[1]
    if strategy.closedtrades.exit_id(strategy.closedtrades-1) == 'exit3'
        entrySL4Long3 := false
    if strategy.closedtrades.exit_id(strategy.closedtrades-1) == 'exit2'
        entrySL4Long2 := false
    if strategy.closedtrades.exit_id(strategy.closedtrades-1) == 'exit1'
        entrySL4Long1 := false

    
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Entry
if dir3 < 0
    if dir2 > 0 and dir1 < 0
        strategy.entry('long1', strategy.long)
    else if dir2 < 0
        strategy.entry('long2', strategy.long, stop=superTrend1)
else
    if dir1 < 0 and highestGreen > 0
        strategy.entry('long3', strategy.long, stop=highestGreen)


///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Exit
isUseAllDowntrendExit = input.bool(true, group = "Exit Type")
if isUseAllDowntrendExit and dir3 > 0 and dir2 > 0 and dir1 > 0 and close < open
    strategy.close_all()

isUseAvgPriceInLoss = input.bool(true, group = "Exit Type")
if isUseAvgPriceInLoss and strategy.position_avg_price > close //and strategy.position_avg_price <= close[1]
    //  and (dir1 > 0 or dir2 > 0 or dir3 > 0)
    //  and strategy.opentrades >= 1  
    //  and strategy.opentrades >= 3  
    strategy.close_all()

isUseAllPositionsInLoss = input.bool(false, group = "Exit Type")
if isUseAllPositionsInLoss
      and (
       false
         or (strategy.opentrades == 1 and ((not na(strategy.opentrades.entry_price(0))) and strategy.opentrades.entry_price(0) > close))

         or (strategy.opentrades == 1 and ((not na(strategy.opentrades.entry_price(0))) and strategy.opentrades.entry_price(0) > close)
             and ((not na(strategy.opentrades.entry_price(1))) and strategy.opentrades.entry_price(1) > close))

         or (strategy.opentrades == 1 and ((not na(strategy.opentrades.entry_price(0))) and strategy.opentrades.entry_price(0) > close)
             and ((not na(strategy.opentrades.entry_price(1))) and strategy.opentrades.entry_price(1) > close)
             and ((not na(strategy.opentrades.entry_price(2))) and strategy.opentrades.entry_price(2) > close))
         )
    strategy.close_all()


///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Plot
plot(superTrend1, title='Fast Supertrend',      color=dir1 == 1 and dir1[1] == 1 ? color.red : dir1 == -1 and dir1[1] == -1 ? color.green : na)
plot(superTrend2, title='Medium Supertrend',    color=dir2 == 1 and dir2[1] == 1 ? color.red : dir2 == -1 and dir2[1] == -1 ? color.green : na)
plot(superTrend3, title='Slow Supertrend',      color=dir3 == 1 and dir3[1] == 1 ? color.red : dir3 == -1 and dir3[1] == -1 ? color.green : na)