
A estratégia é baseada em um design de Kaufman Adapted Moving Average (KAMA), que permite ajustar dinamicamente as posições de negociação e acompanhar automaticamente as tendências do mercado. As principais funções da estratégia incluem:
Através do uso desses recursos, a estratégia tenta obter benefícios adicionais da tendência, enquanto controla os riscos.
A estratégia baseia-se no trabalho de Kaufman na adaptação do indicador de média móvel. A KAMA ajusta dinamicamente o peso e a suavidade da média, calculando o rácio de movimento e oscilação dos preços, de modo a responder mais rapidamente às mudanças de preço.
Quando o KAMA atravessa a linha de parada para baixo, a tendência é reversível, gerando um sinal de compra; quando o KAMA atravessa a linha de parada para baixo, a tendência é reversível, gerando um sinal de venda. Após entrar em posição, a estratégia calcula uma distância de parada dinâmica de acordo com o ATR e estabelece uma linha de parada. Quando o KAMA se move na direção vantajosa, a linha de parada também se ajusta, movendo a linha de parada para uma posição mais vantajosa para bloquear mais lucros.
Dessa forma, a estratégia pode seguir a tendência e mover a linha de parada gradualmente até que a linha de parada seja acionada ou o sinal de reversão seja acionado e a posição seja liquidada.
Em comparação com a estratégia de média móvel tradicional, a estratégia tem as seguintes vantagens:
Em geral, a estratégia é rápida, controlada e é uma estratégia típica de acompanhamento de tendências.
A estratégia também apresenta alguns riscos:
Estes riscos podem ser controlados por meio de métodos como a otimização da distância de parada, a configuração da porcentagem máxima de parada. Também pode ser combinado com outros indicadores como confirmação, evitando transações erradas.
A estratégia pode ser otimizada para:
Por exemplo, pode-se testar a adição de MACD como um indicador de confirmação auxiliar, ao mesmo tempo em que o KAMA Goldfork, também requer que o MACDDif também seja positivo e ampliado. Isso pode filtrar alguns sinais falsos e evitar aberturas de posição repetidas desnecessariamente.
Esta estratégia funciona bem como um todo, usando um stop loss dinâmico para acompanhar a tendência e maximizar o lucro da tendência. A adaptabilidade do indicador KAMA também permite que a estratégia acompanhe as mudanças rápidas do mercado. Com alguma otimização, a estratégia pode se tornar um programa de acompanhamento de tendências eficiente, adequado para operações de linha média e longa.
/*backtest
start: 2024-01-26 00:00:00
end: 2024-02-25 00:00:00
period: 1h
basePeriod: 15m
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}]
*/
//@version=5
strategy("THMA - Bharath Vc Improved", overlay=true, process_orders_on_close=true)
// Function to calculate pips with higher precision
getPips(price) =>
difc = syminfo.mintick
hlpips = price / difc
math.round(hlpips / syminfo.mintick) * syminfo.mintick
// Inputs
buyMess = input.string("Buy Message","Buy Alert Message")
sellMess = input.string("Sell Message","Sell Alert Message")
buyExitMessage = input.string("Buy Exit","Buy Exit Alert Message" )
sellExitMessage = input.string("Sell Exit","Sell Exit Alert Message" )
tmf = input.timeframe("", "Timeframe")
length = input(title='Length', defval=14)
fastLength = input(title='Fast EMA Length', defval=2)
slowLength = input(title='Slow EMA Length', defval=30)
src = input(title='Source', defval=close)
highlight = input(title='Highlight ?', defval=true)
awaitBarConfirmation = input(title='Await Bar Confirmation ?', defval=true)
// Function to calculate the TMA
gettma() =>
mom = math.abs(ta.change(src, length))
volatility = math.sum(math.abs(ta.change(src)), length)
er = volatility != 0 ? mom / volatility : 0
fastAlpha = 2 / (fastLength + 1)
slowAlpha = 2 / (slowLength + 1)
alpha = math.pow(er * (fastAlpha - slowAlpha) + slowAlpha, 2)
kama = 0.0
kama := alpha * src + (1 - alpha) * nz(kama[1], src)
await = awaitBarConfirmation ? barstate.isconfirmed : true
maColor = highlight ? kama > kama[1] and await ? color.green : color.red : color.new(color.purple, 0)
thma = kama
hma_dif = (thma - thma[2])/2
colour = hma_dif > 0 ? color.green : color.red
isGreen = hma_dif > 0
[thma, isGreen, colour]
// Dynamic pip size based on ATR to adapt better to smaller timeframes
pips = ta.atr(14) * 0.1
// Main execution logic
var float psl = na
var int lastSignal = 0
var float lastPsl = na
[thma, isGreen, colour] = request.security(syminfo.tickerid, tmf, gettma(), gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_off)
plot(thma, title='KAMA', linewidth=2, color=colour)
if ta.crossover(thma, psl) and strategy.position_size < 0
strategy.exit("Sell Exit", stop=thma, alert_message=sellExitMessage)
if ta.crossunder(thma, psl) and strategy.position_size > 0
strategy.exit("Buy Exit", stop=thma, alert_message=buyExitMessage)
if isGreen and strategy.position_size <= 0
if na(psl)
psl := close + getPips(pips)
strategy.entry("Buy", strategy.long, alert_message=buyMess)
lastSignal := 1
if not isGreen and strategy.position_size >= 0
if na(psl)
psl := close - getPips(pips)
strategy.entry("Sell", strategy.short, alert_message=sellMess)
lastSignal := -1
if (thma >= lastPsl or na(lastPsl)) and thma > psl
psl := psl + getPips(pips)
lastPsl := psl
if (thma <= lastPsl or na(lastPsl)) and thma < psl
psl := psl - getPips(pips)
lastPsl := psl
plot(psl, title="Position Stop Level", style=plot.style_stepline, color=color.blue)
plot(lastPsl, title="Last Position Stop Level", style=plot.style_cross, color=color.red)