Tendencia del canal de media móvil de la envolvente siguiendo la estrategia

El autor:¿ Qué pasa?, Fecha: 2023-11-23 15:06:32
Las etiquetas:

img

Resumen general

La estrategia de seguimiento de tendencia del canal de media móvil es una estrategia de seguimiento de tendencia basada en líneas de media móvil e indicadores de canal. Realiza el juicio y seguimiento de las tendencias de precios mediante el establecimiento de un canal de media móvil de varios niveles.

Estrategia lógica

El principio básico de esta estrategia se basa en la funcionalidad de seguimiento de tendencias de las líneas de promedio móvil y el juicio del canal de los indicadores de envoltura. La estrategia utiliza parámetros configurables como el período de promedio móvil, el tipo suave, la fuente de precios, etc. para construir un promedio móvil de línea base. Luego, los canales ascendente y descendente se establecen de acuerdo con los valores de cambio porcentual establecidos por los parámetros. Cuando el precio rompe el canal inferior, vaya largo; cuando el precio rompe el canal superior, vaya corto. Al mismo tiempo, la estrategia introduce un promedio móvil independiente como la línea de stop loss.

En concreto, la estrategia tiene las siguientes características:

  1. Apoyar tanto las operaciones largas como las cortas, juzgar la dirección de la tendencia a través de canales ascendentes y descendentes.

  2. Abrir hasta 4 órdenes, implementar la apertura de orden piramidal a través de capas de polilínea para perseguir mayores ganancias.

  3. Configurar la media móvil de apertura y la media móvil de cierre independientes para lograr un stop loss preciso.

  4. Apoyar el cálculo de promedios móviles de diferentes marcos de tiempo (1 minuto a 1 día) para lograr la fusión de marcos de tiempo múltiples.

  5. Los promedios móviles de apertura y cierre admiten la selección de 6 modos de suavizado diferentes, que se pueden optimizar para diferentes variedades y ciclos.

  6. Se pueden introducir desplazamientos positivos y negativos para ajustar los canales y buscar avances más precisos.

La lógica de negociación específica de la estrategia es la siguiente:

  1. Calcular la media móvil de apertura del índice de referencia y obtener 4 líneas de avance según el porcentaje de parámetros establecido.

  2. Cuando el precio rompe la línea inferior del canal, abrir posiciones para ir largo; cuando el precio rompe la línea superior del canal, abrir posiciones para ir corto.

  3. Cuando el precio cae por debajo de la línea otra vez, stop los pedidos largos en capas; cuando el precio sube por encima de la línea otra vez, stop los pedidos cortos en capas.

  4. Se pueden abrir hasta 4 órdenes. Utilice la apertura de orden piramidal en capas para obtener mayores ganancias.

A través del principio de esta estrategia, se puede ver que la estrategia integra elementos tales como el seguimiento de tendencias de las líneas de media móvil, señales de avance del juicio del canal y el establecimiento de líneas de stop loss independientes para formar un sistema de tendencia relativamente riguroso y completo.

Análisis de ventajas

Según el código y el análisis lógico, la media móvil envuelve la tendencia del canal siguiendo la estrategia y tiene las siguientes ventajas:

  1. La fusión de marcos de tiempo múltiples mejora la probabilidad de capturar tendencias a gran escala. La estrategia admite el cálculo de promedios móviles de diferentes ciclos de 1 minuto a 1 día. Configurar los promedios móviles de apertura y stop-loss con diferentes ciclos logra la fusión del poder de juicio de tendencias de marcos de tiempo múltiples, lo que es más propicio para capturar tendencias a gran escala.

  2. El método de apertura de órdenes piramidal persigue mayores ganancias. La estrategia puede abrir hasta 4 órdenes. Al abrir órdenes en capas, equilibra la relación de ganancias y persigue mayores ganancias mientras controla los riesgos.

  3. El promedio móvil de apertura y stop-loss admite la selección de 6 modos, incluidos SMA / EMA / Promedio Móvil Dinámico, que se pueden optimizar para diferentes variedades y ciclos para mejorar la adaptabilidad.

  4. La estrategia permite la entrada de parámetros de porcentaje móvil del canal para ajustar el ancho del canal para la optimización hacia diferentes variedades o entornos de mercado, mejorando la precisión de los juicios de avance.

  5. La línea de stop loss independiente es útil para controlar el riesgo. La estrategia calcula una línea de promedio móvil independiente como la línea de cierre para detener las órdenes largas o cortas, lo que puede reducir en gran medida los riesgos comerciales y evitar perseguir órdenes perdedoras.

  6. La estructura del código es clara y fácil de desarrollar en segundo lugar. La estrategia está escrita en Pine Script con una estructura clara y fácil de entender y desarrollar en segundo lugar. Los usuarios pueden continuar optimizando parámetros o agregar otra lógica basada en el marco existente.

