Tendencia de la media móvil doble siguiendo la estrategia

El autor:¿ Qué pasa?, Fecha: 2023-09-18 21:57:00
Las etiquetas:

Resumen general

Esta estrategia utiliza promedios móviles rápidos y lentos para identificar la dirección de la tendencia y generar señales cuando un MA rápido cruza un MA lento, creando un sistema de MA dual.

Principios

La estrategia emplea un MA rápido más corto y un MA lento más largo.

El precio por encima del MA es una tendencia alcista, el precio por debajo es una tendencia bajista.

En tendencias alcistas, se genera una señal larga cuando el MA rápido cruza el MA lento.

Después de la señal, la parada trasera se puede activar opcionalmente.

Ventajas

  1. La combinación de MA rápida y lenta identifica efectivamente la tendencia.

  2. El MA rápido produce señales comerciales sensibles.

  3. El MA lento filtra el ruido evitando una falsa fuga.

  4. Se pueden utilizar varios tipos de MA como EMA, DEMA.

  5. Se puede activar el stop loss de seguimiento.

Riesgos y mitigaciones

  1. Los parámetros más sensibles pueden ser probados.

  2. El stop loss puede estar demasiado apretado, lo que dará lugar a una salida prematura.

  3. Si se ignora el volumen, existe el riesgo de manipulación de precios.

  4. Sólo indicador propenso a señales falsas.

  5. La optimización de parámetros es difícil. La optimización paso a paso o GA puede encontrar parámetros óptimos.

Oportunidades de mejora

  1. Para obtener los mejores resultados, ensayar diferentes tipos y parámetros de MA.

  2. Investiga las medias móviles adaptativas para una mejor sensibilidad.

  3. Añadir otros indicadores o factores para el filtrado de señales.

  4. Construir paradas dinámicas para paradas flexibles.

  5. Optimice la gestión de dinero como el dimensionamiento dinámico de posiciones con ATR.

Resumen de las actividades

La estrategia opera con dos cruces MA para identificar tendencias, con paradas que limitan el riesgo. La lógica es simple y clara, pero la selección de parámetros y otros problemas existen. Las mejoras a través de la optimización, el filtrado, las paradas pueden mejorar la robustez. Sirve como un sistema de seguimiento de tendencias de base razonable.


/*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)

Más.