Estratégia de negociação baseada no canal Donqi stepwise multi-escala


Data de criação: 2024-02-27 14:57:37 última modificação: 2024-02-27 14:57:37
cópia: 0 Cliques: 657
1
focar em
1617
Seguidores

Estratégia de negociação baseada no canal Donqi stepwise multi-escala

Visão geral

Esta é uma estratégia de negociação que usa um canal de tangas em várias escalas de tempo para determinar os pontos de entrada e saída. A principal idéia da estratégia é: determinar a direção da tendência em escalas de tempo mais longas e encontrar o momento de entrada; determinar a reversão da tendência em escalas de tempo mais curtas e encontrar o momento de saída.

Princípio da estratégia

A estratégia utiliza principalmente o conceito de um canal de tangas. O canal de tangas é formado por linhas ao longo do canal superior, inferior e médio. A largura do canal varia com a escala de tempo.

  1. Construindo um túnel de 52 ciclos em uma escala de tempo mais longa, obtendo uma linha superior, inferior e central do túnel
  2. Construir um canal de tangas em menor escala de tempo usando 12 ciclos, obtendo linhas de topo, baixo e centro do canal

Lógica de entrada: quando o preço quebra o topo de um canal de escala de tempo mais longo, é considerado um momento de entrada múltipla. Para evitar falsas rupturas, exigimos que pelo menos uma das três linhas K mais recentes tenha um preço de fechamento de linha K superior ao topo do canal dessa linha K, evitando assim falsas rupturas causadas por excesso de expansão de curto prazo.

A lógica de saída: quando o preço cai abaixo do corredor de uma escala de tempo mais curta, é hora de sair da posição. Também exigimos que pelo menos um dos três últimos K-lines tenha um preço de fechamento de K-line abaixo do corredor abaixo do corredor de K-line, para que a eficácia da ruptura possa ser confirmada e evitar a captura.

Vantagens estratégicas

  1. A estratégia combina os benefícios de acompanhamento de tendências e negociação de reversão. A escala de tempo mais longo determina a direção da tendência e a escala de tempo mais curta determina a reversão local. A combinação de ambos permite capturar a oscilação local na tendência.

  2. O uso de análises em várias escalas de tempo pode ajudar a lidar melhor com o problema de brechas falsas, tornando as entradas e saídas mais claras e eficazes.

  3. Otimizando os parâmetros, pode ser adaptado a diferentes variedades e ambientes de mercado.

Riscos e soluções

  1. A estratégia é sensível a parâmetros, e diferentes parâmetros podem ter resultados completamente diferentes. Otimizar com testes completos é necessário para encontrar a melhor combinação de parâmetros.

  2. Em situações de turbulência, a estratégia pode gerar uma grande quantidade de sinais de negociação, resultando em excesso de negociação. A perda individual pode ser controlada através da configuração de stop loss.

  3. A estratégia não leva em conta a lógica de julgamento de tendências em grande escala, podendo falhar no ponto de conversão de ativos e perdas. Pode ser combinada com outros indicadores para julgar a tendência em grande escala.

Direção de otimização

  1. Optimizar os parâmetros para encontrar a melhor combinação de parâmetros. Parâmetros como duração do ciclo de otimização, tipo de canal.

  2. Aumentar a lógica de stop loss. Configurar um stop loss móvel razoável e controlar a perda individual.

  3. Combinado com outros indicadores para determinar tendências de grande escala. Por exemplo, EMA, K Line Channel, MAC, etc. Evite falhas em pontos críticos de mudança.

Resumir

A estratégia em geral é uma típica estratégia de ruptura de canal em várias escalas temporais. Combina bem os benefícios do acompanhamento de tendências e do comércio de reversão, capturando oscilações locais na tendência com o julgamento de canais em diferentes escalas temporais. Se os parâmetros estiverem otimizados, a eficácia é excelente em mercados com tendências evidentes.

