Estratégia de negociação de ruptura de momento

Autora:ChaoZhang, Data: 2023-12-19 15:46:38
Tags:

img

Resumo

A Estratégia de Negociação de Breakout de Momento é uma estratégia de tendência que gera sinais de negociação detectando breakouts de preços além dos principais níveis de suporte / resistência.

Estratégia lógica

O indicador central desta estratégia é o canal de Donchian. O canal de Donchian consiste no preço mais alto, preço mais baixo e preço da linha média durante um período definido. A faixa superior e inferior do canal conectam os preços mais altos e mais baixos de acordo durante o período de retrospectiva. Um sinal longo é gerado quando o preço quebra acima da faixa superior, enquanto um sinal curto é gerado em uma quebra abaixo da faixa inferior, refletindo mudanças no impulso do mercado.

A média móvel é usada para medir a direção da tendência.

Especificamente, a condição de entrada consiste em: O preço rompe acima da faixa superior do Canal de Donchian E fecha acima da média móvel. A condição de saída é: O preço rompe abaixo da faixa inferior do Canal de Donchian.

O stop loss segue a faixa inferior do canal de Donchian, garantindo que o stop se ajuste mais alto junto com a tendência.

Análise das vantagens

Esta estratégia combina efetivamente dois indicadores para julgar a direção da tendência e o momento, evitando negócios errôneos de falsos sinais de ruptura.

Especificamente, as vantagens são:

  1. O canal de Donchian determina dinamicamente os principais níveis de suporte/resistência, identificando pontos de virada da tendência.

  2. A média móvel filtra as consolidações, evitando problemas desnecessários.

  3. Seguir a faixa inferior do Canal de Donchian permite maximizar os lucros.

  4. Os parâmetros razoáveis proporcionam flexibilidade em vários ambientes de mercado.

Análise de riscos

Os principais riscos enfrentados:

  1. Risco de ruptura fracassada - O preço não consegue manter o ímpeto após a ruptura acima da faixa superior.

  2. Risco de reversão da tendência - O preço reverte-se antes de atingir o stop loss final.

  3. Risco de otimização de parâmetros - Parâmetros ineficazes levam a excesso de negociação ou sinais insuficientes.

Para mitigar, fatores como confirmação de volume, ajuste da média móvel, distâncias razoáveis de parada devem ser incorporados.

Oportunidades de melhoria

Outras optimizações:

  1. Adicione o filtro de volume para garantir grandes breakouts de impulso.

  2. Otimizar os períodos de média móvel para as características dos instrumentos.

  3. Mecanismo adaptativo de stop loss baseado na dinâmica da volatilidade dos preços.

  4. Mecanismo de reentrada após a parada inicial para capturar movimentos adicionais de retomada da tendência.

  5. Testes robustos em vários mercados para identificar parâmetros por nuances do produto.

Conclusão

A estratégia de negociação de breakout de momento combina indicadores para medir efetivamente a tendência e a força do momento, evitando os problemas comuns enfrentados pelos sistemas de tendência em relação a entradas cegas.


/*backtest
start: 2022-12-12 00:00:00
end: 2023-12-18 00:00:00
period: 1d
basePeriod: 1h
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}]
*/

//@version=4

// Revision:        1
// Author:          @millerrh
// Strategy:  
//      Entry: Buy when Donchian Channel breaks out
//      Exit: Trail a stop with the lower Donchian Channel band
// Conditions/Variables:
//    1. Can add a filter to only take setups that are above a user-defined moving average (helps avoid trading counter trend) 
//    2. Manually configure which dates to back test
//    3. User-Configurable DC Channel length


// === CALL STRATEGY/STUDY, PROGRAMATICALLY ENTER STRATEGY PARAMETERS HERE SO YOU DON'T HAVE TO CHANGE THEM EVERY TIME YOU RUN A TEST ===
// (STRATEGY ONLY) - Comment out srategy() when in a study() 
strategy("Donchian Breakout", overlay=true, initial_capital=10000, currency='USD', 
   default_qty_type=strategy.percent_of_equity, default_qty_value=100, commission_type=strategy.commission.percent, commission_value=0.1)
