Estratégia de impulso de cruzamento de média móvel dupla

Autora:ChaoZhang, Data: 2023-11-16 17:25:13
Tags:

img

Resumo

Esta estratégia utiliza o princípio duplo de cruzamento de médias móveis, combina o indicador MACD para julgamento de tendências e realce de fundo cruzado e confirma entradas com pontos de padrão, com o objetivo de capturar tendências de médio prazo no mercado.

Estratégia lógica

A estratégia constrói médias móveis duplas usando EMA rápida e EMA lenta, e determina a direção da tendência com base no cruzamento entre as linhas rápidas e lentas.

De acordo com o código, o comprimento da linha rápida é de 12 e o comprimento da linha lenta é de 26, representando tendências de curto e longo prazo.

Lógica cruzada:

  • tendência_up = macd > sinal: linha rápida cruza a linha lenta, indicando tendência de alta a curto prazo

  • tendência_dn = macd < sinal: linha rápida cruza abaixo da linha lenta, indicando tendência de baixa a curto prazo

Detecção de pontos de cruzamento:

  • cross_UP = sinal[1] >= macd[1] e sinal < macd: linha rápida cruza linha lenta de baixo

  • cross_DN = sinal [1] <= macd [1] e sinal > macd: linha rápida cruza linha lenta de cima

A mudança de cor do histograma determina a força do momento:

  • histA_IsUp = coluna do histograma crescente e superior a 0, fortalecimento do ímpeto na tendência de alta

  • histA_IsDown = coluna do histograma em declínio, mas ainda superior a 0, dinâmica de enfraquecimento na tendência de alta

  • A mesma lógica abaixo de 0

Vantagens

  1. As médias móveis duplas determinam a tendência a médio prazo, evitando o ruído a curto prazo

  2. O MACD ajuda a avaliar as tendências e o ímpeto de curto prazo para uma maior rentabilidade

  3. A mudança de cor do histograma ajuda a identificar melhor o momento da entrada

  4. Cor de fundo cruzada destaca sinais

  5. Períodos de média móvel personalizáveis adequados a diferentes ambientes de mercado

  6. Parâmetros MACD ajustáveis otimizam o indicador

  7. Fornece várias confirmações de entrada: tendência, cruzamento, ruptura de padrão

Riscos

  1. As MAs duplas são insensíveis às flutuações de curto prazo, podendo perder oportunidades de curto prazo

  2. Efeito MACD fraco com configurações de parâmetros inadequadas, pode gerar sinais falsos

  3. As entradas baseadas unicamente nos indicadores de crescimento e no MACD apresentam alguns pontos cegos

  4. Não existindo um mecanismo de stop loss, resulta no risco de expansão das perdas

  5. Falta de uma gestão rigorosa do dinheiro e de uma dimensão das posições

Possíveis soluções:

  1. Combinar outros indicadores para definir os intervalos de variação a curto prazo e controlar o risco

  2. Otimizar os parâmetros do MACD e testar em diferentes mercados

  3. Adicionar padrão, impulso, etc. para confirmar sinais

  4. Estabelecer mecanismos de stop loss para limitar o tamanho das perdas

  5. Adicionar módulo de gestão de fundos ao tamanho das posições com base no capital

Orientações de otimização

  1. Teste e otimize as combinações de parâmetros de MA para uma maior adaptabilidade do mercado

  2. Tente diferentes tipos de MA como VWAP, Bollinger midline etc.

  3. Considerar o volume de negociação para evitar falsos breakouts

  4. Incorporar RSI etc. para confirmar sobrecompra/supervenda

  5. Construir mecanismos robustos de stop loss como trailing stop, volatility stop etc.

  6. Incorporar o dimensionamento das posições com base no tamanho da conta

  7. Considere o aprendizado de máquina para otimização de parâmetros

  8. Expandir o universo estratégico para uma abordagem de carteira reforçada

Conclusão

Esta estratégia integra a filtragem de tendência de média móvel dupla e o impulso do MACD, adiciona características de padrão, construindo um sistema de negociação de médio prazo relativamente estável. A principal vantagem reside em capturar a tendência principal, evitando o ruído de curto prazo. Mas também há áreas que poderiam ser melhoradas, como adicionar mecanismos de stop loss e gerenciamento de risco.


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

