Estrategia de negociación cuantitativa de múltiples indicadores

El autor:¿ Qué pasa?, Fecha: 2023-12-05 10:29:20
Las etiquetas:

img

Resumen general

Esta estrategia integra promedios móviles, índice de fuerza relativa (RSI) y divergencia de convergencia promedio móvil (MACD), tres indicadores técnicos principales, para abrir y cerrar automáticamente posiciones largas y cortas.

Estrategia lógica

La estrategia juzga principalmente la dirección de la tendencia comparando dos promedios móviles, y combina el indicador RSI para evitar oportunidades de reversión perdidas. Específicamente, la estrategia utiliza EMA o SMA para calcular la línea rápida y la línea lenta. La línea rápida que cruza por encima de la línea lenta es la señal de compra, y la línea rápida que cruza por debajo es la señal de venta. Para filtrar los avances falsos, la estrategia también establece la lógica del indicador RSI, solo cuando el indicador RSI también cumple con la condición, se activará la señal de negociación.

Además, el indicador MACD también se integra en la estrategia para las decisiones comerciales. Cuando la diferencia entre el indicador MACD cruza por encima del eje 0, es una señal de compra, y cuando cruza por debajo, es una señal de venta. Esto puede ayudar a juzgar si la tendencia se ha invertido para evitar señales incorrectas en los puntos de inflexión.

Análisis de ventajas

La mayor ventaja de esta estrategia es la integración de múltiples indicadores para filtrar las señales, lo que puede reducir eficazmente las señales falsas y mejorar la calidad de la señal.

  1. Las líneas rápidas y lentas combinadas con el indicador RSI pueden evitar falsos avances causados por el uso único de medias móviles.

  2. La integración del indicador MACD puede juzgar si la tendencia se ha invertido prematuramente para evitar señales erróneas en el punto de inflexión.

  3. La elección entre EMA y SMA permite seleccionar indicadores más adecuados para las diferentes características del mercado.

  4. La elección de sistemas de gestión de fondos permite controlar el tamaño de las órdenes individuales para controlar eficazmente los riesgos.

  5. Apoyar el stop loss y el take profit permite bloquear las ganancias y evitar que las pérdidas se agranden.

Análisis de riesgos

Los principales riesgos de esta estrategia incluyen:

  1. La optimización incorrecta de parámetros puede conducir a un mal rendimiento de la estrategia.

  2. La probabilidad de que el indicador emita señales erróneas todavía existe.

  3. El rendimiento de un solo símbolo es inestable, es necesario ampliar a otras variedades.

  4. La estrategia tendrá efecto en el futuro.

Direcciones de optimización

Los principales aspectos para optimizar esta estrategia incluyen:

  1. Prueba diferentes combinaciones de parámetros del indicador para encontrar los parámetros óptimos.

  2. Aumentar el stop de seguimiento en el mecanismo de stop loss. Después de que el precio corre una cierta distancia, puede dejar de seguir para obtener ganancias.

  3. Aumentar los indicadores de juicio para la tendencia principal para evitar el comercio en contra de la tendencia.

  4. El módulo de gestión monetaria para una mejor gestión de riesgos.

  5. Ve Filtro para factores fundamentales como las noticias.

Resumen de las actividades

Esta estrategia realiza la búsqueda y filtración de posiciones largas y cortas mediante la integración de múltiples indicadores técnicos como promedios móviles, RSI y MACD. Su ventaja es que puede filtrar eficazmente señales falsas y mejorar la calidad de la señal. Los principales inconvenientes son la selección de parámetros y la probabilidad de que los indicadores emitan señales incorrectas todavía existen. Las direcciones de optimización futuras incluyen optimización de parámetros, optimización de pérdidas de parada, filtración de tendencias, etc. En general, esta estrategia es efectiva como un marco de estrategia de múltiples indicadores, y necesita una mayor optimización y verificación en el futuro.