Código-fonte da estratégia
/*backtest
start: 2023-02-20 00:00:00
end: 2024-02-26 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/
// © venkyrocker7777

//@version=5

strategy('Donchain channel based investment strategy', shorttitle='Donchain channel strategy', overlay=true)

Length = input.int(21, minval=1)
xPrice = close
xvnoise = math.abs(xPrice - xPrice[1])
nAMA = 0.0
nfastend = 0.666
nslowend = 0.0645
nsignal = math.abs(xPrice - xPrice[Length])
nnoise = math.sum(xvnoise, Length)
nefratio = nnoise != 0 ? nsignal / nnoise : 0
nsmooth = math.pow(nefratio * (nfastend - nslowend) + nslowend, 2)
nAMA := nz(nAMA[1]) + nsmooth * (xPrice - nz(nAMA[1]))
plot(nAMA, color=color.new(color.blue, 0), title='KAMA')

// Function to get Lower Channel, Upper Channel, Middle Channel for a period length
getLCUCMC(PeriodLength) =>
    lowestValueInThePeriod = ta.lowest(PeriodLength)  // LC
    highestValueInThePeriod = ta.highest(PeriodLength)  // UC
    middleChannelInTheperiod = math.avg(highestValueInThePeriod, lowestValueInThePeriod)  // MC
    // Returns Lower Channel, Upper Channel, Middle Channel for a period length
    [lowestValueInThePeriod, highestValueInThePeriod, middleChannelInTheperiod]

// Longer time frame for entry
longerPeriod = 52

// Shorter time frame for exit
shorterPeriod = 12

if timeframe.period == 'D'
    // Longer time frame for entry
    longerPeriod := 52 * 5

    // Shorter time frame for exit
    shorterPeriod := 12 * 5
    shorterPeriod

if timeframe.period == 'M'
    // Longer time frame for entry
    longerPeriod := 12

    // Shorter time frame for exit
    shorterPeriod := 3
    shorterPeriod

// Get Lower Channel, Upper Channel, Middle Channel for longerPeriod, shorterPeriod
[lowestValueInTheLongerPeriodLength, highestValueInTheLongerPeriodLength, middleChannelInLongerperiod] = getLCUCMC(longerPeriod)
[lowestValueInTheShorterPeriodLength, highestValueInTheShorterPeriodLength, middleChannelInShorterperiod] = getLCUCMC(shorterPeriod)


// Plot Upper Channel of longerPeriod in dark green
plot(highestValueInTheLongerPeriodLength, 'highestValueInTheLongerPeriodLength', color=color.new(color.green, 0))

// Plot Lower Channel of shorterPeriod in dark red
plot(lowestValueInTheShorterPeriodLength, 'lowestValueInTheShorterPeriodLength', color=color.new(color.red, 0))

// Entry Plan
// Will start to see if we can enter when high crosses up longer period high (high >= highestValueInTheLongerPeriodLength)
// Check if any of the three past candles and enter when any of the 3 past candles satisfy
// 1) high of that candle >= highestValueInTheLongerPeriodLength of that candle (high[i] >= highestValueInTheLongerPeriodLength[i])
// 2) close of entry point consideration candle is above close of that candle (close > close[i])
isThisPointAnEntry() =>
// Check last 3 bars
    isThisPointAnEntry = false
    offset = 0
    for i = 1 to 3 by 1
        isCurrentCandleALongerPeriodHigh = high >= highestValueInTheLongerPeriodLength
        isCurrentCandleCloseGreaterThanPreiousIthOne = close > close[i]
        isPreviousIthCandleAlsoALongerPeriodHigh = high[i] >= highestValueInTheLongerPeriodLength[i]
        isThisPointAnEntry := isCurrentCandleALongerPeriodHigh and isCurrentCandleCloseGreaterThanPreiousIthOne and isPreviousIthCandleAlsoALongerPeriodHigh
        if isThisPointAnEntry
            offset := -i
            break
    [isThisPointAnEntry, offset]

// Exit Plan - same as entry plan, with things reversed and also on a shorter time frame
// Will start to see if we should exit when low crosses down longer period low (low <= lowestValueInTheShorterPeriodLength)
// Check if any of the three past candles and exit when any of the 3 past candles satisfy
// 1) low of that candle <= highestValueInTheLongerPeriodLength of that candle (low[i] <= lowestValueInTheShorterPeriodLength[i])
// 2) close of exit point consideration candle is below close of that candle (close < close[i])
isThisPointAnExit() =>
// Check last 3 bars
    isThisPointAnExit = false
    for i = 1 to 3 by 1
        isCurrentCandleAShorterPeriodLow = low <= lowestValueInTheShorterPeriodLength
        isCurrentCandleCloseLesserThanPreiousIthOne = close < close[i]
        isPreviousIthCandleAlsoAShorterPeriodLow = low[i] <= lowestValueInTheShorterPeriodLength[i]
        isThisPointAnExit := isCurrentCandleAShorterPeriodLow and isCurrentCandleCloseLesserThanPreiousIthOne and isPreviousIthCandleAlsoAShorterPeriodLow
        break
    isThisPointAnExit

[isEntry, offset] = isThisPointAnEntry()


if isEntry
    strategy.entry('Buy', strategy.long)

strategy.close_all(when=isThisPointAnExit() == true)

if year(timenow) == year(time) and month(timenow) == month(time) and dayofmonth(timenow) - 2 == dayofmonth(time)
    strategy.close_all()