Análisis de riesgos

Aunque la lógica general de la estrategia es rigurosa y el control de riesgos está establecido, todavía hay algunos riesgos comerciales que deben ser conocidos, incluidos específicamente:

  1. Riesgo de inversión de tendencia a gran escala. La suposición central de la estrategia es que los precios seguirán avanzando de manera constante, con cierta tendencia. Sin embargo, cuando las tendencias a gran escala se invierten, tendrá un mayor impacto en la rentabilidad de la estrategia. Es necesario detener la pérdida a tiempo para controlar las pérdidas.

  2. En los mercados laterales o de choque, los precios pueden volver a caer por debajo de la línea del canal después de romper, lo que causará persecución al perder órdenes.

  3. La estrategia establece 4 capas de órdenes piramidal para perseguir mayores ganancias, lo que resulta en rendimientos significativos durante los períodos de ganancias, pero también una fuerte caída en las expectativas durante los períodos de pérdidas.

  4. El riesgo de optimización de la señal. La estrategia implica ajustes y optimizaciones a través de múltiples parámetros como el ancho del canal y el ciclo de media móvil. Esto requiere que los cuantos profesionales tengan experiencia en optimización para evitar el sobreajuste.

  5. Las condiciones extremas del mercado como brechas rápidas o límites de línea corta dañarán en gran medida la lógica de la estrategia, por lo que es necesario prestar atención a las métricas de riesgo sistémico para detener las pérdidas oportunamente.

En general, la estrategia se basa principalmente en ganancias de tendencia a gran escala para la rentabilidad, y solo se aplica a variedades y entornos de mercado con características de persistencia a largo plazo.

Direcciones de optimización

Para esta media móvil, la tendencia del canal de envoltura sigue la estrategia de las principales direcciones de optimización:

  1. Optimización adaptativa de líneas de canal y líneas de stop loss basadas en algoritmos de aprendizaje automático.

  2. Incorporar factores auxiliares como indicadores de sentimiento, ratios de ponderación de cartera para optimizar la lógica de la pirámide.

  3. Introducir modelos de costos de negociación y deslizamiento para mejorar la autenticidad de las pruebas de retroceso.

  4. Ampliar el análisis de correlación a través de clases de activos similares para construir marcos de control de riesgos unificados. Ampliar la estrategia de activo único actual a múltiples mercados similares como materias primas y criptomonedas, y unificar el control de riesgos a través del análisis de correlación para mejorar la estabilidad de la estrategia.

  5. Usar métodos como SHAP para analizar la importancia de cada variable de entrada para los resultados de la estrategia, clasificar la importancia de la salida y hacer que la lógica de la estrategia sea más transparente e interpretable para los usuarios.

La introducción de algoritmos como el aprendizaje automático y los modelos de múltiples factores para optimizar aún más la estabilidad, la autenticidad y la usabilidad de la estrategia es la principal dirección de mejora en el futuro.

Resumen de las actividades

En resumen, la estrategia de seguimiento de tendencia del canal de media móvil integra tres puntos clave: seguimiento de tendencias de medias móviles, identificación de indicadores de tendencia del canal y líneas de stop loss independientes para el control de riesgos. En los mercados de tendencia estricta, la estrategia puede proporcionar retornos estables con una cantidad razonable de tendencia después de la ganancia. Pero los usuarios deben prestar atención a los entornos del mercado macro, optimizar los parámetros adecuadamente y gestionar los riesgos, para que la estrategia pueda adaptarse a mercados comerciales complejos y en constante cambio. En general, la estrategia proporciona a los usuarios una solución de seguimiento de tendencias relativamente completa y rigurosa, y es un marco de estrategia cuantitativa muy adecuado para el desarrollo propietario y el desarrollo secundario.


