Tendência do canal da média móvel de envelopes seguindo a estratégia

Autora:ChaoZhang, Data: 2023-11-23 15:06:32
Tags:

img

Resumo

A estratégia de seguimento de tendência do canal de média móvel é uma estratégia de seguimento de tendência baseada em linhas de média móvel e indicadores de canal. Realiza o julgamento e o rastreamento das tendências de preços estabelecendo um canal de média móvel de vários níveis. A estratégia também combina cálculos de média móvel de diferentes prazos para alcançar fusão de vários prazos, o que ajuda a capturar tendências maiores.

Estratégia lógica

O princípio central desta estratégia é baseado na funcionalidade de rastreamento de tendências das linhas de média móvel e no julgamento do canal dos indicadores de Envelope. A estratégia usa parâmetros configuráveis, como período de média móvel, tipo suave, fonte de preço, etc., para construir uma média móvel de linha de base. Em seguida, os canais para cima e para baixo são estabelecidos de acordo com os valores de mudança percentual definidos pelos parâmetros. Quando o preço atravessa o canal inferior, vá longo; quando o preço atravessa o canal superior, vá curto. Ao mesmo tempo, a estratégia introduz uma média móvel independente como a linha de stop loss.

Em especial, a estratégia apresenta as seguintes características:

  1. Apoiar operações longas e curtas, julgar a direção da tendência através de canais para cima e para baixo.

  2. Abrir até 4 ordens, implementar a abertura de ordem piramidal através de camadas de polilineia para buscar maiores lucros.

  3. Configurar a média móvel de abertura e a média móvel de fechamento independentes para obter uma perda de parada precisa.

  4. Suporte ao cálculo da média móvel de diferentes prazos (1 minuto a 1 dia) para alcançar a fusão de vários prazos.

  5. As médias móveis de abertura e fechamento suportam a selecção de 6 modos de suavização diferentes, que podem ser otimizados para diferentes variedades e ciclos.

  6. Os deslocamentos positivos e negativos podem ser inseridos para ajustar os canais e buscar avanços mais precisos.

A lógica de negociação específica da estratégia é a seguinte:

  1. Calcular a média móvel de abertura do índice de referência e obter 4 linhas de avanço de acordo com a percentagem de parâmetros definida.

  2. Quando o preço atravessa a linha inferior do canal, abrir posições para fazer long; quando o preço atravessa a linha superior do canal, abrir posições para fazer short.

  3. Calcule a média móvel de fechamento independente como linha de stop loss. Quando o preço cai abaixo da linha novamente, stop loss as ordens longas em camadas; quando o preço sobe acima da linha novamente, stop loss as ordens curtas em camadas.

  4. Pode-se abrir até 4 ordens. Use a abertura de ordens de pirâmide em camadas para obter maiores lucros.

Através do princípio desta estratégia, pode-se ver que a estratégia integra elementos como o acompanhamento da tendência das linhas de média móvel, sinais de ruptura do julgamento do canal e a definição de linhas de stop loss independentes para formar um sistema de tendência relativamente rigoroso e completo.

Análise das vantagens

De acordo com o código e a análise lógica, a média móvel envolve a tendência do canal seguindo a estratégia e tem as seguintes vantagens:

  1. A fusão multi-tempo melhora a probabilidade de capturar tendências de grande escala. A estratégia suporta o cálculo de médias móveis de diferentes ciclos de 1 minuto a 1 dia. Configurar médias móveis de abertura e stop-loss com diferentes ciclos alcança a fusão de poder de julgamento de tendências multi-tempo, o que é mais propício para capturar tendências de grande escala.

  2. O método de abertura de ordens piramidal busca maiores lucros. A estratégia pode abrir até 4 ordens. Por abertura de ordens em camadas, ele equilibra o rácio de lucro e busca maiores lucros enquanto controla os riscos.

  3. A média móvel de abertura e stop-loss suporta a seleção de 6 modos, incluindo SMA/EMA/Dynamic Moving Average, que podem ser otimizados para diferentes variedades e ciclos para melhorar a adaptabilidade.

  4. A estratégia permite a entrada de parâmetros de porcentagem de movimento do canal para ajustar a largura do canal para otimização para diferentes variedades ou ambientes de mercado, melhorando a precisão dos julgamentos de avanço.

  5. A estratégia calcula uma linha média móvel independente como a linha de fechamento para parar as ordens longas ou curtas, o que pode reduzir muito os riscos de negociação e evitar perseguir ordens perdedoras.

  6. A estrutura do código é clara e fácil de desenvolver em segundo lugar. A estratégia é escrita em Pine Script com estrutura clara e fácil de entender e desenvolver em segundo lugar. Os usuários podem continuar a otimizar parâmetros ou adicionar outra lógica com base na estrutura existente.

