Tendência de média móvel dupla de acordo com a estratégia

Autora:ChaoZhang, Data: 2023-09-18 21:57:00
Tags:

Resumo

Esta estratégia utiliza médias móveis rápidas e lentas para identificar a direção da tendência e gerar sinais quando a MA rápida cruza a MA lenta, criando um sistema de MA dupla.

Princípios

A estratégia utiliza uma MA rápida mais curta e uma MA lenta mais longa.

O MA lento define a principal direção da tendência.

Em tendências de alta, o sinal longo é gerado quando o MA rápido cruza acima do MA lento. Em tendências de baixa, o sinal curto é gerado quando o MA rápido cruza abaixo do MA lento.

Após o sinal, a parada de tração pode ser habilitada opcionalmente.

Vantagens

  1. A combinação de MA rápida e lenta identifica eficazmente a tendência.

  2. A MA rápida produz sinais comerciais sensíveis.

  3. A MA lenta filtra o ruído, evitando uma falsa fuga.

  4. Vários tipos de MA como EMA, DEMA podem ser usados.

  5. O trailing stop loss pode ser ativado.

Riscos e atenuações

  1. O atraso de MA pode atrasar os sinais. Podem ser testados parâmetros mais sensíveis.

  2. O stop loss pode ser muito apertado, levando a uma saída prematura.

  3. O volume é ignorado, existe o risco de manipulação de preços.

  4. Indicador apenas propenso a sinais falsos.

  5. A otimização de parâmetros é difícil. A otimização por etapas ou GA pode encontrar parâmetros ideais.

Oportunidades de melhoria

  1. Ensaiar diferentes tipos e parâmetros de MA para obter os melhores resultados.

  2. Pesquise médias móveis adaptativas para uma melhor sensibilidade.

  3. Adicionar outros indicadores ou fatores de filtragem de sinal.

  4. Construir paradas dinâmicas para paradas flexíveis.

  5. Otimizar a gestão de dinheiro como dimensionamento de posição dinâmica com ATR.

Resumo

A estratégia troca cruzamento de MA duplo para identificar tendências, com paradas limitando o risco. A lógica é simples e clara, mas a seleção de parâmetros e outras questões existem. Melhorias através de otimização, filtragem, paradas podem melhorar a robustez.


/*backtest
start: 2023-08-18 00:00:00
end: 2023-09-17 00:00:00
period: 3h
basePeriod: 15m
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}]
*/

//@version=2
strategy(title = "Noro's Trend MAs Strategy v1.7", shorttitle = "Trend MAs str 1.7", overlay=true, default_qty_type = strategy.percent_of_equity, default_qty_value=100.0, pyramiding=0)

//Settings
needlong = input(true, "long")
needshort = input(true, "short")
needstops = input(false, "stops")
stoppercent = input(5, defval = 5, minval = 1, maxval = 50, title = "Stop, %")
type = input(7, defval = 7, minval = 1, maxval = 7, title = "Type of Slow MA")
src = input(close, defval = close, title = "Source of Slow MA")
usefastsma = input(true, "Use fast MA Filter")
fastlen = input(5, defval = 5, minval = 1, maxval = 50, title = "fast MA Period")
len = input(20, defval = 20, minval = 2, maxval = 200, title = "slow MA Period")
bars = input(2, defval = 2, minval = 0, maxval = 3, title = "Bars Q")
needbg = input(false, defval = false, title = "Need trend Background?")
needarr = input(false, defval = false, title = "Need entry arrows?")

fastsma = ema(src, fastlen)

//DEMA
dema = 2 * ema(src, len) - ema(ema(close, len), len)

//TEMA
xPrice = close
xEMA1 = ema(src, len)
xEMA2 = ema(xEMA1, len)
xEMA3 = ema(xEMA2, len)
tema = 3 * xEMA1 - 3 * xEMA2 + xEMA3

//KAMA
xvnoise = abs(src - src[1])
nfastend = 0.20
nslowend = 0.05
nsignal = abs(src - src[len])
nnoise = sum(xvnoise, len)
nefratio = iff(nnoise != 0, nsignal / nnoise, 0)
nsmooth = pow(nefratio * (nfastend - nslowend) + nslowend, 2) 
kama = nz(kama[1]) + nsmooth * (src - nz(kama[1]))

//PriceChannel
lasthigh = highest(src, len)
lastlow = lowest(src, len)
center = (lasthigh + lastlow) / 2

//Trend
ma = type == 1 ? sma(src, len) : type == 2 ? ema(src, len) : type == 3 ? vwma(src, len) : type == 4 ? dema : type == 5 ? tema : type == 6 ? kama : type == 7 ? center : 0
trend = low > ma and low[1] > ma[1] and low[2] > ma[2] ? 1 : high < ma and high[1] < ma[1] ? -1 : trend[1]

//Bars
bar = close > open ? 1 : close < open ? -1 : 0
redbars = bars == 0 ? 1 : bars == 1 and bar == -1 ? 1 : bars == 2 and bar == -1 and bar[1] == -1 ? 1 : bars == 3 and bar == -1 and bar[1] == -1 and bar[2] == -1 ? 1 : 0
greenbars = bars == 0 ? 1 : bars == 1 and bar == 1 ? 1 : bars == 2 and bar == 1 and bar[1] == 1 ? 1 : bars == 3 and bar == 1 and bar[1] == 1 and bar[2] == 1 ? 1 : 0

//Signals
min = min(open, close)
max = max(open, close)
up = trend == 1 and (low < fastsma or usefastsma == false) and redbars == 1 ? 1 : 0
dn = trend == -1 and (high > fastsma or usefastsma == false) and greenbars == 1 ? 1 : 0

//Lines
colorfastsma = usefastsma == true ? red : na
plot(fastsma, color = colorfastsma, title = "Fast MA")
plot(ma, color = blue, linewidth = 3, transp = 0, title = "Slow MA")

//Arrows
plotarrow(up == 1 and needarr == true ? 1 : 0, colorup = black, colordown = black, transp = 0)
plotarrow(dn == 1 and needarr == true ? -1 : 0, colorup = black, colordown = black, transp = 0)

//Background
col = needbg == false ? na : trend == 1 ? lime : red
bgcolor(col, transp = 90)

//Alerts
alertcondition(up == 1, title='buy', message='Uptrend')
alertcondition(dn == 1, title='sell', message='Downtrend')

//Trading
stoplong = up == 1 and needstops == true ? close - (close / 100 * stoppercent) : stoplong[1]
stopshort = dn == 1 and needstops == true ? close + (close / 100 * stoppercent) : stopshort[1]

longCondition = up == 1
if (longCondition)
    strategy.entry("Long", strategy.long, needlong == false ? 0 : na)
    strategy.exit("Stop Long", "Long", stop = stoplong)

shortCondition = dn == 1
if (shortCondition)
    strategy.entry("Short", strategy.short, needshort == false ? 0 : na)
    strategy.exit("Stop Short", "Short", stop = stopshort)

Mais.