/*backtest
start: 2023-10-23 00:00:00
end: 2023-11-22 00:00:00
period: 1h
basePeriod: 15m
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}]
*/

// This source code is subject to the terms of the GNU Affero General Public License v3.0 at https://www.gnu.org/licenses/agpl-3.0.html
//@version=4
strategy(title = "HatiKO Envelopes", shorttitle = "HatiKO Envelopes", overlay = true, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, pyramiding = 4, initial_capital=10, calc_on_order_fills=false)

//Settings
isLotSizeAvgShifts=input(true, title ="Calculate lot size with avgPrice shifts (HatiKO  calculate)")

lotsize_Short = input(100, defval = 100, minval = 0, maxval = 10000, title = "Lot short, %")
lotsize_Long = input(100, defval = 100, minval = 0, maxval = 10000, title = "Lot long, %")

//Shorts Open Config
timeFrame_Short =  input(defval = "Current.", options = ["Current.", "1m", "3m", "5m", "10m", "15m", "20m", "30m", "45m", "1H","2H","3H","4H","1D"], title = "Timeframe Short")
ma_type_Short = input(defval = "1. SMA", options = ["1. SMA", "2. PCMA", "3. EMA", "4. WMA", "5. DEMA", "6. ZLEMA"], title = "MA Type Short")
Short_Data_input = input(defval = "7.OHLC4", options = ["1.Open", "2.High", "3.Low", "4.Close", "5.HL2", "6.HLC3", "7.OHLC4", "8.OC2"], title = "Data Short")
len_Short = input(3, minval = 1, title = "MA Length Short")
offset_Short = input(0, minval = 0, title = "MA offset Short")

//Longs Open Config
timeFrame_Long =  input(defval = "Current.", options = ["Current.", "1m", "3m", "5m", "10m", "15m", "20m", "30m", "45m", "1H","2H","3H","4H","1D"], title = "Timeframe Long")
ma_type_Long = input(defval = "1. SMA", options = ["1. SMA", "2. PCMA", "3. EMA", "4. WMA", "5. DEMA", "6. ZLEMA"], title = "MA Type Long")
Long_Data_input = input(defval = "7.OHLC4", options = ["1.Open", "2.High", "3.Low", "4.Close", "5.HL2", "6.HLC3", "7.OHLC4", "8.OC2"], title = "Data Long")
len_Long = input(3, minval = 1, title = "MA Length Long")
offset_Long = input(0, minval = 0, title = "MA offset Long")

//Shorts Close Config
isEnableShortCustomClose=input(false, title ="Mode close MA Short")
timeFrame_close_Short = input(defval = "Current.", options = ["Current.", "1m", "3m", "5m", "10m", "15m", "20m", "30m", "45m", "1H","2H","3H","4H","1D"], title = "Timeframe Short Close")
ma_type_close_Short = input(defval = "1. SMA", options = ["1. SMA", "2. PCMA", "3. EMA", "4. WMA", "5. DEMA", "6. ZLEMA"], title = "MA Type Close Short")
Short_Data_input_close = input(defval = "7.OHLC4", options = ["1.Open", "2.High", "3.Low", "4.Close", "5.HL2", "6.HLC3", "7.OHLC4", "8.OC2"], title = "Data Short Close")
len_Short_close = input(3, minval = 1, title = "MA Length Short Close")
shortDeviation = input( 0.0, title = "Short Deviation %",step=0.1)
offset_Short_close = input(0, minval = 0, title = "MA offset Short Close")

//Longs Close Config
isEnableLongCustomClose=input(false, title ="Mode close MA Long")
timeFrame_close_Long =  input(defval = "Current.", options = ["Current.", "1m", "3m", "5m", "10m", "15m", "20m", "30m", "45m", "1H","2H","3H","4H","1D"], title = "Timeframe Long Close")
ma_type_close_Long = input(defval = "1. SMA", options = ["1. SMA", "2. PCMA", "3. EMA", "4. WMA", "5. DEMA", "6. ZLEMA"], title = "MA Type Close Long")
Long_Data_input_close = input(defval = "7.OHLC4", options = ["1.Open", "2.High", "3.Low", "4.Close", "5.HL2", "6.HLC3", "7.OHLC4", "8.OC2"], title = "Data Long Close")
len_Long_close = input(3, minval = 1, title = "MA Length Long Close")
longDeviation = input( -0.0, title = "Long Deviation %",step=0.1)
offset_Long_close = input(0, minval = 0, title = "MA offset Long Close")

