This ProBuilder code snippet is designed to calculate the average duration of trend phases over a specified number of recent trends in financial market data. It uses a combination of moving averages and standard deviation to define trend boundaries and counts the number of bars (candles) each trend lasts before reversing.
// --- 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
elsif close crosses under bbdn then
ts=bbup
trend=-1
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
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
lastbarindex=barindex
endif
//average of trend duration
if t>xTrendDurationAverage then
diff=0
for i = t downto t-xTrendDurationAverage do
diff=diff+$bardiff[i]
next
trendavg=diff/xTrendDurationAverage
endif
return trendavg as "average of previous X trend duration"
This code snippet operates by defining upper and lower boundaries for trends based on a moving average and its standard deviation. Here’s a breakdown of its functionality:
This tool is useful for traders who want to gauge the stability or volatility of the market by understanding how long trends typically last before reversing.
Check out this related content for more information:
https://www.prorealcode.com/topic/buy-sell-magical-trend/page/2/#post-215711
Visit Link