//@version=5
strategy(title="Histogram MacD MVP_V2.1", shorttitle="Histogram MacD MVP_2.1")
//Plot Inputs
res           = input.timeframe("",  "Indicator TimeFrame")
fast_length   = input.int(title="Fast Length", defval=12)
slow_length   = input.int(title="Slow Length", defval=26)
src           = input.source(title="Source", defval=close)
signal_length = input.int(title="Signal Smoothing", minval = 1, maxval = 999, defval = 9)
sma_source    = input.string(title="Oscillator MA Type", defval="EMA", options=["SMA", "EMA"])
sma_signal    = input.string(title="Signal Line MA Type", defval="EMA", options=["SMA", "EMA"])
// Show Plots T/F
show_macd     = input.bool(true, title="Show MACD Lines", group="Show Plots?", inline="SP10")
show_macd_LW  = input.int(3, minval=0, maxval=5, title = "MACD Width", group="Show Plots?", inline="SP11")
show_signal_LW= input.int(2, minval=0, maxval=5, title = "Signal Width", group="Show Plots?", inline="SP11")
show_Hist     = input.bool(true, title="Show Histogram", group="Show Plots?", inline="SP20")
show_hist_LW  = input.int(5, minval=0, maxval=5, title = "-- Width", group="Show Plots?", inline="SP20")
show_trend    = input.bool(true, title = "Show MACD Lines w/ Trend Color", group="Show Plots?", inline="SP30")
show_HB       = input.bool(false, title="Show Highlight Price Bars", group="Show Plots?", inline="SP40")
show_cross    = input.bool(false, title = "Show BackGround on Cross", group="Show Plots?", inline="SP50")
show_dots     = input.bool(true, title = "Show Circle on Cross", group="Show Plots?", inline="SP60")
show_dots_LW  = input.int(5, minval=0, maxval=5, title = "-- Width", group="Show Plots?", inline="SP60")