shift_Short4_percent = input(0.0, title = "Short Shift 4")
shift_Short3_percent = input(10.0, title = "Short Shift 3")
shift_Short2_percent = input(7.0, title = "Short Shift 2")
shift_Short1_percent = input(4.0, title = "Short Shift 1")
shift_Long1_percent = input(-4.0, title = "Long Shift 1")
shift_Long2_percent = input(-7.0, title = "Long Shift 2")
shift_Long3_percent = input(-10.0, title = "Long Shift 3")
shift_Long4_percent = input( -0.0, title = "Long Shift 4")
isEnableDoubleLotShift3_Long=input(false, title ="Shift3 Long LotSize*2")
isEnableDoubleLotShift3_Short=input(false, title ="Shift3 Short LotSize*2")

year_Start = input(19, defval = 19, minval = 10, maxval = 99, title = "From Year 20XX")
year_End = input(99, defval = 99, minval = 10, maxval = 99, title = "To Year 20XX")
month_Start = input(01, defval = 01, minval = 01, maxval = 12, title = "From Month")
month_End = input(12, defval = 12, minval = 01, maxval = 12, title = "To Month")
day_Start = input(01, defval = 01, minval = 01, maxval = 31, title = "From day")
day_End = input(31, defval = 31, minval = 01, maxval = 31, title = "To day")

short4_isActive = shift_Short4_percent != 0 and lotsize_Short > 0
short3_isActive = shift_Short3_percent != 0 and lotsize_Short > 0
short2_isActive = shift_Short2_percent != 0 and lotsize_Short > 0
short1_isActive = shift_Short1_percent != 0 and lotsize_Short > 0
long1_isActive = shift_Long1_percent != 0 and lotsize_Long > 0
long2_isActive = shift_Long2_percent != 0 and lotsize_Long > 0
long3_isActive = shift_Long3_percent != 0 and lotsize_Long > 0
long4_isActive = shift_Long4_percent != 0 and lotsize_Long > 0

mult = 1 / syminfo.mintick
is_time_true = time > timestamp(2000+year_Start, month_Start, day_Start, 00, 00) and time < timestamp(2000+ year_End, month_End, day_End, 23, 59)

//MA
TFsecurity_Short = timeFrame_Short == "4H"?60*4:timeFrame_Short=="3H"?60*3:timeFrame_Short=="2H"?60*2:timeFrame_Short=="1H"?60:timeFrame_Short=="45m"?45:timeFrame_Short=="30m"?30:timeFrame_Short=="20m"?20:timeFrame_Short=="15m"?15:timeFrame_Short=="10m"?10:timeFrame_Short=="5m"?5:timeFrame_Short=="3m"?3:1
TFsecurity_Long = timeFrame_Long == "4H"?60*4:timeFrame_Long=="3H"?60*3:timeFrame_Long=="2H"?60*2:timeFrame_Long=="1H"?60:timeFrame_Long=="45m"?45:timeFrame_Long=="30m"?30:timeFrame_Long=="20m"?20:timeFrame_Long=="15m"?15:timeFrame_Long=="10m"?10:timeFrame_Long=="5m"?5:timeFrame_Long=="3m"?3:1

oc2 = (open + close) / 2
lag_Short = (len_Short - 1) / 2//floor((len_Short - 1) / 2)
lag_Long = (len_Long - 1) / 2 //floor((len_Long - 1) / 2)

source_Short = Short_Data_input == "1.Open" ? open : Short_Data_input == "2.High" ? high : Short_Data_input == "3.Low" ? low : Short_Data_input == "4.Close" ? close : Short_Data_input == "5.HL2" ? hl2 : Short_Data_input == "6.HLC3" ? hlc3 : Short_Data_input == "7.OHLC4" ? ohlc4 : Short_Data_input == "8.OC2" ? oc2: close
source_Long = Long_Data_input == "1.Open" ? open : Long_Data_input == "2.High" ? high : Long_Data_input == "3.Low" ? low : Long_Data_input == "4.Close" ? close : Long_Data_input == "5.HL2" ? hl2 : Long_Data_input == "6.HLC3" ? hlc3 : Long_Data_input == "7.OHLC4" ? ohlc4 : Long_Data_input == "8.OC2" ? oc2: close

