Estratégia de rastreamento de tendência de média móvel múltipla e filtragem de volatilidade dinâmica

EMA TR ATR
Data de criação: 2025-01-17 15:00:37 última modificação: 2025-01-17 15:00:37
cópia: 3 Cliques: 303
1
focar em
1617
Seguidores

Estratégia de rastreamento de tendência de média móvel múltipla e filtragem de volatilidade dinâmica

Visão geral

A estratégia é um sistema de negociação inteligente que combina acompanhamento de tendências e filtragem de volatilidade. Ele identifica tendências de mercado por meio da Média Móvel Exponencial (EMA), usa o True Range (TR) e filtros de volatilidade dinâmica para determinar o momento de entrada e gerencia o risco com um mecanismo dinâmico de stop-profit e stop-loss com base na volatilidade. A estratégia oferece suporte a dois modos de negociação: Scalp e Swing, que podem ser alternados de forma flexível de acordo com diferentes ambientes de mercado e estilos de negociação.

Princípio da estratégia

A lógica central da estratégia inclui os seguintes componentes principais:

  1. Identificação de tendências: use a MME de 50 períodos como um filtro de tendências e só opere comprado quando o preço estiver acima da MME e vendido quando o preço estiver abaixo da MME.
  2. Filtragem de volatilidade: calcula a EMA do intervalo verdadeiro (TR) e usa um fator de filtro ajustável (padrão 1,5) para filtrar o ruído do mercado.
  3. Condições de entrada: Combinado com a análise morfológica de três linhas K consecutivas, o movimento do preço deve ser contínuo e acelerado.
  4. Take Profit e Stop Loss: No modo de curto prazo, é definido com base no TR atual; no modo de banda, é definido com base nos pontos altos e baixos anteriores para obter um gerenciamento de risco dinâmico.

Vantagens estratégicas

  1. Forte adaptabilidade: por meio da combinação de filtragem dinâmica de volatilidade e rastreamento de tendências, ele pode se adaptar a diferentes ambientes de mercado.
  2. Gerenciamento de risco perfeito: forneça mecanismos dinâmicos de stop-profit e stop-loss para dois modos de negociação, que podem ser selecionados de forma flexível de acordo com as características do mercado.
  3. Boa ajustabilidade de parâmetros: parâmetros-chave como coeficiente de filtro, ciclo de tendência, etc. podem ser otimizados de acordo com as características dos produtos de negociação.
  4. Bom efeito de visualização: fornece marcas de sinais de compra e venda claras e exibições de posição de stop-profit e stop-loss para facilitar o monitoramento de transações.

Risco estratégico

  1. Risco de reversão de tendência: paradas consecutivas podem ocorrer em pontos de virada de tendência.
  2. Risco de falso rompimento: Sinais falsos podem ser disparados quando a volatilidade aumenta repentinamente.
  3. Sensibilidade dos parâmetros: A configuração inadequada dos coeficientes do filtro pode resultar em muito ou pouco sinal.
  4. Impacto do deslizamento: em um mercado rápido, você pode enfrentar grandes deslizamentos, o que pode afetar o desempenho da sua estratégia.

Direção de otimização da estratégia

  1. Adicionar filtragem de força de tendência: indicadores como ADX podem ser introduzidos para avaliar a força da tendência e melhorar os efeitos de rastreamento de tendências.
  2. Otimize o take-profit e o stop-loss: considere introduzir um stop-loss móvel para proteger mais lucros.
  3. Melhorar o modelo de swing trading: mais condições de julgamento específicas para swing trading podem ser adicionadas para melhorar as capacidades de retenção de médio e longo prazo.
  4. Adicionar análise de volume: combine alterações de volume para confirmar a validade do avanço.

Resumir

Esta estratégia constrói um sistema de negociação completo combinando organicamente rastreamento de tendências, filtragem de volatilidade e gerenciamento dinâmico de risco. A vantagem da estratégia é que ela é altamente adaptável e com risco controlado, além de oferecer um grande espaço para otimização. Ao definir parâmetros razoáveis ​​e escolher modos de negociação apropriados, a estratégia pode manter um desempenho estável em diferentes ambientes de mercado. É recomendável que os traders realizem testes retrospectivos e otimização de parâmetros suficientes antes do uso real e façam os ajustes correspondentes com base nas características de produtos de negociação específicos.

Código-fonte da estratégia
/*backtest
start: 2024-12-17 00:00:00
end: 2025-01-15 08:00:00
period: 2h
basePeriod: 2h
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT","balance":49999}]
*/

// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Creativ3mindz

//@version=5
strategy("Scalp Slayer (I)", overlay=true)

// Input Parameters
filterNumber = input.float(1.5, "Filter Number", minval=1.0, maxval=10.0, tooltip="Higher = More aggressive Filter, Lower = Less aggressive")
emaTrendPeriod = input.int(50, "EMA Trend Period", minval=1, tooltip="Period for the EMA used for trend filtering")
lookbackPeriod = input.int(20, "Lookback Period for Highs/Lows", minval=1, tooltip="Period for determining recent highs/lows")
colorTP = input.color(title='Take Profit Color', defval=color.orange)
colorSL = input.color(title='Stop Loss Color', defval=color.red)

// Inputs for visibility
showBuyLabels = input.bool(true, title="Show Buy Labels")
showSellLabels = input.bool(true, title="Show Sell Labels")

// Alert Options
alertOnCondition = input.bool(true, title="Alert on Condition Met", tooltip="Enable to alert when condition is met")