//show_trend    = input(true, title = "Colors MACD Lines w/ Trend Color", group="Show Plots?", inline="SP5")
// MACD Lines colors
col_macd      = input.color(#FF6D00, "MACD Line  ",  group="Color Settings", inline="CS1")
col_signal    = input.color(#2962FF, "Signal Line  ",  group="Color Settings", inline="CS1")
col_trnd_Up   = input.color(#4BAF4F, "Trend Up      ",  group="Color Settings", inline="CS2")
col_trnd_Dn   = input.color(#B71D1C, "Trend Down    ",  group="Color Settings", inline="CS2")
// Histogram Colors
col_grow_above = input.color(#26A69A, "Above   Grow",  group="Histogram Colors", inline="Hist10")
col_fall_above = input.color(#FF5252, "Fall",  group="Histogram Colors", inline="Hist10")
col_grow_below = input.color(#FF5252, "Below Grow",  group="Histogram Colors", inline="Hist20")
col_fall_below = input.color(#f8f524, "Fall",  group="Histogram Colors", inline="Hist20")
// Alerts T/F Inputs
alert_Long    = input.bool(true, title = "MACD Cross Up", group = "Alerts", inline="Alert10")
alert_Short   = input.bool(true, title = "MACD Cross Dn", group = "Alerts", inline="Alert10")
alert_Long_A  = input.bool(false, title = "MACD Cross Up & > 0", group = "Alerts", inline="Alert20")
alert_Short_B = input.bool(false, title = "MACD Cross Dn & < 0", group = "Alerts", inline="Alert20")
// Calculating
fast_ma = request.security(syminfo.tickerid, res, sma_source == "SMA" ? ta.sma(src, fast_length) : ta.ema(src, fast_length))
slow_ma = request.security(syminfo.tickerid, res, sma_source == "SMA" ? ta.sma(src, slow_length) : ta.ema(src, slow_length))
macd = fast_ma - slow_ma
signal = request.security(syminfo.tickerid, res, sma_signal == "SMA" ? ta.sma(macd, signal_length) : ta.ema(macd, signal_length))
hist = macd - signal
// MACD Trend and Cross Up/Down conditions
trend_up   = macd > signal
trend_dn   = macd < signal
cross_UP   = signal[1] >= macd[1] and signal < macd
cross_DN   = signal[1] <= macd[1] and signal > macd
cross_UP_A = (signal[1] >= macd[1] and signal < macd) and macd > 0
cross_DN_B = (signal[1] <= macd[1] and signal > macd) and macd < 0
// Condition that changes Color of MACD Line if Show Trend is turned on..
trend_col = show_trend  and trend_up ? col_trnd_Up : trend_up ? col_macd : show_trend  and trend_dn ? col_trnd_Dn: trend_dn ? col_macd : na 

//Var Statements for Histogram Color Change
var bool histA_IsUp = false
var bool histA_IsDown = false
var bool histB_IsDown = false
var bool histB_IsUp = false
histA_IsUp   := hist == hist[1] ? histA_IsUp[1] : hist > hist[1] and hist > 0
histA_IsDown := hist == hist[1] ? histA_IsDown[1] : hist < hist[1] and hist > 0
histB_IsDown := hist == hist[1] ? histB_IsDown[1] : hist < hist[1] and hist <= 0
histB_IsUp   := hist == hist[1] ? histB_IsUp[1] : hist > hist[1] and hist <= 0

hist_col =  histA_IsUp ? col_grow_above : histA_IsDown ? col_fall_above : histB_IsDown ? col_grow_below : histB_IsUp ? col_fall_below :color.silver 

// Plot Statements
//Background Color
bgcolor(show_cross and cross_UP ? col_trnd_Up : na, editable=false)
bgcolor(show_cross and cross_DN ? col_trnd_Dn : na, editable=false)
//Highlight Price Bars
barcolor(show_HB and trend_up ? col_trnd_Up : na, title="Trend Up", offset = 0, editable=false)
barcolor(show_HB and trend_dn ? col_trnd_Dn : na, title="Trend Dn", offset = 0, editable=false)
//Regular Plots
plot(show_Hist and hist ? hist : na, title="Histogram", style=plot.style_columns, color=color.new(hist_col ,0),linewidth=show_hist_LW)
plot(show_macd  and signal ? signal : na, title="Signal", color=color.new(col_signal, 0),  style=plot.style_line ,linewidth=show_signal_LW)
plot(show_macd  and macd ? macd : na, title="MACD", color=color.new(trend_col, 0),  style=plot.style_line ,linewidth=show_macd_LW)
hline(0, title="0 Line", color=color.new(color.gray, 0), linestyle=hline.style_dashed, linewidth=1, editable=false)
plot(show_dots and cross_UP ? macd : na, title="Dots", color=color.new(trend_col ,0), style=plot.style_circles, linewidth=show_dots_LW, editable=false)
plot(show_dots and cross_DN ? macd : na, title="Dots", color=color.new(trend_col ,0), style=plot.style_circles, linewidth=show_dots_LW, editable=false)

//Alerts
if alert_Long and cross_UP
    alert("Symbol = (" + syminfo.tickerid + ") TimeFrame = (" + timeframe.period + ") Current Price (" + str.tostring(close) + ") MACD Crosses Up.", alert.freq_once_per_bar_close)

if alert_Short and cross_DN
    alert("Symbol = (" + syminfo.tickerid + ") TimeFrame = (" + timeframe.period + ") Current Price (" + str.tostring(close) + ") MACD Crosses Down.", alert.freq_once_per_bar_close)
//Alerts - Stricter Condition - Only Alerts When MACD Crosses UP & MACD > 0 -- Crosses Down & MACD < 0
if alert_Long_A and cross_UP_A
    alert("Symbol = (" + syminfo.tickerid + ") TimeFrame = (" + timeframe.period + ") Current Price (" + str.tostring(close) + ") MACD > 0 And Crosses Up.", alert.freq_once_per_bar_close)

if alert_Short_B and cross_DN_B
    alert("Symbol = (" + syminfo.tickerid + ") TimeFrame = (" + timeframe.period + ") Current Price (" + str.tostring(close) + ") MACD < 0 And Crosses Down.", alert.freq_once_per_bar_close)


if (histA_IsUp)
	strategy.entry("buy", strategy.long, comment="buy")
if (histA_IsDown)
	strategy.entry("sell", strategy.short, comment="sell")


Mais.