A combinação de banda de Bollinger e RSI com a estratégia DCA

Autora:ChaoZhang, Data: 2024-01-18 11:23:15
Tags:

img

Resumo

A estratégia é chamada Bollinger Band e RSI Mixing com DCA. Ela constrói sinais de negociação com base nos indicadores Bollinger Band e Relative Strength Index (RSI) e gerencia riscos usando a média progressiva de custos em dólares (DCA).

Princípio da estratégia

A estratégia integra os indicadores Bollinger Band e RSI. A banda de Bollinger julga claramente a tendência onde acima da banda média significa um mercado de touros e abaixo significa um mercado de ursos. O RSI indica situações de sobrecompra e sobrevenda. A estratégia constrói um indicador MIX ponderando o desvio da banda de Bollinger e o valor K do RSI. Um sinal longo é gerado quando o indicador MIX atravessa 20 a partir de baixo.

Para a parte DCA progressiva, uma posição inicial é aberta quando o MIX atravessa 20. Posições adicionais são adicionadas a um valor fixo toda vez que o preço cai por uma porcentagem fixa. Isso continua até que as posições máximas sejam alcançadas ou o stop loss / take profit seja ativado. Adicionando posições em mínimos de mercado várias vezes, o custo médio pode ser reduzido progressivamente.

Vantagens da estratégia

  1. A combinação de dois indicadores melhora a precisão do sinal através de um julgamento mais claro da tendência.

  2. O DCA progressivo reduz a base de custos durante os declínios, reduzindo o risco de perdas e aumentando a gama de lucros.

  3. As condições de captação de lucro e stop loss controlam prontamente os riscos e bloqueiam lucros parciais.

  4. O filtro de intervalo de datas adicionado permite backtests focados e otimizações de períodos específicos.

Riscos e soluções

  1. Tanto a banda de Bollinger quanto o RSI podem sofrer falhas. Diferentes combinações de parâmetros podem ser testadas para melhor precisão do sinal.

  2. O DCA progressivo pode aumentar as perdas durante grandes crashes adicionando continuamente posições.

  3. Os eventos de cisne negro e os movimentos anormais dos preços não podem ser previstos.

Orientações de otimização

  1. Teste e otimize os parâmetros do indicador MIX para obter sinais de negociação mais precisos.

  2. Otimizar os parâmetros de stop loss e take profit para melhor relação lucro/perda.

  3. Teste diferentes tamanhos e frequências de adição de posições para encontrar combinações ideais.

  4. Considerar a adição de módulos de controlo do volume de negociação à estratégia de abertura/fechamento baseada nas condições de volume.

Resumo

O Bollinger Band e RSI Mixing with DCA Strategy combina múltiplas técnicas e métodos quantitativos. Ele constrói um indicador de avaliação de tendência claro e reduz a base de custo através de adições progressivas. Métodos de controle de risco rigorosos, incluindo stop loss e take profit, tornam-no prático. Mais testes e otimizações podem desbloquear suas vantagens únicas em um sistema de negociação lucrativo.


/*backtest
start: 2023-01-11 00:00:00
end: 2024-01-17 00:00:00
period: 1d
basePeriod: 1h
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}]
*/

// © lagobrian23
//@version=4
strategy(title = 'Bollinger Bands and RSI mix with DCA', shorttitle = 'BB/RSI with DCA',pyramiding = 20, calc_on_every_tick = true, overlay = false )
source=close
smoothK = input(3, "K", minval=1)
smoothD = input(3, "D", minval=1)
lengthRSI = input(14, "RSI Length", minval=1)
lengthStoch = input(14, "Stochastic Length", minval=1)
src = input(close, title="RSI Source")
rsi1 = rsi(src, lengthRSI)
k = sma(stoch(rsi1, rsi1, rsi1, lengthStoch), smoothK)
d = sma(k, smoothD)

// Bollinger Band

