Estratégia de negociação baseada em zonas de oferta e procura com EMA e Trailing Stop

Autora:ChaoZhang, Data: 2024-01-18 16:41:16
Tags:

img

Resumo

A estratégia utiliza as zonas de oferta e demanda, a média móvel exponencial (EMA) e a parada de rastreamento da faixa verdadeira média (ATR) para os sinais de negociação. Os usuários podem ajustar as configurações da EMA e a visibilidade do sinal. A estratégia marca as zonas de alta alta (HH), baixa baixa (LL), baixa alta (LH) e baixa alta (HL). Os sinais são mostrados após a terceira vela, adequados para backtesting.

Estratégia lógica

Cálculos de indicadores

Média Móvel Exponencial (EMA):

  • A EMA é calculada a partir dos preços de encerramento de um período (default: 200).
  • Fórmula: EMA = (Price_t x α) + (EMA_t-1 x (1 - α)), onde α = 2/(longitude + 1)

Distância real média (ATR):

  • O ATR mede a volatilidade do mercado a partir da gama real de preços.
  • O alcance verdadeiro é o maior dos seguintes:
    • Corrente alta menos corrente baixa
    • Valor absoluto do máximo atual menos fechamento anterior
    • Valor absoluto do mínimo atual menos o fechamento anterior
  • O ATR normalmente usa 14 períodos.

A taxa de variação da taxa de variação da taxa de variação da taxa de variação da taxa de variação da taxa de variação da taxa de variação da taxa de variação da taxa de variação da taxa de variação.

Identificação da zona de oferta e de procura

Identifica padrões HH (Higher High), LL (Lower Low), HL (Higher Low) e LH (Lower High):

  1. Maior Maior (HH): Pico actual > pico anterior, ímpeto ascendente.

  2. Baixo Baixo (LL): Abaixo corrente < Abaixo anterior, ímpeto descendente.

  3. Alto Baixo (HL): Baço actual > Baço anterior, continuação ascendente.

  4. Baixo Alto (LH): Pico actual < pico anterior, continuação descendente.

Usado com tendências para identificar reversões ou continuações.

Entrada e saída

Sinal de entrada: Comprar/vender no terceiro fechamento da vela acima/abaixo do máximo/mínimo anterior.

Saída: Stop-loss traseiro baseado no ATR.

Vantagens

  1. Combina tendências, inversões, volatilidade para sinais robustos.
  2. As zonas de procura/oferta identificam os principais S/R.
  3. A parada dinâmica do ATR ajusta-se à volatilidade.
  4. Parâmetros personalizáveis.
  5. Regras de entrada simples.

Riscos e melhorias

  1. Falsos sinais: otimizar o comprimento da EMA.
  2. Um elevado multiplicador de ATR corre o risco de perseguir tendências.
  3. Considere filtros adicionais nas entradas.
  4. Teste uma abordagem centrada na tendência.

Conclusão

Combina várias técnicas para backtests decentes. mundo real é complexo, otimização é a chave. estratégia básica permite extensões e combinações.


/*backtest
start: 2023-12-18 00:00:00
end: 2024-01-17 00:00:00
period: 2h
basePeriod: 15m
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}]
*/

//@version=5
strategy("Supply and Demand Zones with EMA and Trailing Stop", shorttitle="SD Zones", overlay=true)

showBuySignals = input(true, title="Show Buy Signals", group="Signals")
showSellSignals = input(true, title="Show Sell Signals", group="Signals")
showHLZone = input(true, title="Show HL Zone", group="Zones")
showLHZone = input(true, title="Show LH Zone", group="Zones")
showHHZone = input(true, title="Show HH Zone", group="Zones")
showLLZone = input(true, title="Show LL Zone", group="Zones")

emaLength = input(200, title="EMA Length", group="EMA Settings")
atrLength = input(14, title="ATR Length", group="Trailing Stop")
atrMultiplier = input(2, title="ATR Multiplier", group="Trailing Stop")

// Function to identify supply and demand zones
getZones(src, len, mult) =>
    base = request.security(syminfo.tickerid, "D", close)
    upper = request.security(syminfo.tickerid, "D", high)
    lower = request.security(syminfo.tickerid, "D", low)
    multiplier = request.security(syminfo.tickerid, "D", mult)
    zonetype = base + multiplier * len
    zone = src >= zonetype
    [zone, upper, lower]

// Identify supply and demand zones
[supplyZone, _, _] = getZones(close, high[1] - low[1], 1)
[demandZone, _, _] = getZones(close, high[1] - low[1], -1)

// Plot supply and demand zones
bgcolor(supplyZone ? color.new(color.red, 80) : na)
bgcolor(demandZone ? color.new(color.green, 80) : na)

// EMA with Linear Weighted method
ema = ta.ema(close, emaLength)

// Color code EMA based on its relation to candles
emaColor = close > ema ? color.new(color.green, 0) : close < ema ? color.new(color.red, 0) : color.new(color.yellow, 0)

// Plot EMA
plot(ema, color=emaColor, title="EMA")

// Entry Signal Conditions after the third candle
longCondition = ta.crossover(close, high[1]) and bar_index >= 2
shortCondition = ta.crossunder(close, low[1]) and bar_index >= 2

// Trailing Stop using ATR
atrValue = ta.atr(atrLength)
trailStop = close - atrMultiplier * atrValue

// Strategy Entry and Exit
if (longCondition)
    strategy.entry("Buy", strategy.long)
    strategy.exit("TrailStop", from_entry="Buy", loss=trailStop)

if (shortCondition)
    strategy.entry("Sell", strategy.short)
    strategy.exit("TrailStop", from_entry="Sell", loss=trailStop)

// Plot Entry Signals
plotshape(series=showBuySignals ? longCondition : na, title="Buy Signal", color=color.new(color.green, 0), style=shape.triangleup, location=location.belowbar)
plotshape(series=showSellSignals ? shortCondition : na, title="Sell Signal", color=color.new(color.red, 0), style=shape.triangledown, location=location.abovebar)

// Plot Trailing Stop
plot(trailStop, color=color.new(color.red, 0), title="Trailing Stop")

// Plot HH, LL, LH, and HL zones
plotshape(series=showHHZone and ta.highest(high, 2)[1] and ta.highest(high, 2)[2] ? 1 : na, title="HH Zone", color=color.new(color.blue, 80), style=shape.triangleup, location=location.abovebar)
plotshape(series=showLLZone and ta.lowest(low, 2)[1] and ta.lowest(low, 2)[2] ? 1 : na, title="LL Zone", color=color.new(color.blue, 80), style=shape.triangledown, location=location.belowbar)
plotshape(series=showLHZone and ta.highest(high, 2)[1] and ta.lowest(low, 2)[2] ? 1 : na, title="LH Zone", color=color.new(color.orange, 80), style=shape.triangleup, location=location.abovebar)
plotshape(series=showHLZone and ta.lowest(low, 2)[1] and ta.highest(high, 2)[2] ? 1 : na, title="HL Zone", color=color.new(color.orange, 80), style=shape.triangledown, location=location.belowbar)


Mais.