// (STUDY ONLY) - Comment out study() when in a strategy() 
//study("Donchian Breakout", overlay=true)


// === BACKTEST RANGE ===
From_Year  = input(defval = 2019, title = "From Year")
From_Month = input(defval = 1, title = "From Month", minval = 1, maxval = 12)
From_Day   = input(defval = 1, title = "From Day", minval = 1, maxval = 31)
To_Year    = input(defval = 9999, title = "To Year")
To_Month   = input(defval = 1, title = "To Month", minval = 1, maxval = 12)
To_Day     = input(defval = 1, title = "To Day", minval = 1, maxval = 31)
Start  = timestamp(From_Year, From_Month, From_Day, 00, 00)  // backtest start window
Finish = timestamp(To_Year, To_Month, To_Day, 23, 59)        // backtest finish window

// == INPUTS ==
trigInput = input(title = "Execute Trades On...", defval = "Wick", options=["Wick","Close"]) // Useful for comparing standing stop orders vs. waiting for candle closes prior to action
stopTrail = input(title = "Trail Stops On...", defval = "ATR", options = ["ATR","Bottom of DC Channel","Midline of DC Channel","Tightest of ATR/Bot DC Channel"])
dcPeriod = input(title="DC period", type=input.integer, defval=20)

// === PLOT THE DONCHIAN CHANNEL ===
// Logic
dcUpper = highest(high, dcPeriod)
dcLower = lowest(low, dcPeriod)
dcMid = avg(dcUpper, dcLower)

// Plotting
dcUplot = plot(dcUpper, color=color.blue, linewidth=1, title="Upper Channel Line")
dcLplot = plot(dcLower, color=color.blue, linewidth=1, title="Lower Channel Line")
dcMidPlot = plot(dcMid, color=color.gray, linewidth=1, title="Mid-Line Average")
fill(dcUplot, dcLplot, color=color.gray, transp=90)

// == FILTERING ==
// Inputs
useMaFilter = input(title = "Use MA for Filtering?", type = input.bool, defval = true)
maType = input(defval="SMA", options=["EMA", "SMA"], title = "MA Type For Filtering")
maLength   = input(defval = 100, title = "MA Period for Filtering", minval = 1)

// Declare function to be able to swap out EMA/SMA
ma(maType, src, length) =>
    maType == "EMA" ? ema(src, length) : sma(src, length) //Ternary Operator (if maType equals EMA, then do ema calc, else do sma calc)
maFilter = ma(maType, close, maLength)
plot(maFilter, title = "Trend Filter MA", color = color.green, linewidth = 3, style = plot.style_line, transp = 50)

// Check to see if the useMaFilter check box is checked, this then inputs this conditional "maFilterCheck" variable into the strategy entry 
maFilterCheck = if useMaFilter == true
    maFilter
else
    0

// == ENTRY AND EXIT CRITERIA ==
// Trigger stop based on candle close or High/Low (i.e. Wick) - If doing daily timeframe, can do candle close.  Intraday should use wick.
trigResistance = trigInput == "Close" ? close : trigInput == "Wick" ? high : na
trigSupport = trigInput == "Close" ? close : trigInput == "Wick" ? low : na
buySignal = trigResistance >= dcUpper[1] // The [1] looks at the previous bar's value as it didn't seem to be triggering correctly without it (likely) DC moves with each bar
sellSignal = trigSupport <= dcLower[1]

buy = buySignal and dcUpper[1] > maFilterCheck // All these conditions need to be met to buy


// (STRATEGY ONLY) Comment out for Study
// This string of code enters and exits at the close
if (trigInput == "Close")
    strategy.entry("Long", strategy.long, when = buy)
    strategy.close("Long", when = sellSignal)

// This string of code enters and exits at the wick (i.e. with pre-set stops)
if (trigInput == "Wick")
    strategy.entry("Long", strategy.long, stop = dcUpper[1], when = time > Start and time < Finish and dcUpper[1] > maFilterCheck)
    strategy.exit("Exit Long", from_entry = "Long", stop = dcLower[1])





Mais.