length = input(20,title = 'BB lookback length', minval=1)
mult = input(2.0, minval=0.001, maxval=50, title="StdDev")
basis = sma(src, length)
dev = mult * stdev(src, length)
upper = basis + dev
lower = basis - dev
BBval = (src - basis)/dev*30+50
offset = input(0, title = "Offset", type = input.integer, minval = -500, maxval = 500)
mix=(d + BBval)/2

//plot
//plot(k, "K", color=#606060)
plot(BBval, "BBval", color=#872323, offset = offset)
plot(d, "D", color=#FF6A00)
h0 = hline(80, "Upper Band", color=#606060)
h1 = hline(20, "Lower Band", color=#606060)
plot(mix, "MIX", color=#888888, linewidth=3)

//background MIX
bgcolor(mix < 20 ? color.green : color.white, transp=50)
bgcolor(mix > 80 ? color.red : color.white, transp=50)

// Choosing the date 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 = 1970)
toMonth = input(defval = 1,    title = "To Month",      type = input.integer, minval = 1, maxval = 12)
toDay   = input(defval = 1,    title = "To Day",        type = input.integer, minval = 1, maxval = 31)
toYear  = input(defval = 2112, title = "To Year",       type = input.integer, minval = 1970)

start     = timestamp(fromYear, fromMonth, fromDay, 00, 00)        // backtest start window
finish    = timestamp(toYear, toMonth, toDay, 23, 59)        // backtest finish window
window()  => true

// Initializing the strategy paraeters

P = input(defval = 1, title = 'Amount (P)' , type = input.integer, minval = 1, maxval = 100)
X = input(defval = 2, title = '% Price drop for consecutive entries(X)', type = input.float, minval = 1, maxval = 100)
B_tp = input(defval = 10, title = '% Level for Take Profit (B)', type = input.float , minval = 1, maxval = 100)
D_sl = input(defval = 10, title = '% Level for Stop Loss (D)', type = input.float, minval = 1, maxval = 100)
A = input(defval = 5, title = 'Max consecutive entries (A)', type = input.integer, minval = 2, maxval = 20)
Z = input(defval = 0.5, title = 'Z', type = input.float , minval = 0, maxval = 10)

// Declaring key DCA variables
entry_price = 0.0
entry_price := na(entry_price[1]) ? na : entry_price[1]
new_entry = 0.0
consec_entryCondition = false
// Implementing the strategy
longEntry = crossover(mix,20)
exitLongs = crossunder(mix, 80)

if(longEntry)
    entry_price := close
    strategy.entry('main_LE', strategy.long , P, when = window() and longEntry)

// Exiting conditions
stoploss = strategy.position_avg_price*(1-(D_sl/100))
takeprofit = strategy.position_avg_price*(1+(B_tp/100))
slCondition = crossunder(close, stoploss)
tpCondition = crossover(close, takeprofit)

// We want to exit if the 'mix' indicator crosses 80, take profit is attained or stop loss is tagged.
exitConditions = exitLongs or slCondition or tpCondition

// Consecutive entries upto A times
// strategy.risk.max_intraday_filled_orders(A)

//Dollar-Cost-Averaging
// Enter long whenever price goes down X%: amount set to (P+Y)*Z
newAmount = (P+X)*Z
// If we haven't reached max open trades, buy newAmount immediately price crosses under X% lower the previous entry price
new_entry := entry_price - ((X/100)*entry_price)
consec_entryCondition := crossunder(close, new_entry)
if(consec_entryCondition and strategy.opentrades != A)
    strategy.entry('consec_LE', strategy.long, newAmount, oca_name = 'consecLongs', when = window() and consec_entryCondition)
    entry_price := close
    
// Exiting
// The main trade is closed only when the  main exit conditions are satisfied
strategy.close('main_LE', comment = 'Main Long Closed', when = window() and exitConditions)

// A consective long is closed only when tp or sl is tagged
strategy.exit('ext a consec', 'consec_LE', loss = D_sl*strategy.position_avg_price , profit = B_tp*strategy.position_avg_price, oca_name =  'consecLongs')


Mais.