Estrategia dinámica de suspensión de pérdidas de bandas de Bollinger

El autor:¿ Qué pasa?, Fecha: 2024-02-01 10:48:52
Las etiquetas:

img

Resumen general

Esta estrategia utiliza los rieles superior e inferior de las bandas de Bollinger para implementar un stop loss dinámico. Se corta cuando el precio rompe el rieles superior y se hace largo cuando el precio rompe el rieles inferior. Y establece un stop loss dinámico para rastrear el movimiento del precio.

Principio

El núcleo de esta estrategia se encuentra en los rieles superior e inferior de las bandas de Bollinger. El rieles medio es el promedio móvil de n días. El rieles superior es el rieles medio + kDesviación estándar de n días. El carril inferior es el carril medio − kCuando el precio rebota desde el rieles inferior, ir largo. Cuando el precio cae de nuevo desde el rieles superior, ir corto. Al mismo tiempo, la estrategia establece un punto de stop loss y se ajusta dinámicamente durante el movimiento del precio para establecer un punto de toma de beneficios para implementar un control de riesgo prudente.

Ventajas

  1. Utilice las bandas de Bollinger de fuerte regresión a la característica del tren medio para capturar las tendencias a medio y largo plazo;
  2. señales largas y cortas claras, fáciles de operar;
  3. Establecer un stop loss dinámico para maximizar el bloqueo de ganancias y controlar los riesgos;
  4. Parámetros ajustables para adaptarse a las diferentes condiciones del mercado.

Riesgos y soluciones

  1. Las bandas de Bollinger pueden generar múltiples señales largas y cortas durante los mercados de rango, causando que los usuarios se queden atrapados en whipssaws.
  2. La solución es optimizar razonablemente los parámetros para diferentes productos.

Direcciones de optimización

  1. Optimizar los parámetros de las medias móviles para adaptarlos a las características del producto;
  2. Añadir un filtro de tendencia para evitar el mercado limitado por el rango;
  3. Combinar con otros indicadores como condiciones de filtrado para mejorar la estabilidad de la estrategia.

Conclusión

Esta estrategia utiliza los atributos de regresión de Bollinger Bands junto con el stop loss dinámico para obtener ganancias de tendencia a medio y largo plazo mientras controla los riesgos. Es una estrategia cuantitativa altamente adaptable y estable. A través de la optimización de parámetros y la optimización lógica, se puede adaptar a más productos y obtener ganancias constantes en el comercio en vivo.


/*backtest
start: 2024-01-24 00:00:00
end: 2024-01-31 00:00:00
period: 30m
basePeriod: 15m
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}]
*/

//@version=5
strategy(shorttitle="BB Strategy", title="Bollinger Bands Strategy", overlay=true)
length = input.int(20, minval=1, group = "Bollinger Bands")
maType = input.string("SMA", "Basis MA Type", options = ["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"], group = "Bollinger Bands")
src = input(close, title="Source", group = "Bollinger Bands")
mult = input.float(2.0, minval=0.001, maxval=50, title="StdDev", group = "Bollinger Bands")

ma(source, length, _type) =>
    switch _type
        "SMA" => ta.sma(source, length)
        "EMA" => ta.ema(source, length)
        "SMMA (RMA)" => ta.rma(source, length)
        "WMA" => ta.wma(source, length)
        "VWMA" => ta.vwma(source, length)

