Estratégia de Crossover de Média Móvel de Momentum


Data de criação: 2023-09-21 21:29:22 última modificação: 2023-09-21 21:29:22
cópia: 1 Cliques: 596
1
focar em
1617
Seguidores

Visão geral

Esta estratégia usa o princípio de cruzamento de médias móveis rápidas e médias móveis lentas para determinar a direção da tendência do mercado para emitir sinais de compra e venda. A estratégia é simples, fácil de entender e fácil de implementar, e aplica-se a negociações de linha curta e média.

Princípio da estratégia

A estratégia usa duas médias móveis, uma linha rápida e uma linha lenta. A linha rápida tem um EMA de 3 dias e a linha lenta tem um EMA de 15 dias. A estratégia julga que quando a linha rápida quebra a linha lenta a partir de baixo, é considerado um sinal de compra. Por outro lado, quando a linha rápida cai a partir de cima e quebra a linha lenta, é considerado um sinal de venda.

A estratégia também define um EMA de 3 dias com um parâmetro mais rápido como a linha de saída rápida. Quando o preço cai abaixo dessa linha de saída rápida, é determinado um reverso de tendência e deve sair da posição de multi-cabeça original. Da mesma forma, quando o preço re-quebrar a linha de saída, é re-transformado em um bullish e, portanto, é um sinal de reentrada.

A configuração de sinais de operação específica é a seguinte:

  1. A linha rápida vai de baixo para cima, a linha lenta vai de cima para cima, a linha rápida vai de baixo para cima.

  2. A linha rápida desce da linha lenta para cima e para baixo.

  3. Preço cai abaixo da linha de saída rápida, liquidação de ações

  4. Os preços voltaram a ultrapassar a linha de saída rápida e a fazer mais.

Vantagens estratégicas

  • Simples de usar, com apenas dois parâmetros de média móvel bem configurados, muito fácil de implementar

  • Os dados de retrospectiva são abundantes e os indicadores utilizados são mais comuns para avaliar a eficácia da estratégia

  • Há mais parâmetros configuráveis, que podem ser ajustados para otimizar a estratégia

  • O risco é melhor controlado com um Stop Loss de Movimento Rápido da Média

  • A estratégia é clara, os sinais de compra e venda são muito claros.

  • Frequência de operação moderada, evitando transações excessivamente frequentes

Risco estratégico

  • Como uma estratégia de acompanhamento de tendências, quando as tendências não são visíveis, são criados mais sinais falsos.

  • As médias móveis, por si só, são atrasadas e podem perder um ponto de viragem.

  • A configuração de parâmetros fixos não pode ser adaptada a mudanças no mercado, deve ser combinada com a utilização de parâmetros otimizados

  • A configuração de parada de perda pode ser muito fraca para parar a perda a tempo

  • Sinais de estratégia frequentes e custos de transação mais elevados

  • Os sinais de negociação podem ser desviados e devem ser confirmados em combinação com outros indicadores.

O risco pode ser controlado por meio de otimização de parâmetros, confirmação auxiliar com outros indicadores, relaxamento apropriado dos padrões de suspensão de perdas e atualização oportuna dos parâmetros.

Otimização de Estratégia

  • Pode testar e otimizar os parâmetros das médias móveis para que sejam mais adequados às características do mercado atual

  • Pode-se introduzir mais indicadores para combinação, formando um sistema de estratégias mais forte

  • Pode definir configurações de parâmetros adaptáveis, ajustando os parâmetros em tempo real de acordo com o mercado

  • Algoritmos de aprendizagem de máquina podem ser introduzidos para a otimização de estratégias mais inteligentes

  • Pode-se definir um stop-loss dinâmico e um stop-loss de rastreamento para melhor controlar o risco

  • Pode ser combinado com indicadores de quantidade de energia, evitando desvios que levam a erros de comando

Resumir

A estratégia global é uma estratégia simples de cruzamento de duas médias móveis. Utiliza a relação cruzada entre a média rápida e a média lenta para determinar a tendência do mercado e o momento de compra e venda. A vantagem da estratégia é que a ideia é clara, fácil de implementar e pode ser adaptada a diferentes mercados através da otimização de parâmetros.

