Tendência após a estratégia de ruptura do canal com média móvel e parada de tração

Autora:ChaoZhang, Data: 2024-01-15 12:25:26
Tags:

img

Resumo

Esta é uma estratégia de ruptura baseada no canal de preços, combinada com indicadores de média móvel e stop/take profit para entrada e saída.

Estratégia lógica

A estratégia calcula as médias móveis de preços altos/baixos para formar um canal de preços. Especificamente, ele calcula o comprimento 10 SMA de preços altos/baixos para traçar a faixa superior e inferior do canal. Quando o preço rompe acima da faixa inferior para a faixa superior, ele entra em longo. Quando o preço rompe da faixa superior para a faixa inferior, ele entra em curto.

Após a entrada, a estratégia usa um stop loss fixo ou um trailing stop para sair. O trailing stop consiste em dois parâmetros: nível fixo de lucro e offset de ativação. Quando o preço atinge o offset de ativação, o nível de lucro começa a seguir o preço. Isso permite bloquear lucros mantendo algum espaço aberto.

A estratégia também combina o filtro de intervalo de tempo, executando apenas backtest dentro de um prazo histórico especificado, para testar o desempenho em diferentes estágios do mercado.

Análise das vantagens

A estratégia explora o canal de preços e a tendência seguindo com trailing stop, o que permite capturar direções de tendência de médio a longo prazo.

Em geral, a estratégia tem uma lógica clara, indicadores e parâmetros mínimos, fácil de testar, adequada para negociação de tendências de médio a longo prazo e pode lucrar com tendências fortes.

Análise de riscos

A estratégia tende a ser interrompida facilmente durante os mercados agitados, incapazes de sustentar lucros.

O ajustamento do parâmetro é bastante subjetivo, exigindo ajustes em diferentes estágios do mercado.

Oportunidades de melhoria

Outros indicadores como volume, Bandas de Bollinger podem ser incorporados para filtrar sinais de entrada, evitando armadilhas.

As regras de saída podem ser atualizadas para trailing stop ou Chandelier Exit. Objetivos de lucro parciais podem ser considerados quando o preço retorna ao canal. A otimização de filtros de entrada e regras de saída pode melhorar muito a estabilidade da estratégia.

Conclusão

Em resumo, esta é uma estratégia quantitativa baseada no canal de preço, seguimento da tendência, gerenciamento de stop loss / take profit. Tem fluxo lógico claro, estrutura de parâmetros simples, fácil de entender e backtest. É adequado para aprender conceitos de negociação algorítmica. A estratégia pode ser aprimorada em vários aspectos para melhorar a estabilidade e lucratividade. A ideia central é capturar a direção da tendência e gerenciar os riscos por meio de stop loss e take profit. Pode ser aplicada a vários produtos em diferentes prazos.


/*backtest
start: 2023-12-01 00:00:00
end: 2023-12-21 23:59:59
period: 3h
basePeriod: 15m
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}]
*/

//@version=3
strategy("Generalized SSL Backtest w/ TSSL", shorttitle="GSSL Backtest", overlay=true )
// Generalized SSL:
//  This is the very first time the SSL indicator, whose acronym I ignore, is on Tradingview. 
//  It is based on moving averages of the highs and lows. 
//  Similar channel indicators can be found, whereas 
//  this one implements the persistency inside the channel, which is rather tricky.
//  The green line is the base line which decides entries and exits, possibly with trailing stops.
//  With respect to the original version, here one can play with different moving averages.
//  The default settings are (10,SMA)
//
// Vitelot/Yanez/Vts March 2019

lb = input(10, title="Lb", minval=1)
maType = input( defval="SMA", title="MA Type", options=["SMA","EMA","HMA","McG","WMA","Tenkan"])

fixedSL = input(title="SL Activation", defval=300)
trailSL = input(title="SL Trigger", defval=1)
fixedTP = input(title="TP Activation", defval=150)
trailTP = input(title="TP Trigger", defval=1)

FromMonth = input(defval = 1, title = "From Month", minval = 1, maxval = 12)
FromDay   = input(defval = 1, title = "From Day", minval = 1, maxval = 31)
FromYear  = input(defval = 2019, title = "From Year", minval = 2017)
ToMonth   = input(defval = 6, title = "To Month", minval = 1, maxval = 12)
ToDay     = input(defval = 19, title = "To Day", minval = 1, maxval = 31)
ToYear    = input(defval = 2020, title = "To Year", minval = 2017)
start     = timestamp(FromYear, FromMonth, FromDay, 00, 00)  // backtest start window
finish    = timestamp(ToYear, ToMonth, ToDay, 23, 59)        // backtest finish window
startTimeOk()  => true // create function "within window of time" if statement true
// QUANDL:BCHAIN/ETRVU is USD-denominated daily transaction value on BTC blockchain
// QUANDL:BCHAIN/MKTCP is USD-denominated Bitcoin marketcap

hma(sig, n) => // Hull moving average definition
    wma( 2*wma(sig,round(n/2))-wma(sig,n), round(sqrt(n)))

mcg(sig,length) => // Mc Ginley MA definition
    mg = 0.0
    mg := na(mg[1]) ? ema(sig, length) : mg[1] + (sig - mg[1]) / (length * pow(sig/mg[1], 4))

tenkan(sig,len) =>
    0.5*(highest(sig,len)+lowest(sig,len))

ma(t,sig,len) =>
    sss=na
    if t =="SMA"
        sss := sma(sig,len)
    if t == "EMA"
        sss := ema(sig,len)
    if t == "HMA"
        sss := hma(sig,len)
    if t == "McG" // Mc Ginley
        sss := mcg(sig,len)
    if t == "Tenkan"
        sss := tenkan(sig,len)
    if t == "WMA"
        sss := wma(sig,len)
    sss

base(mah, mal) =>
    bbb = na
    inChannel = close<mah and close>mal
    belowChannel = close<mah and close<mal
    bbb := inChannel? bbb[1]: belowChannel? -1: 1
    uuu = bbb==1? mal: mah
    ddd = bbb==1? mah: mal
    [uuu, ddd]

maH = ma(maType, high, lb)
maL = ma(maType, low, lb)

[up, dn] = base(maH,maL)

plot(up, title="High MA", color=lime, linewidth=3)
plot(dn, title="Low MA", color=orange, linewidth=3)

long = crossover(dn,up)
short = crossover(up,dn)

// === STRATEGY - LONG POSITION EXECUTION ===
strategy.entry("Long", strategy.long, when= long and startTimeOk())
strategy.exit("Exit", qty_percent = 100, loss=fixedSL, trail_offset=trailTP, trail_points=fixedTP) 
strategy.exit("Exit", when= short)
// === STRATEGY - SHORT POSITION EXECUTION ===
strategy.entry("Short", strategy.short, when= short and startTimeOk())
strategy.exit("Exit", qty_percent = 100, loss=fixedSL, trail_offset=trailTP, trail_points=fixedTP)
strategy.exit("Exit", when= long)

Mais.