// Trade Mode Toggle
tradeMode = input.bool(false, title="Trade Mode (ON = Swing, OFF = Scalp)", tooltip="Swing-mode you can use your own TP/SL.")

// Calculations
tr = high - low
ema = filterNumber * ta.ema(tr, 50)
trendEma = ta.ema(close, emaTrendPeriod)  // Calculate the EMA for the trend filter

// Highest and lowest high/low within lookback period for swing logic
swingHigh = ta.highest(high, lookbackPeriod)
swingLow = ta.lowest(low, lookbackPeriod)

// Variables to track the entry prices and SL/TP levels
var float entryPriceLong = na
var float entryPriceShort = na
var float targetPriceLong = na
var float targetPriceShort = na
var float stopLossLong = na
var float stopLossShort = na
var bool tradeActive = false

// Buy and Sell Conditions with Trend Filter
buyCondition = close > trendEma and  // Buy only if above the trend EMA
      close[2] > open[2] and close[1] > open[1] and close > open and 
      (math.abs(close[2] - open[2]) > math.abs(close[1] - open[1])) and 
      (math.abs(close - open) > math.abs(close[1] - open[1])) and 
      close > close[1] and close[1] > close[2] and tr > ema

sellCondition = close < trendEma and  // Sell only if below the trend EMA
       close[2] < open[2] and close[1] < open[1] and close < open and 
       (math.abs(close[2] - open[2]) > math.abs(close[1] - open[1])) and 
       (math.abs(close - open) > math.abs(close[1] - open[1])) and 
       close < close[1] and close[1] < close[2] and tr > ema

// Entry Rules
if (buyCondition and not tradeActive)
    entryPriceLong := close  // Track entry price for long position
    stopLossLong := tradeMode ? ta.lowest(low, lookbackPeriod) : swingLow  // Scalping: recent low, Swing: lowest low of lookback period
    targetPriceLong := tradeMode ? close + tr : swingHigh  // Scalping: close + ATR, Swing: highest high of lookback period
    tradeActive := true

if (sellCondition and not tradeActive)
    entryPriceShort := close  // Track entry price for short position
    stopLossShort := tradeMode ? ta.highest(high, lookbackPeriod) : swingHigh  // Scalping: recent high, Swing: highest high of lookback period
    targetPriceShort := tradeMode ? close - tr : swingLow  // Scalping: close - ATR, Swing: lowest low of lookback period
    tradeActive := true

// Take Profit and Stop Loss Logic
signalBuyTPPrint = (not na(entryPriceLong) and close >= targetPriceLong)
signalSellTPPrint = (not na(entryPriceShort) and close <= targetPriceShort)

signalBuySLPrint = (not na(entryPriceLong) and close <= stopLossLong)
signalSellSLPrint = (not na(entryPriceShort) and close >= stopLossShort)

if (signalBuyTPPrint or signalBuySLPrint)
    entryPriceLong := na  // Reset entry price for long position
    targetPriceLong := na  // Reset target price for long position
    stopLossLong := na  // Reset stop-loss for long position
    tradeActive := false

if (signalSellTPPrint or signalSellSLPrint)
    entryPriceShort := na  // Reset entry price for short position
    targetPriceShort := na  // Reset target price for short position
    stopLossShort := na  // Reset stop-loss for short position
    tradeActive := false

// Plot Buy and Sell Labels with Visibility Conditions
plotshape(showBuyLabels and buyCondition, "Buy", shape.labelup, location=location.belowbar, color=color.green, text="BUY", textcolor=color.white, size=size.tiny)
plotshape(showSellLabels and sellCondition, "Sell", shape.labeldown, location=location.abovebar, color=color.red, text="SELL", textcolor=color.white, size=size.tiny)

// Plot Take Profit Flags
plotshape(showBuyLabels and signalBuyTPPrint, title="Take Profit (buys)", text="TP", style=shape.flag, location=location.abovebar, color=colorTP, textcolor=color.white, size=size.tiny)
plotshape(showSellLabels and signalSellTPPrint, title="Take Profit (sells)", text="TP", style=shape.flag, location=location.belowbar, color=colorTP, textcolor=color.white, size=size.tiny)

// Plot Stop Loss "X" Marker
plotshape(showBuyLabels and signalBuySLPrint, title="Stop Loss (buys)", text="X", style=shape.xcross, location=location.belowbar, color=colorSL, textcolor=color.white, size=size.tiny)
plotshape(showSellLabels and signalSellSLPrint, title="Stop Loss (sells)", text="X", style=shape.xcross, location=location.abovebar, color=colorSL, textcolor=color.white, size=size.tiny)

// Alerts

alertcondition(buyCondition and alertOnCondition, title="Buy Alert", message='{"content": "Buy {{ticker}} at {{close}}"}')
alertcondition(sellCondition and alertOnCondition, title="Sell Alert", message='{"content": "Sell {{ticker}} at {{close}}"}')
alertcondition(signalBuyTPPrint and alertOnCondition, title="Buy TP Alert", message='{"content": "Buy TP {{ticker}} at {{close}}"}')
alertcondition(signalSellTPPrint and alertOnCondition, title="Sell TP Alert", message='{"content": "Sell TP {{ticker}} at {{close}}"}')
alertcondition(signalBuySLPrint and alertOnCondition, title="Buy SL Alert", message='{"content": "Buy SL {{ticker}} at {{close}}"}')
alertcondition(signalSellSLPrint and alertOnCondition, title="Sell SL Alert", message='{"content": "Sell SL {{ticker}} at {{close}}"}')

if buyCondition
    strategy.entry("Enter Long", strategy.long)
else if sellCondition
    strategy.entry("Enter Short", strategy.short)