Código-fonte da estratégia
/*backtest
start: 2023-01-01 00:00:00
end: 2023-02-03 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/
// © ehaarjee, ECHKAY, JackBauer007

//@version=4
//study(title="Tale_indicators", overlay=true)
strategy("Tale Indicators Strategy", overlay=true, precision=8, max_bars_back=200, pyramiding=0, initial_capital=20000, commission_type="percent", commission_value=0.1)

len_fast = input(3, minval=1, title="FAST EMA")
src_fast = input(close, title="Source for Fast")
fastMA = ema(src_fast, len_fast)
plot(fastMA, title="Slow EMA", color=color.orange)

len_slow = input(15, minval=1, title="SLOW EMA")
src_slow = input(close, title="Source for Slow")
slowMA = ema(src_slow, len_slow)
plot(slowMA, title="Fast EMA", color=color.blue)

len_fast_exit = input(3, minval=1, title="FAST EMA Exit")
src_fast_exit = input(close, title="Source for Fast Exit")
fastMAE = ema(src_fast_exit, len_fast_exit)
plot(fastMAE, title="Fast EMA Ex", color=color.red)


src_slow_enter_short = input(low, title="Source for Short Entry")
slowMASEn = ema(src_slow_enter_short, len_slow)

src_slow_enter_long = input(high, title="Source for Long Entry")
slowMALEn = ema(src_slow_enter_long, len_slow)

src_slow_exit_short = input(low, title="Source for Short Exit")
slowMASEx = ema(src_slow_enter_short, len_slow)

src_slow_exit_long = input(high, title="Source for Long Exit")
slowMALEx = ema(src_slow_enter_long, len_slow)

enter_long = crossover(fastMA, slowMALEn)
enter_short = crossunder(fastMA, slowMASEn)
exit_long = crossunder(fastMAE, slowMALEx)
exit_short = crossover(fastMAE, slowMALEx)

out_enter = iff(enter_long == true, 1, iff(enter_short == true, -1, 0))
plotarrow(out_enter, "Plot Enter Points", colorup=color.green, colordown=color.red, maxheight = 30)

bull = fastMA > slowMALEn
bear = fastMA < slowMASEn

c = bull ? color.green : bear ? color.red  : color.white
bgcolor(c)

exit_tuner = input(0.005, title="Exit Tuner to touch slowEMA")

bull_exit = (bull and (low>(fastMAE*(1+exit_tuner)))) or exit_long or (not(bear) and (fastMAE>high))
bear_exit = (bear and ((fastMAE*(1-exit_tuner))>high)) or exit_short or (not(bull) and (low>fastMAE))

bull_r = (bull and ((bull_exit[1]) or (bull_exit[2] and bull_exit[1])) and (low<=fastMAE))
bear_r = (bear and ((bear_exit[1]) or (bull_exit[2] and bull_exit[1])) and (fastMAE<=high))

bull_re = (bull and (low<slowMALEn)) and not(enter_long)
bear_re = (bear and (high>slowMASEn)) and not(enter_short)

bull_ree = (bull and ((low<slowMALEn) and not(bull_re[1] or enter_long[1]))) 
bear_ree = (bear and ((high>slowMASEn) and not(bear_re[1] or enter_short[1])))

bull_reenter =  (bull_r) and not(enter_long)
bear_reenter =  (bear_r) and not(enter_short)

plotshape(bull_exit, "Plot Bull Exit", style = shape.arrowdown, color=color.green, size=size.small, text="ExL", location=location.abovebar)
plotshape(bear_exit, "Plot Bear Exit", style = shape.arrowup, color=color.red, size=size.small, text="ExS", location=location.belowbar)

plotshape(bull_reenter, "Plot Bull ReEnter", style = shape.arrowup, color=color.green, size=size.small, text="ReL", location=location.belowbar)
plotshape(bear_reenter, "Plot Bear ReEnter", style = shape.arrowdown, color=color.red, size=size.small, text="ReS", location=location.abovebar)

run_strategy = input(true, title="Run Strategy")
// === INPUT BACKTEST RANGE ===
fromMonth = input(defval = 1,    title = "From Month",      type = input.integer, minval = 1, maxval = 12)
fromDay   = input(defval = 1,    title = "From Day",        type = input.integer, minval = 1, maxval = 31)
fromYear  = input(defval = 2020, title = "From Year",       type = input.integer, minval = 2000)
thruMonth = input(defval = 1,    title = "Thru Month",      type = input.integer, minval = 1, maxval = 12)
thruDay   = input(defval = 1,    title = "Thru Day",        type = input.integer, minval = 1, maxval = 31)
thruYear  = input(defval = 2100, title = "Thru Year",       type = input.integer, minval = 2000)

// === INPUT SHOW PLOT ===
showDate  = input(defval = true, title = "Show Date Range", type = input.bool)
// === FUNCTION EXAMPLE ===
start     = timestamp(fromYear, fromMonth, fromDay, 00, 00)        // backtest start window
finish    = timestamp(thruYear, thruMonth, thruDay, 23, 59)        // backtest finish window
window()  => true       // create function "within window of time"

var long_position_open = false
var short_position_open = false


if (enter_long and not(bull_exit) and not(long_position_open))
//    strategy.entry("LO", strategy.long, qty=4)
    long_position_open := true
    if (short_position_open)
//        strategy.close("SO")
        short_position_open := false

if (bull_reenter and not(long_position_open))  
//    strategy.entry("LO", strategy.long, qty=1)
    long_position_open := true

if (bull_exit and long_position_open)
//  strategy.close("LO")
    long_position_open := false
    
if (enter_short and not(bear_exit) and not(short_position_open))
//    strategy.entry("SO", strategy.short, qty=4)
    short_position_open := true
    if(long_position_open)
//        strategy.close("LO")
        long_position_open := false

if (bear_reenter and not(short_position_open))  
//    strategy.entry("SO", strategy.long, qty=1)
    long_position_open := true

if (bear_exit and short_position_open)
//    strategy.close("SO")
    short_position_open := false

if(run_strategy)
    strategy.entry("LO", strategy.long, when=(window() and enter_long), qty=4)
    strategy.entry("LO", strategy.long, when=(window() and bull_reenter and not(long_position_open)), qty=1)
    strategy.close("LO", when=(window() and bull_exit and long_position_open))
    strategy.entry("SO", strategy.short, when=(window() and enter_short), qty=4)
    strategy.entry("SO", strategy.short, when=(window() and bear_reenter and not(short_position_open)), qty=1)
    strategy.close("SO", when=(window() and bear_exit and short_position_open))