This code snippet demonstrates how to calculate a weighted average of trend durations in financial markets, emphasizing trends with smaller price movements. The weighting is based on both the duration and the price difference of each trend.
// --- settings
SignalPeriod = 12
ArrowPeriod = 2
xTrendDurationAverage = 10
// --- end of settings
bbup = average[signalperiod]+std[signalperiod]*arrowperiod
bbdn = average[signalperiod]-std[signalperiod]*arrowperiod
if ts=0 then
if close crosses over bbup then
ts=bbdn
trend=1
startPrice = close
elsif close crosses under bbdn then
ts=bbup
trend=-1
startPrice = close
endif
endif
if trend=1 then
ts=max(ts,bbdn)
elsif trend=-1 then
ts=min(ts,bbup)
endif
if trend=1 and close crosses under ts then
trend=-1
ts=bbup
t=t+1 //trend count
$bardiff[t]=barindex-lastbarindex //trend duration in bars
$pricediff[t]=abs(close-startPrice) //price movement
startPrice=close
lastbarindex=barindex
endif
if trend=-1 and close crosses over ts then
trend=1
ts=bbdn
t=t+1 //trend count
$bardiff[t]=barindex-lastbarindex //trend duration in bars
$pricediff[t]=abs(close-startPrice) //price movement
startPrice=close
lastbarindex=barindex
endif
//weighted average of trend duration
if t>xTrendDurationAverage then
diff=0
totalWeight=0
for i = t downto t-xTrendDurationAverage do
weightDuration=xTrendDurationAverage-(t-i)
weightPrice=1/$pricediff[i]
weightTotal=weightDuration*weightPrice
diff=diff+weightTotal*$bardiff[i]
totalWeight=totalWeight+weightTotal
next
trendavg=diff/totalWeight
endif
return trendavg as "weighted average of previous X trend duration"
This ProBuilder code snippet is designed to calculate a weighted average of trend durations where the weights are influenced by the price movements within those trends. The smaller the price movement, the higher the weight, emphasizing periods of low volatility.
This approach can be particularly useful for analyzing market conditions where less volatile periods are given more significance, potentially aiding in decision-making processes in trading strategies.
Check out this related content for more information:
https://www.prorealcode.com/topic/buy-sell-magical-trend/page/2/#post-215751
Visit Link