
La estrategia de seguimiento de tendencias de canales de envelopes de promedio móvil es una estrategia de seguimiento de tendencias basada en promedios móviles y indicadores de canales. Permite el juicio y el seguimiento de las tendencias de precios mediante la creación de canales de promedios móviles en múltiples capas. La estrategia combina el cálculo de promedios móviles de diferentes períodos de tiempo al mismo tiempo, lo que permite la fusión de múltiples marcos de tiempo, lo que ayuda a capturar tendencias más grandes.
El principio central de esta estrategia se basa en la función de seguimiento de tendencias de las medias móviles y en la determinación de canales en el indicador Envelop. La estrategia construye una media móvil de referencia con parámetros configurables como el ciclo de las medias móviles, el tipo de suavizado y la fuente de precios.
En concreto, la estrategia tiene las siguientes características:
Apoya operaciones de plus y de minus, para determinar la dirección de la tendencia a través de canales ascendentes y descendentes.
Se pueden abrir hasta 4 hojas, para conseguir una pirámide de apuestas mediante la división de la línea de descuento, con el fin de obtener más ganancias.
Se puede configurar un promedio móvil de apertura de posición independiente y un promedio móvil de posición, para lograr un alto de pérdida preciso.
Soporta el cálculo de promedios móviles en diferentes períodos de tiempo (de 1 minuto a 1 día) y permite la integración de múltiples marcos de tiempo.
Las medias móviles de apertura de depósito y de depósito soportan 6 opciones diferentes de modos suaves, que se pueden optimizar para diferentes variedades y períodos.
Se puede introducir un desplazamiento positivo y negativo para ajustar el canal y buscar una brecha más precisa.
La lógica específica de la estrategia es la siguiente:
Calcula el promedio móvil de apertura de posición de referencia, establece el porcentaje de acuerdo con el parámetro y obtiene 4 líneas de ruptura.
Cuando el precio se rompe la línea de la vía inferior, hacer más posiciones en el orden; cuando el precio se rompe la línea de la vía superior, en el orden de la apertura de la posición a la baja.
Calcula el promedio móvil de posición libre independiente como la línea de parada. Cuando el precio vuelve a caer por debajo de la línea, se detiene por un nivel de pérdidas para los singles; cuando el precio vuelve a romper la línea, se detiene por un nivel de pérdidas para los singles.
Se pueden abrir hasta 4 hojas, para ganar dinero a través de la pirámide de estratificación de la línea de corte.
La estrategia combina elementos como el seguimiento de tendencias de las medias móviles, las señales de ruptura de los juicios de canal y el establecimiento de líneas de parada independientes para formar un sistema de tendencias relativamente riguroso y completo.
De acuerdo con el código de la estrategia y la anatomía lógica, la estrategia de seguimiento de tendencias del canal de la media móvil de la envolvente tiene las siguientes ventajas:
La combinación de múltiples marcos de tiempo mejora la probabilidad de capturar tendencias a gran escala. La estrategia admite el cálculo de promedios móviles de diferentes períodos, desde 1 minuto hasta 1 día. Se puede configurar la apertura de posiciones y el cierre de pérdidas con promedios móviles de diferentes períodos.
La estrategia se puede abrir hasta 4 hojas, equilibrar las ganancias y las pérdidas a través de la estrategia de la pirámide, y buscar más ganancias bajo la premisa de controlar el riesgo.
Se puede elegir entre 6 modos de promedio móvil y es muy adaptable. Los promedios móviles de apertura y pérdida admiten SMA / EMA / promedios móviles dinámicos. Se pueden optimizar para diferentes variedades y períodos, lo que mejora la adaptabilidad.
La línea de canal es ajustable, la precisión del juicio de ruptura. La estrategia puede introducir el parámetro de porcentaje de movimiento del canal y ajustar el ancho del canal para optimizarlo para diferentes variedades o entornos de mercado, lo que mejora la precisión del juicio de ruptura.
Línea de parada independiente, ayuda a controlar el riesgo. La estrategia de calcular la media móvil independiente como línea de equilibrio, para detener el multi-unidad o unidad vacía, puede reducir considerablemente el riesgo de negociación, evitar la inyección de seguimiento.
La estructura del código es clara y fácil de reutilizar. Las estrategias se escriben con Pine Script, la estructura del código es clara, fácil de entender y reutilizar. El usuario puede seguir optimizando los parámetros basándose en el marco existente o agregar otra lógica.
A pesar de la rigurosidad lógica y el control de riesgos de la estrategia en general, existen ciertos riesgos de transacción a tener en cuenta, que incluyen:
Riesgo de reversión de la tendencia a gran escala. La estrategia se basa en la hipótesis de que el precio seguirá avanzando y que existe una cierta tendencia. Sin embargo, cuando se produce una reversión de la tendencia a gran escala, el impacto en la ganancia de la estrategia será mayor.
Riesgo de fracaso de la ruptura. En un mercado de reajuste o de crisis, los precios pueden volver a caer después de romper la línea de canal. Esto provoca una inyección de seguimiento, que debe reducirse mediante parámetros de optimización.
Gestión de riesgos de valor esperado. La estrategia de establecer 4 capas de alza de posición para buscar más ganancias, lo que significa que los beneficios son significativos cuando se gana, pero el valor esperado disminuye significativamente en los períodos de pérdidas. Esto requiere que los inversores tengan una capacidad de gestión mental profesional.
La estrategia implica la optimización de ajustes de varios parámetros, como la anchura del canal, el ciclo de las medias móviles, etc., lo que requiere que los analistas cuantitativos profesionales tengan experiencia en optimización para evitar el riesgo de sobreajuste.
Riesgo en situaciones especiales. Los riesgos extremos, como la brecha rápida o el día límite de la línea corta, pueden destruir considerablemente la lógica de la estrategia. En este caso, es necesario prestar atención a los indicadores de riesgo del sistema y detener los daños a tiempo.
En general, la estrategia depende principalmente de la tendencia a gran escala para obtener ganancias, y solo se aplica a variedades y entornos de mercado con características de persistencia a largo plazo. Además, la optimización de múltiples parámetros y el control de la mentalidad también son clave para garantizar la rentabilidad estable de la estrategia.
Las principales direcciones de optimización para la estrategia de seguimiento de tendencias en el canal de envelopes de la media móvil incluyen:
Optimización de la autoadaptación de las líneas de acceso y las líneas de parada basadas en algoritmos de aprendizaje automático. Se pueden usar algoritmos como LSTM, predicción de trayectoria para entrenar modelos de líneas de acceso y líneas de parada, para una predicción de precios y una evitación de riesgos más inteligentes.
Optimización de la lógica de alza de la posición en combinación con factores auxiliares como los indicadores de sentimiento y la proporción de la posición de la cartera. Se pueden agregar indicadores como la amplitud absoluta de la onda, el sentimiento del mercado, el control del riesgo de la cartera y la optimización de la lógica de alza de la pirámide.
Introducción de costos de transacción y modelos de puntos de deslizamiento para mejorar la veracidad de la retroalimentación. La retroalimentación actual no tiene en cuenta el impacto de los costos de transacción, que es un factor importante en el disco real, y se necesita la creación de modelos matemáticos para incorporarlos.
Extensión del análisis de correlación de la misma variedad, construcción de un sistema de control de riesgo unificado. Extensión de la estrategia de una variedad única existente a varios mercados similares, como mercancías, monedas digitales, control de riesgo unificado a través del análisis de correlación, mejora de la estabilidad de la estrategia.
Aumentar la explanabilidad de la política, mejorar la facilidad de uso del usuario. El uso de métodos como SHAP para analizar la influencia de cada variable de entrada en los resultados de la política, ordenar la importancia de la salida, hacer que la lógica de la política sea más transparente y explicable para el usuario.
La estabilidad, autenticidad y facilidad de uso de la estrategia, mediante la introducción de métodos algorítmicos como el aprendizaje automático y los modelos multifactoriales, son las principales mejoras que se obtendrán a partir de esta estrategia.
En general, la estrategia de seguimiento de tendencias del canal de la media móvil de envelopes combina los tres elementos centrales del seguimiento de tendencias de las medias móviles, el juicio de tendencias de los indicadores del canal y el control de riesgos de la línea de parada independiente. En un mercado de tendencia estricta, las estrategias de estrategias pueden ofrecer una implementación estable y con algunos beneficios de avance.
/*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")