Média móvel dupla com estratégia de ruptura de impulso

Autora:ChaoZhang, Data: 2024-02-06 14:39:22
Tags:

img

Resumo

Esta estratégia usa a cruz de ouro da EMA de 12 dias e da EMA de 26 dias como sinal de entrada. Para filtrar falhas, o MACD é aplicado para julgar a tendência do mercado e o RSI para níveis de sobrecompra / sobrevenda. A quebra de preço acima da resistência também é usada como confirmação.

A estratégia fornece três métodos opcionais de stop loss: trailing stop loss, moving average stop e moving average crossover stop.

Estratégia lógica

  1. Sinal de entrada
    • Cruzamento entre a EMA de 12 dias e a EMA de 26 dias
    • O MACD é positivo e a linha MACD acima da linha de sinal
    • RSI dentro do intervalo pré-definido
  2. Confirmação de entrada
    • Opcional: quebra de preço acima da resistência dinâmica
  3. Parar de Perder
    • Preço de entrada e percentagem pré-estabelecidas
    • Fechar abaixo da SMA de 7 dias
    • Cruzamento de baixa entre a EMA de 12 e 26 dias
  4. Aproveite
    • Dois objetivos de lucro em fases, saída parcial da posição no primeiro alvo e todos no segundo

Vantagens

  1. O sistema MA filtra os falsos sinais, melhora a precisão de entrada
  2. Opções de stop loss múltiplas para diferentes tipos de operadores
  3. Riscos relacionados com o controlo dinâmico da parada de tracção
  4. Tirar lucro em etapas fechar em algum lucro

Riscos

  1. Mais sinais falsos quando oscila o mercado
  2. A paragem traseira pode ser penetrada após uma corrida forte.
  3. Não sair em tempo hábil da inversão da tendência

Soluções:

  1. Use o MACD para julgar a tendência real
  2. Ajuste da percentagem de atraso
  3. Usar outros métodos de paragem ou combinar paradas

Reforço

  1. Otimizar os parâmetros de MA para melhor desempenho
  2. Teste diferentes paragens e encontre o melhor método
  3. Ajustar os níveis de lucro para uma melhor recompensa
  4. Adicionar filtros com outros indicadores
  5. Personalizar para diferentes produtos e prazos

Conclusão

A estratégia usa o sistema MA para o sinal de entrada, com filtros adicionais por MACD, RSI etc. Ambas as paradas e metas de lucro são otimizadas para combinar diferentes estilos de comerciante.


