Estratégia de salto da média móvel exponencial

Autora:ChaoZhang, Data: 2023-12-08 16:47:39
Tags:

img

Estratégia geral

A estratégia de salto da média móvel exponencial (EMA) é uma estratégia que rastreia os avanços de preços da linha média móvel.

Nome da estratégia

Estratégia de salto da média móvel exponencial

Estratégia lógica

Esta estratégia é baseada na linha da média móvel exponencial (EMA). Ele calcula uma linha EMA em tempo real. Em seguida, verifica se o preço rebota da linha EMA:

  • Se o preço primeiro atravessa a linha EMA e depois se recupera acima da linha EMA, é um sinal de alta
  • Se o preço primeiro atravessar a linha EMA e depois cair abaixo da linha EMA, é um sinal de baixa

Tal recuperação é o sinal de entrada para a estratégia.

Análise das vantagens

Negocie com a tendência, evite ficar preso

A estratégia de rebote da EMA só entra em vigor após a confirmação da inversão de preços, o que evita que a negociação seja contra a tendência e fique presa.

Pequenas retiradas, bons retornos históricos

Ao utilizar a média móvel exponencial, a estratégia pode efetivamente suavizar os dados de preços e filtrar o ruído do mercado, resultando em pequenas reduções e bons retornos históricos.

Fácil de compreender, ajustamento flexível dos parâmetros

A estratégia de rebote da EMA baseia-se simplesmente em médias móveis, o que é fácil de entender para os iniciantes.

Análise de riscos

Propensos a sinais falsos

Muitas vezes, há falhas densas em torno da linha EMA, o que pode causar sinais errados.

Negociação com a tendência, incapaz de prever pontos de virada

A estratégia é essencialmente negociada junto com a tendência. É incapaz de prever pontos de virada de preços e só pode seguir a tendência. Isso pode perder a melhor oportunidade de entrada durante os ajustes cíclicos.

Previsão de prejuízo

O stop loss perto da linha média móvel às vezes é atingido, levando a perdas ampliadas.

Optimização

Incorporar outros indicadores de filtragem de sinal

Indicadores como RSI e MACD podem ser adicionados para confirmar a reversão do preço e filtrar sinais falsos.

Otimizar os métodos de stop loss

Os métodos de stop loss mais flexíveis, como time stops e volatility stops, podem ser utilizados para reduzir o risco de serem retirados.

Optimização de parâmetros

Otimizar os parâmetros do período EMA para encontrar as melhores combinações de parâmetros.

Conclusão

A estratégia de rebote da EMA é uma estratégia de tendência simples e prática. Tem pequenas reduções e é fácil de entender. Ao mesmo tempo, também tem alguns riscos de sinais falsos e ser parado. Podemos otimizar a estratégia usando melhores combinações de indicadores, métodos de stop loss e seleções de parâmetros para torná-la uma estratégia quantitativa estável e confiável.


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

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © tweakerID

// Simple strategy that checks for price bounces over an Exponential Moving Average. If the CLOSE of the candle bounces
// back from having it's LOW below the EMA, then it's a Bull Bounce. If the CLOSE of the candle bounces down from having it's
// high above the EMA, then it's a Bear Bounce. This logic can be reverted.

//@version=4
strategy("EMA Bounce", overlay=true, 
     default_qty_type=strategy.percent_of_equity, 
     default_qty_value=100, 
     initial_capital=10000, 
     commission_value=0.04, 
     calc_on_every_tick=false, 
     slippage=0)

direction = input(0, title = "Strategy Direction", type=input.integer, minval=-1, maxval=1)
strategy.risk.allow_entry_in(direction == 0 ? strategy.direction.all : (direction < 0 ? strategy.direction.short : strategy.direction.long))

/////////////////////// STRATEGY INPUTS ////////////////////////////////////////
title1=input(true, "-----------------Strategy Inputs-------------------")  

i_EMA=input(20, title="EMA Length")

/////////////////////// BACKTESTER /////////////////////////////////////////////
title2=input(true, "-----------------General Inputs-------------------")  

// Backtester General Inputs
i_SL=input(true, title="Use Swing Stop Loss and Take Profit")
i_SPL=input(defval=10, title="Swing Point Loopback")
i_PercIncrement=input(defval=.2, step=.1, title="Swing Point SL Perc Increment")*0.01
i_TPRRR = input(1.2, step=.1, title="Take Profit Risk Reward Ratio")

// Bought and Sold Boolean Signal
bought = strategy.position_size > strategy.position_size[1] 
 or strategy.position_size < strategy.position_size[1]

// Price Action Stop and Take Profit
LL=(lowest(i_SPL))*(1-i_PercIncrement)
HH=(highest(i_SPL))*(1+i_PercIncrement)
LL_price = valuewhen(bought, LL, 0)
HH_price = valuewhen(bought, HH, 0)
entry_LL_price = strategy.position_size > 0 ? LL_price : na 
entry_HH_price = strategy.position_size < 0 ? HH_price : na 
tp=strategy.position_avg_price + (strategy.position_avg_price - entry_LL_price)*i_TPRRR
stp=strategy.position_avg_price - (entry_HH_price - strategy.position_avg_price)*i_TPRRR


/////////////////////// STRATEGY LOGIC /////////////////////////////////////////

EMA=ema(close, i_EMA)
LowAboveEMA=low > EMA
LowBelowEMA=low < EMA
HighAboveEMA=high > EMA
HighBelowEMA=high < EMA
BullBounce=LowAboveEMA[1] and LowBelowEMA and close > EMA //and close > open
BearBounce=HighBelowEMA[1] and HighAboveEMA and close < EMA //and close < open
plot(EMA)

BUY=BullBounce
SELL=BearBounce

//Inputs
DPR=input(false, "Allow Direct Position Reverse")
reverse=input(false, "Reverse Trades")

// Entries
if reverse
    if not DPR
        strategy.entry("long", strategy.long, when=SELL and strategy.position_size == 0)
        strategy.entry("short", strategy.short, when=BUY and strategy.position_size == 0)
    else     
        strategy.entry("long", strategy.long, when=SELL)
        strategy.entry("short", strategy.short, when=BUY)
else
    if not DPR 
        strategy.entry("long", strategy.long, when=BUY and strategy.position_size == 0)
        strategy.entry("short", strategy.short, when=SELL and strategy.position_size == 0)
    else
        strategy.entry("long", strategy.long, when=BUY)
        strategy.entry("short", strategy.short, when=SELL)


SL=entry_LL_price
SSL=entry_HH_price
TP=tp
STP=stp

strategy.exit("TP & SL", "long", limit=TP, stop=SL, when=i_SL)
strategy.exit("TP & SL", "short", limit=STP, stop=SSL, when=i_SL)

/////////////////////// PLOTS //////////////////////////////////////////////////

plot(strategy.position_size > 0 ? SL : na , title='SL', style=plot.style_cross, color=color.red)
plot(strategy.position_size < 0 ? SSL : na , title='SSL', style=plot.style_cross, color=color.red)
plot(strategy.position_size > 0 ? TP : na, title='TP', style=plot.style_cross, color=color.green)
plot(strategy.position_size < 0 ? STP : na, title='STP', style=plot.style_cross, color=color.green)
// Draw price action setup arrows
plotshape(BUY ? 1 : na, style=shape.triangleup, location=location.belowbar, 
 color=color.green, title="Bullish Setup", transp=80, size=size.auto)
plotshape(SELL ? 1 : na, style=shape.triangledown, location=location.abovebar, 
 color=color.red, title="Bearish Setup", transp=80, size=size.auto)


Mais.