Análise de riscos

Embora a lógica geral da estratégia seja rigorosa e o controlo dos riscos esteja em vigor, ainda há alguns riscos comerciais a tomar em consideração, nomeadamente:

  1. Risco de reversão de tendência em larga escala. A suposição central da estratégia é que os preços continuarão a avançar de forma constante, com alguma tendência. No entanto, quando as tendências em larga escala se revertem, isso terá um impacto maior na lucratividade da estratégia. É necessário parar a perda a tempo para controlar as perdas.

  2. Risco de ruptura inválido. Em mercados laterais ou de choque, os preços podem cair abaixo da linha do canal após a ruptura, o que causará perseguição por perdas de ordens. Os parâmetros precisam ser otimizados para reduzir tais casos.

  3. A estratégia define 4 camadas de ordens de pirâmide para buscar maiores lucros, o que resulta em retornos significativos durante períodos de lucro, mas também uma queda acentuada nas expectativas durante períodos de perda.

  4. Risco de otimização de sinal. A estratégia envolve ajustes e otimizações em vários parâmetros, como largura de canal e ciclo médio móvel. Isso requer que os quants profissionais tenham experiência em otimização para evitar o sobreajuste.

  5. Condições especiais de risco de mercado: condições de mercado extremas, como brechas rápidas ou limites de linha curta, prejudicarão muito a lógica da estratégia, por isso é necessário prestar atenção às métricas de risco sistêmico para parar as perdas em tempo hábil.

Em geral, a estratégia baseia-se principalmente em ganhos de tendência em larga escala para a rentabilidade e só se aplica a variedades e ambientes de mercado com características de persistência a longo prazo.

Orientações de otimização

Para esta média móvel, a tendência do canal de envelope após a estratégia, as principais direções de otimização incluem:

  1. Optimização adaptativa de linhas de canal e linhas de stop loss com base em algoritmos de aprendizado de máquina.

  2. Incorporar fatores auxiliares como indicadores de sentimento, rácios de ponderação de carteira para otimizar a lógica da pirâmide.

  3. Introduzir modelos de custo de negociação e deslizamento para melhorar a autenticidade do backtesting.

  4. Expandir a análise de correlação em classes de ativos semelhantes para construir estruturas unificadas de controle de risco. Expandir a atual estratégia de ativo único para vários mercados semelhantes, como commodities e criptomoedas, e unificar o controle de risco através da análise de correlação para melhorar a estabilidade da estratégia.

  5. Use métodos como SHAP para analisar a importância de cada variável de entrada para os resultados da estratégia, classificações de importância de saída e tornar a lógica da estratégia mais transparente e interpretável para os usuários.

A introdução de algoritmos como o aprendizado de máquina e modelos multifatores para otimizar ainda mais a estabilidade, autenticidade e usabilidade da estratégia é a principal direção de melhoria para o futuro.

Resumo

Em resumo, a média móvel envolve a estratégia de tendência do canal, que integra três pontos-chave: rastreamento de tendência de médias móveis, identificação de indicadores de tendência do canal e linhas de stop loss independentes para controle de risco. Em mercados de tendência rigorosa, a estratégia pode fornecer retornos estáveis com uma quantidade razoável de tendência após lucro. Mas os usuários precisam prestar atenção aos ambientes de mercado macro, otimizar adequadamente os parâmetros e gerenciar os riscos, para que a estratégia possa se adaptar a mercados comerciais complexos e em constante mudança.


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

Mais.