/*backtest
start: 2023-01-30 00:00:00
end: 2024-02-05 00:00:00
period: 1d
basePeriod: 1h
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/
// © AbdulRahimShama
//@version=5


strategy('12/26-IT strategy', overlay=true,initial_capital = 100000)



Show_Only_12_26_Crossover_Entry = input.bool(true, group = "Entry_Exit Criteria")
Show_12_26_Crossover_and_resistance_Entry = input.bool(false, group = "Entry_Exit Criteria")


Show_TSL_StopLoss = input.bool(true, group = "Entry_Exit Criteria")
Show_Crossdown_StopLoss = input.bool(true, group = "Entry_Exit Criteria")
Show_SMA7_StopLoss = input.bool(false, group = "Entry_Exit Criteria")



////////////////////////////////////////////////
////////////////TARGETS INPUT
////////////////////////////////////////////////

////////Target1

TargetPerc1 = input.float(title="Target (%)", minval=0,defval=5, group="Target-1") / 100
TargetPrice1 = strategy.position_avg_price * (1 + TargetPerc1)
Target1_exit_qty = input.int(50, group="Target-1",tooltip = "% qty to sell when Target1 is reached")



////////Target2

TargetPerc2 = input.float(title="Target (%)", minval=0,defval=10, group="Target-2") / 100
TargetPrice2 = strategy.position_avg_price * (1 + TargetPerc2)
Target2_exit_qty = input.int(100, group="Target-2",tooltip = "% qty to sell when Target2 is reached")



////////////////////////////////////////////////
////////////////TRAILING STOP LOSS
////////////////////////////////////////////////


TSLsource = input(low, title="TSL Source", group="Trailing StopLoss")

longTrailPerc = input.float(title='Trail Long Loss (%)', minval=0.0, step=0.1, defval=1, group="Trailing StopLoss") * 0.01

TrailStopPrice = 0.0

TrailStopPrice := if strategy.position_size > 0
    sPIVOT_highValue = TSLsource * (1 - longTrailPerc)
    math.max(sPIVOT_highValue, TrailStopPrice[1])
else
    0

TSL = close < TrailStopPrice
plot(series=strategy.position_size > 0 and Show_TSL_StopLoss ? TrailStopPrice : na, color=color.new(color.fuchsia, 0), style=plot.style_linebr, linewidth=2, title='Trailing StopLoss')




////////////////////////////////////////////////
////////////////Moving Averages
////////////////////////////////////////////////



EMA_12=ta.ema(close, 12)
EMA_26=ta.ema(close, 26)
EMA_21=ta.ema(close,21)

plot(EMA_12, title="EMA_12", color=color.rgb(0, 255, 0), offset=0, linewidth=1)
plot(EMA_26, title="EMA_26", color=color.rgb(0, 0, 255), offset=0, linewidth=1)
plot(Show_SMA7_StopLoss ? ta.sma(close,7) : na, title="SMA_7", color=color.rgb(255, 0, 0), offset=0, linewidth=1)



////////////////////////////////////////////////
////////////////RESISTANCE INPUT and PLOTTING
////////////////////////////////////////////////

CrossOverLookbackCandles = input.int(10, group= "RESISTANCE")

resistanceSRC = input(high, group= "RESISTANCE")
resistanceLEFT = input(10, group= "RESISTANCE")
resistanceRIGHT = input(10, group= "RESISTANCE")

hih = ta.pivothigh(resistanceSRC, resistanceLEFT, resistanceRIGHT)
top = ta.valuewhen(hih, resistanceSRC[resistanceRIGHT], 0)

res = plot(top, color=top != top[1] ? na : color.new(#00ff00, 50), offset=-resistanceLEFT, linewidth=2, title="Resistance Line")

EMA_12_Low = ta.lowest(EMA_12, CrossOverLookbackCandles)
EMA_26_Low = ta.lowest(EMA_26, CrossOverLookbackCandles)


////////////////////////////////////////////////
////////////////RSI INPUT and PLOTTING
////////////////////////////////////////////////
RSI = ta.rsi(close, 14)
RSILowerRange = input.int(50, tooltip = "RSI value should be ABOVE this value for entry", group = "RSI")
RSIUpperRange = input.int(70, tooltip = "RSI value should be BELOW this value for entry", group = "RSI")



////////////////////////////////////////////////
////////////////MACD
////////////////////////////////////////////////
fast_length = 12
slow_length = 26
MACD_src = close
signal_length = 9

fast_ma = ta.ema(MACD_src, fast_length)
slow_ma = ta.ema(MACD_src, slow_length)
macd = fast_ma - slow_ma
signal = ta.ema(macd, signal_length)
hist = macd - signal



////////////////////////////////////////////////
////////////////ENTRY CRITERIA
////////////////////////////////////////////////


BUYVALUE= input(100000, tooltip = "Buy qty displayed on chart will be based on this value")

BASEENTRY = macd > signal and RSI > RSILowerRange and RSI < RSIUpperRange and close > EMA_21 and close > ta.sma(close, 7)


Entry= ta.crossover(EMA_12, EMA_26) and BASEENTRY
Entry2 = ta.crossover(close, top) and EMA_12_Low < EMA_26_Low and EMA_12 > EMA_26 and RSI < 70

////////////////////////////////////////////////
////////////////BUY SELL STRATEGY
////////////////////////////////////////////////

if ((Entry and Show_Only_12_26_Crossover_Entry))
    strategy.entry("buy", strategy.long, qty=BUYVALUE/close)

if (Entry2 and Show_12_26_Crossover_and_resistance_Entry)
    strategy.entry("buy", strategy.long, qty=BUYVALUE/close)

strategy.exit("Tg1", "buy", limit=TargetPrice1, qty_percent = Target1_exit_qty)
strategy.exit("Tg2", "buy", limit=TargetPrice2, qty_percent = Target2_exit_qty)



if TSL and Show_TSL_StopLoss and close < EMA_12 
    strategy.close_all ("sl")

if ta.crossunder(EMA_12, EMA_26) and Show_Crossdown_StopLoss
    strategy.close_all ("sl")

if ta.crossunder(close, ta.sma(close, 7)) and Show_SMA7_StopLoss
    strategy.close_all ("sl")




Mais.