basis = ma(src, length, maType)
dev = mult * ta.stdev(src, length)
upper = basis + dev
lower = basis - dev
offset = input.int(0, "Offset", minval = -500, maxval = 500, group = "Bollinger Bands")
plot(basis, "Basis", color=#FF6D00, offset = offset)
p1 = plot(upper, "Upper", color=#2962FF, offset = offset)
p2 = plot(lower, "Lower", color=#2962FF, offset = offset)
fill(p1, p2, title = "Background", color=color.rgb(33, 150, 243, 95))

lo = input.bool(true, "Long", group = "Strategy")
sh = input.bool(true, "Short", group = "Strategy")
x = input.float(3.0, "Target Multiplier (X)", group = "Strategy", minval = 1.0, step = 0.1)
token = input.string(defval = "", title = "Token", group = "AUTOMATION")
Buy_CE = '{"auth-token":"' + token + '","key":"Value1","value":"' + str.tostring(1) + '"}'
Buy_PE = '{"auth-token":"' + token + '","key":"Value1","value":"' + str.tostring(2) + '"}'
Exit_CE = '{"auth-token":"' + token + '","key":"Value1","value":"' + str.tostring(-1) + '"}'
Exit_PE = '{"auth-token":"' + token + '","key":"Value1","value":"' + str.tostring(-2) + '"}'
Exit_PE_CE = '{"auth-token":"' + token + '","key":"Value1","value":"' + str.tostring(2.5) + '"}'
Exit_CE_PE = '{"auth-token":"' + token + '","key":"Value1","value":"' + str.tostring(1.5) + '"}'
long = high < lower
short = low > upper
var sl_b = 0.0
var tar_b = 0.0
var sl_s = 0.0
var tar_s = 0.0
var static_sl = 0.0
entry = strategy.opentrades.entry_price(strategy.opentrades - 1)
if long and lo and strategy.position_size == 0
    strategy.entry("Long", strategy.long, alert_message = Buy_CE, stop = high)
    strategy.exit("LX", "Long", profit = (math.abs(high - low) * x)/syminfo.mintick, stop = low, alert_message = Exit_CE)
    sl_b := low
    tar_b := high + (math.abs(high - low) * x)
    static_sl := math.abs(low - high)
if short and sh and strategy.position_size == 0
    strategy.entry("Short", strategy.short, alert_message = Buy_PE, stop = low)
    strategy.exit("SX", "Short", profit = (math.abs(high - low) * x)/syminfo.mintick, stop = high, alert_message = Exit_PE)
    sl_s := high
    tar_s := low - (math.abs(high - low) * x)
    static_sl := math.abs(high - low)
// if long and strategy.position_size < 0
//     strategy.entry("Long", strategy.long, alert_message = Exit_PE_CE, stop = high)
//     strategy.exit("LX", "Long", profit = (math.abs(high - low) * x)/syminfo.mintick, stop = low, alert_message = Exit_CE)
//     sl_b := low
//     tar_b := high + (math.abs(high - low) * x)
// if short and strategy.position_size > 0
//     strategy.entry("Short", strategy.short, alert_message = Exit_CE_PE, stop = low)
//     strategy.exit("SX", "Short", profit = (math.abs(high - low) * x)/syminfo.mintick, stop = high, alert_message = Exit_PE)
//     sl_s := math.max(high[1], high)
//     tar_s := low - (math.abs(high - low) * x)
if ta.change(dayofmonth) or (long[1] and not long[2])
    strategy.cancel("Long")
if ta.change(dayofmonth) or (short[1] and not short[2])
    strategy.cancel("Short")
var count = 1
if strategy.position_size != 0
    if strategy.position_size > 0
        if close > (entry + (static_sl * count))
            strategy.exit("LX", "Long", limit = tar_b, stop = sl_b, alert_message = Exit_CE)
            sl_b := entry + (static_sl * (count - 1))
            count += 1
            
    else
        if close < (entry - (static_sl * count))
            strategy.exit("SX", "Short", limit = tar_s, stop = sl_s, alert_message = Exit_PE)
            sl_s := entry - (static_sl * (count - 1))
            count += 1
// label.new(bar_index, high, str.tostring(static_sl))
if strategy.position_size == 0
    count := 1
plot(strategy.position_size > 0 ? sl_b : na, "", color.red, style = plot.style_linebr)
plot(strategy.position_size < 0 ? sl_s : na, "", color.red, style = plot.style_linebr)
plot(strategy.position_size > 0 ? tar_b : na, "", color.green, style = plot.style_linebr)
plot(strategy.position_size < 0 ? tar_s : na, "", color.green, style = plot.style_linebr)

Más.