/*backtest
start: 2023-11-04 00:00:00
end: 2023-12-04 00:00:00
period: 2h
basePeriod: 15m
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/
// © fikira
//@version=4
strategy("Strategy Tester EMA-SMA-RSI-MACD", shorttitle="Strat-test", overlay=true, max_bars_back=5000, 
 default_qty_type= strategy.percent_of_equity, calc_on_order_fills=false, calc_on_every_tick=false, 
 pyramiding=0, default_qty_value=100, initial_capital=100)

Tiny     = "Tiny"
Small    = "Small"
Normal   = "Normal"
Large    = "Large"

cl      = "close" , op  = "open" , hi  = "high" , lo  = "low"
c4      = "ohlc4" , c3  = "hlc3" , hl  = "hl2"

co      = "(E)MA 1 > (E)MA 2" 
cu      = "(E)MA 3 < (E)MA 4"

co_HTF  = "(E)MA 1 (HTF) > (E)MA 2 (HTF)" 
cu_HTF  = "(E)MA 3 (HTF) < (E)MA 4 (HTF)"

L_S     = "Long & Short"                , _L_  = "Long Only"                , _S_ = "Short Only"

cla     = "Close above (E)MA 1"         
clu     = "Close under (E)MA 3"

cla_HTF = "Close above (E)MA 1 (HTF)"
clu_HTF = "Close under (E)MA 3 (HTF)"

rsi     = "RSI strategy"

none    = "NONE"
mch     = "macd > signal"               , mcl     = "macd < signal"
mch0    = "macd > 0"                    , mcl0    = "macd < 0"
sgh0    = "signal > 0"                  , sgl0    = "signal < 0"

mch_HTF = "macd (HTF) > signal (HTF)"   , mcl_HTF = "macd (HTF) < signal (HTF)"
mch0HTF = "macd (HTF) > 0"              , mcl0HTF = "macd (HTF) < 0"
sgh0HTF = "signal (HTF) > 0"            , sgl0HTF = "signal (HTF) < 0"

EMA     = "EMA"                         , SMA = "SMA"       

s       = input(cl,   "Source" , options=[cl, op, hi, lo, c4, c3, hl])

src     =
 s  == cl ? close :
 s  == op ? open  :
 s  == hi ? high  :
 s  == lo ? low   :
 s  == c4 ? ohlc4 :
 s  == c3 ? hlc3  : 
 s  == hl ? hl2   :
 close

__1_    = input(false, ">=< >=< [STRATEGIES] >=< >=<")

Type    = input(_L_,  "Type Strategy", options=[L_S, _L_, _S_])

_1a_    = input(false, ">=< >=< [BUY/LONG] >=< >=<")

ENT     = input(co,   "Pick your poison:", options=[co, cla, rsi, mch, mch0, sgh0])
EH      = input(0,    " if RSI >")
EL      = input(100,  " if RSI <")
EH_HTF  = input(0,    " if RSI (HTF) >")
EL_HTF  = input(100,  " if RSI (HTF) <")

EX      = input(none, " Extra argument", options=[none, mch, mch0, sgh0])
EX2     = input(none, " Second argument", options=[none, mch_HTF, mch0HTF, sgh0HTF, co_HTF, cla_HTF])

_1b_    = input(false, ">=< [(E)MA settings (Buy/Long)] >=<")

ma1     = input(SMA,  "  (E)MA 1", options=[EMA, SMA])
len1    = input(50,   "     Length"  )
ma2     = input(SMA,  "  (E)MA 2", options=[EMA, SMA])
len2    = input(100,  "     Length"  )
ma1HTF  = input(SMA,  "  (E)MA 1 - HTF", options=[EMA, SMA])
len1HTF = input(50,   "     Length"  )
ma2HTF  = input(SMA,  "  (E)MA 2 - HTF", options=[EMA, SMA])
len2HTF = input(100,  "     Length"  )

_2a_    = input(false, ">=< >=< [SELL/SHORT] >=< >=<")

CLO     = input(cu,   "Pick your poison:", options=[cu, clu, rsi, mcl, mcl0, sgl0])
CH      = input(0,    " if RSI >")
CL      = input(100,  " if RSI <")
CH_HTF  = input(0,    " if RSI (HTF) >")
CL_HTF  = input(100,  " if RSI (HTF) <")

CX      = input(none, " Extra argument", options=[none, mcl, mcl0, sgl0])
CX2     = input(none, " Second argument", options=[none, mcl_HTF, mcl0HTF, sgl0HTF, cu_HTF, clu_HTF])

_2b_    = input(false, ">=< [(E)MA settings (Sell/Short)] >=<")

ma3     = input(SMA,  "  (E)MA 3", options=[EMA, SMA])
len3    = input(50,   "     Length"  )
ma4     = input(SMA,  "  (E)MA 4", options=[EMA, SMA])
len4    = input(100,  "     Length"  )
ma3HTF  = input(SMA,  "  (E)MA 3 - HTF", options=[EMA, SMA])
len3HTF = input(50,   "     Length"  )
ma4HTF  = input(SMA,  "  (E)MA 4 - HTF", options=[EMA, SMA])
len4HTF = input(100,  "     Length"  )

__3_    = input(false, ">=< >=< [RSI]  >=< >=< >=<")

ler     = input(20 , "  RSI Length")

__4_    = input(false, ">=< >=< [MACD] >=< >=< >=<")

fst     = input(12, "  Fast Length")
slw     = input(26, "  Slow Length")
sgn     = input(9 , "  Signal Smoothing")
sma_source = input(false, "Simple MA(Oscillator)")
sma_signal = input(false, "Simple MA(Signal Line)")

__5_    = input(false, ">=< >=< [HTF settings] >=< >=<")

MA_HTF  = input("D", "  (E)MA HTF", type = input.resolution)
RSI_HTF = input("D", "  RSI HTF"  , type = input.resolution)
MACD_HTF= input("D", "  MACD HTF" , type = input.resolution)

__6_    = input(false, ">=< >=< [SL/TP] >=< >=< >=<")

sl      = input(false, "Stop Loss?")
SL      = input(10.0, title="  Stop Loss %"  ) / 100
tp      = input(false, "Take Profit?")
TP      = input(20.0, title="  Take Profit %") / 100
 
SL_     = strategy.position_avg_price * (1 - SL)
TP_     = strategy.position_avg_price * (1 + TP)

// Limitation in time
// (= inspired from a script of "Che_Trader")

xox     = input(false, ">=< >=< [TIME] >=< >=< >=<")

ystr1   = input(2010, "  Since Year" )
ystp1   = input(2099, "  Till Year"  )
mstr1   = input(1   , "  Since Month")
mstp1   = input(12  , "  Till Month" )
dstr1   = input(1   , "  Since Day"  )
dstp1   = input(31  , "  Till Day"   )
 
_Str1   = timestamp(ystr1, mstr1, dstr1,  1,  1)
Stp1_   = timestamp(ystp1, mstp1, dstp1, 23, 59)

TIME    = time >= _Str1 and time <= Stp1_ ? true : false

////////////////////////////////////////////////////////////////////////////////////////////

_1      = 
 ma1 == SMA ? sma(src, len1) : 
 ma1 == EMA ? ema(src, len1) : 
 na
_2      = 
 ma2 == SMA ? sma(src, len2) :
 ma2 == EMA ? ema(src, len2) :
 na
_3      = 
 ma3 == SMA ? sma(src, len3) :
 ma3 == EMA ? ema(src, len3) :
 na
_4      = 
 ma4 == SMA ? sma(src, len4) :
 ma4 == EMA ? ema(src, len4) :
 na

_1b  = 
 ma1HTF == SMA ? sma(src, len1HTF) :
 ma1HTF == EMA ? ema(src, len1HTF) :
 na
_2b  = 
 ma2HTF == SMA ? sma(src, len2HTF) :
 ma2HTF == EMA ? ema(src, len2HTF) :
 na
_3b  = 
 ma3HTF == SMA ? sma(src, len3HTF) :
 ma3HTF == EMA ? ema(src, len3HTF) :
 na
_4b  = 
 ma4HTF == SMA ? sma(src, len4HTF) :
 ma4HTF == EMA ? ema(src, len4HTF) :
 na

_1_HTF = security(syminfo.tickerid, MA_HTF,  _1b)
_2_HTF = security(syminfo.tickerid, MA_HTF,  _2b)
_3_HTF = security(syminfo.tickerid, MA_HTF,  _3b)
_4_HTF = security(syminfo.tickerid, MA_HTF,  _4b)
cl_HTF = security(syminfo.tickerid, MA_HTF,  close)

////////////////////////////////////////////////////////////////////////////////////////////

plot(ENT == co or ENT == cla ? _1 : na            , title="(E)MA 1", color=color.lime                           )
plot(ENT == co               ? _2 : na            , title="(E)MA 2", color=color.red                            )
plot(CLO == cu or CLO == clu ? _3 : na            , title="(E)MA 3", color= _3 == _1 ? color.lime : color.yellow)
plot(CLO == cu               ? _4 : na            , title="(E)MA 4", color= _4 == _2 ? color.red  : color.blue  )
plot(EX2 == co_HTF or EX2 == cla_HTF ? _1_HTF : na, title="(E)MA 1 HTF", color=color.lime, linewidth=2, transp=50)
plot(EX2 == co_HTF                   ? _2_HTF : na, title="(E)MA 2 HTF", color=color.red , linewidth=2, transp=50)
plot(CX2 == cu_HTF or CX2 == clu_HTF ? _3_HTF : na, title="(E)MA 3 HTF", color= _3_HTF == _1_HTF ? color.lime : color.yellow, linewidth=2, transp=50)
plot(CX2 == cu_HTF                   ? _4_HTF : na, title="(E)MA 4 HTF", color= _4_HTF == _2_HTF ? color.red  : color.blue  , linewidth=2, transp=50)

////////////////////////////////////////////////////////////////////////////////////////////

// RSI

rsi_       = rsi(src, ler)
rsi_HTF    = security(syminfo.tickerid, RSI_HTF,  rsi_)

////////////////////////////////////////////////////////////////////////////////////////////

// MACD

fast_ma    = sma_source ? sma(src, fst) : ema(src, fst)
slow_ma    = sma_source ? sma(src, slw) : ema(src, slw)
macd       = fast_ma - slow_ma
signal     = sma_signal ? sma(macd, sgn) : ema(macd, sgn)
hist       = macd - signal

macd_HTF   = security(syminfo.tickerid, MACD_HTF, macd  )
signal_HTF = security(syminfo.tickerid, MACD_HTF, signal)

////////////////////////////////////////////////////////////////////////////////////////////

extra = 
 EX  == none    ? true                   :
 EX  == mch     ? macd >  signal         :
 EX  == mch0    ? macd >  0              :
 EX  == sgh0    ? signal >  0            :
 false

cxtra = 
 CX  == none    ? true                   :
 CX  == mcl     ? macd <= signal         :
 CX  == mcl0    ? macd <= 0              :
 CX  == sgl0    ? signal <= 0            :
 false

EXTRA = 
 EX2 == none    ? true                   :
 EX2 == mch_HTF ? macd_HTF >  signal_HTF :
 EX2 == mch0HTF ? macd_HTF >  0          :
 EX2 == sgh0HTF ? signal_HTF >  0        :
 EX2 == co_HTF  ? _1_HTF >  _2_HTF       :
 EX2 == cla_HTF ? cl_HTF >  _1_HTF       : 
 false
 
CXTRA =
 CX2 == none    ? true                   :
 CX2 == mcl_HTF ? macd_HTF <= signal_HTF :
 CX2 == mcl0HTF ? macd_HTF <= 0          :
 CX2 == sgl0HTF ? signal_HTF <= 0        :
 CX2 == cu_HTF  ? _3_HTF <= _4_HTF       :
 CX2 == clu_HTF ? cl_HTF <= _3_HTF       : 
 false

RSI = rsi_ > EH and rsi_ <= EL and rsi_HTF > EH_HTF and rsi_HTF <= EL_HTF

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

BUY = 
 ENT == co    and TIME and extra and EXTRA and RSI ? _1 > _2        : 
 ENT == cla   and TIME and extra and EXTRA and RSI ? src > _1       : 
 ENT == rsi   and TIME and extra and EXTRA         ? RSI            : 
 ENT == mch   and TIME and extra and EXTRA and RSI ? macd > signal  : 
 ENT == mch0  and TIME and extra and EXTRA and RSI ? macd > 0       : 
 ENT == sgh0  and TIME and extra and EXTRA and RSI ? signal > 0     : 
 na

SELL = 
 CLO == cu    and TIME and cxtra and CXTRA and RSI ? _3 <= _4       : 
 CLO == clu   and TIME and cxtra and CXTRA and RSI ? src <= _3      : 
 CLO == rsi   and TIME and cxtra and CXTRA         ? RSI            :
 CLO == mcl   and TIME and cxtra and CXTRA and RSI ? macd <= signal : 
 CLO == mcl0  and TIME and cxtra and CXTRA and RSI ? macd <= 0      : 
 CLO == sgl0  and TIME and cxtra and CXTRA and RSI ? signal <= 0    : 
 na

if BUY
    if (Type == _S_)
        strategy.close("[S]")
    else
        strategy.entry("[B]", strategy.long)

if SELL
    if (Type == _L_)
        strategy.close("[B]")
    else
        strategy.entry("[S]", strategy.short)

strategy.exit("[SL/TP]", "[B]", stop= sl ? SL_ : na, limit= tp ? TP_ : na)



Más.