preS_MA_Short = ma_type_Short == "1. SMA" ? sma(source_Short, len_Short) : ma_type_Short == "2. PCMA"? (highest(high, len_Short) + lowest(low, len_Short)) / 2 : ma_type_Short == "3. EMA" ? ema(source_Short, len_Short) : ma_type_Short == "4. WMA" ? wma(source_Short, len_Short) : ma_type_Short == "5. DEMA" ? (2 * ema(source_Short,len_Short) - ema(ema(source_Short,len_Short), len_Short)) : ma_type_Short == "6. ZLEMA" ? ema(source_Short + (source_Short - source_Short[lag_Short]), len_Short) : na
preS_MA_Long = ma_type_Long == "1. SMA" ? sma(source_Long, len_Long) :ma_type_Long == "2. PCMA"? (highest(high, len_Long) + lowest(low, len_Long)) / 2 : ma_type_Long == "3. EMA" ? ema(source_Long, len_Long) : ma_type_Long == "4. WMA" ? wma(source_Long, len_Long) : ma_type_Long == "5. DEMA" ? (2 * ema(source_Long,len_Long) - ema(ema(source_Long,len_Long), len_Long)) : ma_type_Long == "6. ZLEMA" ? ema(source_Long + (source_Long - source_Long[lag_Long]), len_Long) : na
pre_MA_Short = timeFrame_Short == "Current." ? preS_MA_Short : security(syminfo.tickerid, tostring(TFsecurity_Short), preS_MA_Short)
pre_MA_Long = timeFrame_Long == "Current." ? preS_MA_Long : security(syminfo.tickerid, tostring(TFsecurity_Long), preS_MA_Long)

MA_Short = (round(pre_MA_Short * mult) / mult)[offset_Short]
MA_Long = (round(pre_MA_Long * mult) / mult)[offset_Long]

Level_Long1 = long1_isActive ? round((MA_Long + MA_Long* shift_Long1_percent / 100) * mult) / mult : na
Level_Long2 = long2_isActive ? round((MA_Long + MA_Long* shift_Long2_percent / 100) * mult) / mult : na
Level_Long3 = long3_isActive ? round((MA_Long + MA_Long* shift_Long3_percent / 100) * mult) / mult : na
Level_Long4 = long4_isActive ? round((MA_Long + MA_Long* shift_Long4_percent / 100) * mult) / mult : na
Level_Short1 = short1_isActive ? round((MA_Short + MA_Short*shift_Short1_percent/ 100) * mult) / mult : na
Level_Short2 = short2_isActive ? round((MA_Short + MA_Short*shift_Short2_percent/ 100) * mult) / mult : na
Level_Short3 = short3_isActive ? round((MA_Short + MA_Short*shift_Short3_percent/ 100) * mult) / mult : na
Level_Short4 = short4_isActive ? round((MA_Short + MA_Short*shift_Short4_percent/ 100) * mult) / mult : na

//MA_Close
lag_Short_close = (len_Short_close - 1) / 2 //floor((len_Short_close - 1) / 2)
lag_Long_close = (len_Long_close - 1) / 2 //floor((len_Long_close - 1) / 2)

pre_PCMA_Short_close = (highest(high, len_Short_close) + lowest(low, len_Short_close)) / 2
pre_PCMA_Long_close = (highest(high, len_Long_close) + lowest(low, len_Long_close)) / 2

source_Short_close = Short_Data_input_close == "1.Open" ? open : Short_Data_input_close == "2.High" ? high : Short_Data_input_close == "3.Low" ? low : Short_Data_input_close == "4.Close" ? close : Short_Data_input_close == "5.HL2" ? hl2 : Short_Data_input_close == "6.HLC3" ? hlc3 : Short_Data_input_close == "7.OHLC4" ? ohlc4 : Short_Data_input_close == "8.OC2" ? oc2: close
source_Long_close = Long_Data_input_close == "1.Open" ? open : Long_Data_input_close == "2.High" ? high : Long_Data_input_close == "3.Low" ? low : Long_Data_input_close == "4.Close" ? close : Long_Data_input_close == "5.HL2" ? hl2 : Long_Data_input_close == "6.HLC3" ? hlc3 : Long_Data_input_close == "7.OHLC4" ? ohlc4 : Long_Data_input_close == "8.OC2" ? oc2: close

