Fractals de Williams combinados com o indicador ZZ para estratégias quantitativas de negociação

Autora:ChaoZhang, Data: 2024-01-29 15:24:30
Tags:

img

Resumo

Esta é uma estratégia de negociação quantitativa que combina o uso da teoria fractal de Bill Williams e o indicador ZZ. Ele julga as tendências do mercado através do cálculo dos fractals de Williams e identifica pontos de ruptura potenciais desenhando linhas de suporte / resistência usando o indicador ZZ para implementar negociações de tendência.

Princípio da estratégia

A estratégia primeiro calcula os fractais de Williams para determinar se o fractal atual está aumentando ou diminuindo. Se for um fractal crescente, acredita-se que a tendência atual é ascendente.

Em seguida, desenha as linhas de suporte e resistência do indicador ZZ com base nos pontos do fractal. Se o preço atravessar a linha de resistência correspondente ao fractal crescente, vá longo. Se o preço atravessar a linha de suporte correspondente ao fractal em queda, vá curto.

Através de tal combinação, é possível captar as mudanças das tendências em tempo útil e implementar transações seguindo a tendência.

Análise das vantagens

Esta estratégia combina dois métodos de análise técnica diferentes - fractais de Williams e indicadores ZZ - para descobrir mais oportunidades de negociação.

O indicador ZZ pode filtrar algumas falhas para evitar perdas desnecessárias.

Em geral, esta estratégia considera tanto o julgamento da tendência como as seleções específicas de pontos de entrada para equilibrar riscos e retornos.

Análise de riscos

O maior risco desta estratégia é que os julgamentos fractais e o indicador ZZ possam emitir sinais de negociação errados, levando a perdas desnecessárias.

Além disso, a forma como os fractais são calculados pode levar a julgamentos errôneos se o prazo for definido incorretamente.

Para reduzir estes riscos, ajustar adequadamente os parâmetros de cálculo dos fractais e aumentar as condições de filtragem para reduzir os sinais errôneos.

Orientações de otimização

Esta estratégia pode ser melhorada nos seguintes aspectos:

  1. Adicionar filtros de indicadores de impulso, como MACD ou Bollinger Bands para evitar algumas falhas.

  2. Otimizar as definições dos parâmetros fractais e ajustar o cálculo dos máximos e mínimos e encurtar o período de tempo para obter julgamentos de tendência mais precisos.

  3. Aumentar os algoritmos de aprendizagem de máquina para julgar a precisão da tendência e evitar limitações humanas.

  4. Adicionar um mecanismo adaptativo de stop loss baseado na volatilidade do mercado.

  5. Usar algoritmos de aprendizagem profunda para otimizar as configurações gerais de parâmetros.

Resumo

Ao combinar habilmente a teoria fractal de Williams e o indicador ZZ, esta estratégia consegue a detecção e captura oportunas de mudanças nas tendências do mercado.


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

//@version=4
strategy(title = "robotrading ZZ-8 fractals", shorttitle = "ZZ-8", overlay = true, default_qty_type = strategy.percent_of_equity, initial_capital = 100, default_qty_value = 100, commission_value = 0.1)

//Settings
needlong  = input(true, defval = true, title = "Long")
needshort = input(false, defval = true, title = "Short")
filterBW = input(false, title="filter Bill Williams Fractals")
showll = input(true, title = "Show levels")
showff = input(true, title = "Show fractals (repaint!)")
showdd = input(true, title = "Show dots (repaint!)")
showbg = input(false, title = "Show background")
showlb = input(false, title = "Show drawdown")
startTime = input(defval = timestamp("01 Jan 2000 00:00 +0000"), title = "Start Time", type = input.time, inline = "time1")
finalTime = input(defval = timestamp("31 Dec 2099 23:59 +0000"), title = "Final Time", type = input.time, inline = "time1")

//Variables
loss = 0.0
maxloss = 0.0
equity = 0.0
truetime = true

