
A ideia central desta estratégia é identificar tendências de mercado em combinação com vários períodos de tempo, usando indicadores de ultrapassagem em períodos de tempo mais elevados como filtros, emitindo sinais de compra e venda em períodos de tempo mais baixos. A estratégia visa usar informações sobre a estrutura do mercado fornecidas por períodos de tempo mais elevados para melhorar a qualidade das decisões de negociação.
A estratégia obteve o valor do indicador de ultrapassagem no quadro de tempo superior (default 4x o quadro de tempo atual) por meio da chamada da função security. O indicador de ultrapassagem inclui duas linhas: a linha de ultrapassagem e a linha de tendência. A linha de ultrapassagem é um sinal de otimismo quando está acima da linha de tendência e um sinal de baixa quando está abaixo.
A estratégia usa a direção do ultra-trend do período de tempo mais alto como condição de filtragem e só emite um sinal de negociação quando a direção do ultra-trend do período de tempo mais baixo coincide com a do período de tempo mais alto. Ou seja, a estratégia só faz mais ou menos quando os indicadores de ultra-trend em ambos os períodos de tempo emitem sinais homogêneos.
Isso evita a interferência do ruído do mercado de baixo período de tempo, aumentando a confiabilidade do sinal. Ao mesmo tempo, use o alto período de tempo para avaliar a estrutura do mercado e fazer o julgamento geral correto.
Solução:
A estratégia pode ser melhorada em vários aspectos:
Otimizando os parâmetros, combinando os indicadores, melhorando o stop loss e introduzindo a aprendizagem de máquina, pode-se aumentar significativamente a eficácia da estratégia de acompanhamento de tendências de múltiplos prazos.
Esta estratégia usa habilmente o discernimento de tendências em quadros de tempo altos para orientar a execução de transações em quadros de tempo baixos. Esta concepção de quadros de tempo múltiplos pode filtrar efetivamente o ruído do mercado e identificar a direção da tendência com mais clareza.
/*backtest
start: 2023-02-14 00:00:00
end: 2024-02-20 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/
// © HeWhoMustNotBeNamed
//@version=4
strategy("Higher TF - Repainting", overlay=true, initial_capital = 100000, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, commission_type = strategy.commission.percent, pyramiding = 1, commission_value = 0.01, calc_on_order_fills = true)
HTFMultiplier = input(4, minval=1, step=1)
SupertrendMult = input(1)
SupertrendPd = input(4, minval=4, step=4)
backtestBars = input(title="Backtest from ", defval=10, minval=1, maxval=30)
backtestFrom = input(title="Timeframe", defval="years", options=["days", "months", "years"])
repaintOption = input(title="Repaint", defval="Yes", options=["Yes", "No - set lookahead false", "No - do not use security"])
f_multiple_resolution(HTFMultiplier) =>
target_Res_In_Min = timeframe.multiplier * HTFMultiplier * (
timeframe.isseconds ? 1. / 60. :
timeframe.isminutes ? 1. :
timeframe.isdaily ? 1440. :
timeframe.isweekly ? 7. * 24. * 60. :
timeframe.ismonthly ? 30.417 * 24. * 60. : na)
target_Res_In_Min <= 0.0417 ? "1S" :
target_Res_In_Min <= 0.167 ? "5S" :
target_Res_In_Min <= 0.376 ? "15S" :
target_Res_In_Min <= 0.751 ? "30S" :
target_Res_In_Min <= 1440 ? tostring(round(target_Res_In_Min)) :
tostring(round(min(target_Res_In_Min / 1440, 365))) + "D"
f_getBackTestTimeFrom(backtestFrom, backtestBars)=>
byDate = backtestFrom == "days"
byMonth = backtestFrom == "months"
byYear = backtestFrom == "years"
date = dayofmonth(timenow)
mth = month(timenow)
yr = year(timenow)
leapYearDaysInMonth = array.new_int(12,0)
array.set(leapYearDaysInMonth,0,31)
array.set(leapYearDaysInMonth,1,29)
nonleapYearDaysInMonth = array.new_int(12,0)
array.set(leapYearDaysInMonth,0,31)
array.set(leapYearDaysInMonth,1,28)
restMonths = array.new_int(10,0)
array.set(leapYearDaysInMonth,0,31)
array.set(leapYearDaysInMonth,1,30)
array.set(leapYearDaysInMonth,2,31)
array.set(leapYearDaysInMonth,3,30)
array.set(leapYearDaysInMonth,4,31)
array.set(leapYearDaysInMonth,5,31)
array.set(leapYearDaysInMonth,6,30)
array.set(leapYearDaysInMonth,7,31)
array.set(leapYearDaysInMonth,8,30)
array.set(leapYearDaysInMonth,9,31)
array.concat(leapYearDaysInMonth,restMonths)
array.concat(nonleapYearDaysInMonth,restMonths)
isLeapYear = yr % 4 == 0 and (year%100 != 0 or year%400 == 0)
numberOfDaysInCurrentMonth = isLeapYear ? array.get(leapYearDaysInMonth, mth-2) : array.get(nonleapYearDaysInMonth, mth-2)
if(byDate)
mth := (date - backtestBars) < 0 ? mth - 1 : mth
yr := mth < 1 ? yr - 1 : yr
mth := mth < 1 ? 1 : mth
date := (date - backtestBars) < 0 ? numberOfDaysInCurrentMonth - backtestBars + date + 1 : date - backtestBars + 1
if(byMonth)
date := 1
yr := (mth - (backtestBars%12)) < 0 ? yr - int(backtestBars/12) - 1 : yr - int(backtestBars/12)
mth := mth - (backtestBars%12) + 1
if(byYear)
date := 1
mth := 1
yr := yr - backtestBars
[date, mth, yr]
repaint = repaintOption == "Yes"
useSecurityLookahead = repaintOption == "No - set lookahead false"
[SupertrendRepaint, DirRepaint] = security(syminfo.tickerid, f_multiple_resolution(HTFMultiplier), supertrend(SupertrendMult, SupertrendPd), lookahead = true, gaps=true)
[SupertrendNoLookahead, DirNoLookahead] = security(syminfo.tickerid, f_multiple_resolution(HTFMultiplier), supertrend(SupertrendMult, SupertrendPd), lookahead = false, gaps=false)
[SupertrendRegular, DirRegular] = supertrend(SupertrendMult, SupertrendPd)
[date, mth, yr] = f_getBackTestTimeFrom(backtestFrom, backtestBars)
inDateRange = time >= timestamp(syminfo.timezone, yr, mth, date, 0, 0)
longCondition = repaint ? DirRepaint == -1 : useSecurityLookahead? DirNoLookahead == -1 : DirRegular == -1
shortCondition = repaint ? DirRepaint == 1 : useSecurityLookahead? DirNoLookahead == 1 : DirRegular == 1
strategy.entry("Buy", strategy.long, when=longCondition and inDateRange)
strategy.entry("Sell", strategy.short, when=shortCondition and inDateRange)