preS_MA_Short_close = ma_type_close_Short == "1. SMA" ? sma(source_Short_close, len_Short_close) : ma_type_close_Short == "2. PCMA"? (highest(high, len_Short_close) + lowest(low, len_Short_close)) / 2 : ma_type_close_Short == "3. EMA" ? ema(source_Short_close, len_Short_close) : ma_type_close_Short == "4. WMA" ? wma(source_Short_close, len_Short_close) : ma_type_close_Short == "5. DEMA" ? (2 * ema(source_Short_close,len_Short_close) - ema(ema(source_Short_close,len_Short_close), len_Short_close)) : ma_type_close_Short == "6. ZLEMA" ? ema(source_Short_close + (source_Short_close - source_Short_close[lag_Short_close]), len_Short_close) : na
preS_MA_Long_close = ma_type_close_Long == "1. SMA" ? sma(source_Long_close, len_Long_close) : ma_type_close_Long == "2. PCMA"? (highest(high, len_Long_close) + lowest(low, len_Long_close)) / 2 : ma_type_close_Long == "3. EMA" ? ema(source_Long_close, len_Long_close) : ma_type_close_Long == "4. WMA" ? wma(source_Long_close, len_Long_close) : ma_type_close_Long == "5. DEMA" ? (2 * ema(source_Long_close,len_Long_close) - ema(ema(source_Long_close,len_Long_close), len_Long_close)) : ma_type_close_Long == "6. ZLEMA" ? ema(source_Long_close + (source_Long_close - source_Long_close[lag_Long_close]), len_Long_close) : na

TFsecurity_close_Short=timeFrame_close_Short=="4H"?60*4:timeFrame_close_Short=="3H"?60*3:timeFrame_close_Short=="2H"?60*2:timeFrame_close_Short=="1H"?60:timeFrame_close_Short=="45m"?45:timeFrame_close_Short=="30m"?30:timeFrame_close_Short=="20m"?20:timeFrame_close_Short=="15m"?15:timeFrame_close_Short=="10m"?10:timeFrame_close_Short=="5m"?5:timeFrame_close_Short=="3m"?3:1
TFsecurity_close_Long=timeFrame_close_Long=="4H"?60*4:timeFrame_close_Long=="3H"?60*3:timeFrame_close_Long=="2H"?60*2:timeFrame_close_Long=="1H"?60:timeFrame_close_Long=="45m"?45:timeFrame_close_Long=="30m"?30:timeFrame_close_Long=="20m"?20:timeFrame_close_Long=="15m"?15:timeFrame_close_Long=="10m"?10:timeFrame_close_Long=="5m"?5:timeFrame_close_Long=="3m"?3:1

pre_MA_close_Short = isEnableShortCustomClose? security(syminfo.tickerid, timeFrame_close_Short=="Current."?timeframe.period:tostring(TFsecurity_close_Short), preS_MA_Short_close) : preS_MA_Short_close
pre_MA_close_Long = isEnableLongCustomClose?  security(syminfo.tickerid, timeFrame_close_Long=="Current."?timeframe.period:tostring(TFsecurity_close_Long), preS_MA_Long_close) : preS_MA_Long_close

MA_Short_close =  (round(pre_MA_close_Short * mult) / mult)[offset_Short_close]
MA_Long_close = (round(pre_MA_close_Long * mult) / mult)[offset_Long_close]

countShifts_Long = 0
countShifts_Long:=long1_isActive?countShifts_Long+1:countShifts_Long
countShifts_Long:=long2_isActive?countShifts_Long+1:countShifts_Long
countShifts_Long:=long3_isActive?countShifts_Long+1:countShifts_Long
countShifts_Long:=long4_isActive?countShifts_Long+1:countShifts_Long
avgPriceForLotShiftLong_Data_input = MA_Long+ (MA_Long*((shift_Long1_percent+shift_Long2_percent+shift_Long3_percent+shift_Long4_percent)/countShifts_Long/100))