//Fractals
isRegularFractal(mode) =>
    ret = mode == 1 ? high[4] < high[3] and high[3] < high[2] and high[2] > high[1] and high[1] > high[0] : mode == -1 ? low[4] > low[3] and low[3] > low[2] and low[2] < low[1] and low[1] < low[0] : false
isBWFractal(mode) =>
    ret = mode == 1 ? high[4] < high[2] and high[3] <= high[2] and high[2] >= high[1] and high[2] > high[0] : mode == -1 ? low[4] > low[2] and low[3] >= low[2] and low[2] <= low[1] and low[2] < low[0] : false
filteredtopf = filterBW ? isRegularFractal(1) : isBWFractal(1)
filteredbotf = filterBW ? isRegularFractal(-1) : isBWFractal(-1)

//Triangles
plotshape(filteredtopf and showff, title='Filtered Top Fractals', style=shape.triangledown, location=location.abovebar, color= color.red, offset=-2)
plotshape(filteredbotf and showff, title='Filtered Bottom Fractals', style=shape.triangleup, location=location.belowbar, color= color.lime, offset=-2)

//Levels
hh = 0.0
ll = 0.0
hh := filteredtopf ? high[2] : hh[1]
ll := filteredbotf ? low[2] : ll[1]

//Trend
trend = 0
trend := high >= hh[1] ? 1 : low <= ll[1] ? -1 : trend[1]

//Lines
hcol = showll and hh == hh[1] and close < hh ? color.lime : na
lcol = showll and ll == ll[1] and close > ll ? color.red : na
plot(hh, color = hcol)
plot(ll, color = lcol)

//Dots
// var line hline = na
// if hh != hh[1] and showdd
//     hline := line.new(bar_index - 0, hh[0], bar_index - 2, hh[0], xloc = xloc.bar_index, extend = extend.none, style = line.style_dotted, color = color.lime, width = 1)
// var line lline = na
// if ll != ll[1] and showdd
//     lline := line.new(bar_index - 0, ll[0] - syminfo.mintick, bar_index - 2, ll[0] - syminfo.mintick, xloc = xloc.bar_index, extend = extend.none, style = line.style_dotted, color = color.red, width = 1)
    
//Background
bgcol = showbg == false ? na : trend == 1 ? color.lime : trend == -1 ? color.red : na
bgcolor(bgcol, transp = 80)

//Orders
if hh > 0 and needlong
    strategy.entry("Long", strategy.long, na, stop = hh, when = needlong and truetime)
    strategy.exit("Exit Long", "Long", stop = ll, when = needshort == false)
if ll > 0 and startTime
    strategy.entry("Short", strategy.short, na, stop = ll, when = needshort and truetime)
    strategy.exit("Exit Short", "Short", stop = hh, when = needlong == false)
if time > finalTime
    strategy.close_all()
    strategy.cancel("Long")
    strategy.cancel("Short")

if showlb

    //Drawdown
    max = 0.0
    max := max(strategy.equity, nz(max[1]))
    dd = (strategy.equity / max - 1) * 100
    min = 100.0
    min := min(dd, nz(min[1]))
    
    //Max loss size
    equity := strategy.position_size != strategy.position_size[1] ? strategy.equity : equity[1]
    loss := equity < equity[1] ? ((equity / equity[1]) - 1) * 100 : 0
    maxloss := min(nz(maxloss[1]), loss)
    
    //Label
    min := round(min * 100) / 100
    maxloss := round(maxloss * 100) / 100
    labeltext = "Drawdown: " + tostring(min) + "%" + "\nMax.loss " + tostring(maxloss) + "%"
    var label la = na
    label.delete(la)
    tc = min > -100 ? color.white : color.red
    osx = timenow + round(change(time)*50)
    osy = highest(100)
    la := label.new(x = osx, y = osy, text = labeltext, xloc = xloc.bar_time, yloc = yloc.price, color = color.black, style = label.style_labelup, textcolor = tc)

Mais.