countShifts_Short = 0
countShifts_Short:=short1_isActive?countShifts_Short+1:countShifts_Short
countShifts_Short:=short2_isActive?countShifts_Short+1:countShifts_Short
countShifts_Short:=short3_isActive?countShifts_Short+1:countShifts_Short
countShifts_Short:=short4_isActive?countShifts_Short+1:countShifts_Short
avgPriceForLotShiftShort_Data_input = MA_Short + (MA_Short*((shift_Short1_percent+shift_Short2_percent+shift_Short3_percent+shift_Short4_percent)/countShifts_Short/100))
strategy.initial_capital = 50000
balance=strategy.initial_capital + strategy.netprofit
lotlong = 0.0
lotshort = 0.0
lotlong := (balance / avgPriceForLotShiftLong_Data_input) * (lotsize_Long / 100)     //strategy.position_size == 0 ? (strategy.equity / close) * (lotsize_Long / 100) : lotlong[1]
lotshort := (balance / avgPriceForLotShiftShort_Data_input) * (lotsize_Short / 100)    //strategy.position_size == 0 ? (strategy.equity / close) * (lotsize_Short / 100) : lotshort[1]
lotlong:= lotlong>1000000000?1000000000:lotlong
lotshort:=lotshort>1000000000?1000000000:lotshort

if isLotSizeAvgShifts==false
    lotlong := (strategy.equity / open) * (lotsize_Long / 100) 
    lotshort := (strategy.equity / open) * (lotsize_Short / 100) 

value_deviationLong=0.0
value_deviationShort=0.0

if(isEnableLongCustomClose == false )
    MA_Long_close:=MA_Long
else 
    value_deviationLong := round(MA_Long_close * longDeviation /100 * mult) / mult
    
if(isEnableShortCustomClose == false )
    MA_Short_close:=MA_Short
else 
    value_deviationShort := round(MA_Short_close * shortDeviation /100 * mult) / mult

if MA_Short > 0 and lotshort > 0// and strategy.position_size<=0
    lotShort_Data_input = strategy.position_size < 0 ? round(abs(strategy.position_size) / lotshort) : 0.0
    strategy.entry("S1", strategy.short, lotshort, limit = Level_Short1, when = (lotShort_Data_input == 0  and short1_isActive and is_time_true ))

    lotShort_Data_input := strategy.position_size < 0 ? round(abs(strategy.position_size) / lotshort) : 0.0
    strategy.entry("S2", strategy.short, lotshort, limit = Level_Short2, when = (lotShort_Data_input <= 1 and short2_isActive and is_time_true ))

    lotshort3 = isEnableDoubleLotShift3_Short? lotshort*2 :lotshort
    lotShort_Data_input := strategy.position_size < 0 ? round(abs(strategy.position_size) / lotshort) : 0.0
    maxLotsshift3=isEnableDoubleLotShift3_Short?3:2
    strategy.entry("S3", strategy.short, lotshort3, limit = Level_Short3, when = (lotShort_Data_input <= maxLotsshift3 and short3_isActive and is_time_true ))

    lotShort_Data_input := strategy.position_size < 0 ? round(abs(strategy.position_size) / lotshort) : 0.0
    maxLotsshift4=isEnableDoubleLotShift3_Short?4:3
    strategy.entry("S4", strategy.short, lotshort, limit = Level_Short4, when = (lotShort_Data_input <= maxLotsshift4 and short4_isActive and is_time_true))
    
    strategy.exit("TPS", "S1" ,limit = MA_Short_close+value_deviationShort , when = is_time_true) 
    strategy.exit("TPS", "S2" ,limit = MA_Short_close+value_deviationShort , when = is_time_true) 
    strategy.exit("TPS", "S3" ,limit = MA_Short_close+value_deviationShort , when = is_time_true) 
    strategy.exit("TPS", "S4" ,limit = MA_Short_close+value_deviationShort , when = is_time_true) 
    
if MA_Long > 0 and lotlong > 0// and strategy.position_size>=0
    lotLong_Data_input = strategy.position_size > 0 ? round(strategy.position_size / lotlong) : 0.0
    strategy.entry("L1", strategy.long, lotlong, limit = Level_Long1, when = (lotLong_Data_input ==0 and long1_isActive and is_time_true))
    
    lotLong_Data_input := strategy.position_size > 0 ?  round(strategy.position_size / lotlong) : 0.0
    strategy.entry("L2", strategy.long, lotlong, limit = Level_Long2, when = ( lotLong_Data_input <= 1 and long2_isActive and is_time_true))
        
    lotlong3 = isEnableDoubleLotShift3_Long? lotlong*2 : lotlong 
    lotLong_Data_input := strategy.position_size > 0 ? round(strategy.position_size / lotlong) : 0.0
    maxLotsshift3=isEnableDoubleLotShift3_Long?3:2
    strategy.entry("L3", strategy.long, lotlong3, limit = Level_Long3, when = (lotLong_Data_input <= maxLotsshift3 and long3_isActive and is_time_true))
    
    maxLotsshift4=isEnableDoubleLotShift3_Long?4:3
    lotLong_Data_input := strategy.position_size > 0 ? round(strategy.position_size / lotlong) : 0.0
    strategy.entry("L4", strategy.long, lotlong, limit = Level_Long4, when = ( lotLong_Data_input<maxLotsshift4 and long4_isActive and is_time_true))
    
    strategy.exit( "TPL", "L1",limit = MA_Long_close+value_deviationLong, when = is_time_true) 
    strategy.exit( "TPL", "L2", limit = MA_Long_close+value_deviationLong, when = is_time_true) 
    strategy.exit( "TPL", "L3", limit = MA_Long_close+value_deviationLong, when = is_time_true) 
    strategy.exit( "TPL", "L4", limit = MA_Long_close+value_deviationLong, when = is_time_true) 
    
if (MA_Long_close < close)
    strategy.close("L1")
    strategy.close("L2")
    strategy.close("L3")
    strategy.close("L4")

if (MA_Short_close > close)
    strategy.close("S1")
    strategy.close("S2")
    strategy.close("S3")
    strategy.close("S4")
    
if time > timestamp(2000+year_End, month_End, day_End, 23, 59)
    strategy.close_all()
    strategy.cancel("L1")
    strategy.cancel("L2")
    strategy.cancel("L3")
    strategy.cancel("S1")
    strategy.cancel("S2")
    strategy.cancel("S3")
    
//Lines
colorlong = color.green
colorshort = color.red

value_long1 = long1_isActive ? Level_Long1 : na
value_long2 = long2_isActive ? Level_Long2 : na
value_long3 = long3_isActive ? Level_Long3 : na
value_long4 = long4_isActive ? Level_Long4 : na
value_short1 = short1_isActive ? Level_Short1 : na
value_short2 = short2_isActive ? Level_Short2 : na
value_short3 = short3_isActive ?Level_Short3 : na
value_short4 = short4_isActive? Level_Short4 : na

value_maShort_close= isEnableShortCustomClose ? MA_Short_close : na
value_maLong_close= isEnableLongCustomClose ? MA_Long_close : na

plot(value_maShort_close + value_deviationShort, offset = 1, color = color.orange, title = "MA line Short Close")

plot(value_short4, offset = 1, color = colorshort, title = "Short Shift 4")
plot(value_short3, offset = 1, color = colorshort, title = "Short Shift 3")
plot(value_short2, offset = 1, color = colorshort, title = "Short Shift 2")
plot(value_short1, offset = 1, color = colorshort, title = "Short Shift 1")
plot(countShifts_Short>0 and lotsize_Short>0 ? MA_Short:na, offset = 1, color = color.purple, title = "MA line Short")
plot(countShifts_Long>0 and lotsize_Long>0? MA_Long:na, offset = 1, color = color.lime, title = "MA line Long")
plot(value_long1, offset = 1, color = colorlong, title = "Long Shift 1")
plot(value_long2, offset = 1, color = colorlong, title = "Long Shift 2")
plot(value_long3, offset = 1, color = colorlong, title = "Long Shift 3")
plot(value_long4, offset = 1, color = colorlong, title = "Long Shift 4")

plot(value_maLong_close + value_deviationLong, offset = 1, color = color.blue, title = "MA line Long Close")

Más.