Weighted Average Calculation of Trend Durations in Financial Markets

22 Nov 2019
0 comment
0 attachment

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.

  • Settings: Initial settings define periods used for calculations.
  • Calculating Bollinger Bands: ‘bbup’ and ‘bbdn’ are calculated using the average and standard deviation over a defined period.
  • Detecting Trend Changes: The script checks for crossings over or under these bands to determine trend changes and initializes variables accordingly.
  • Tracking Trend Duration and Price Movement: When a trend change is detected, the duration and price difference from the start of the trend are recorded.
  • Weighted Average Calculation: For each trend, a weight is calculated based on the duration and the inverse of the price difference. These weights are then used to compute a weighted average of the trend durations.

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.

Related Post

Check out this related content for more information:

https://www.prorealcode.com/topic/buy-sell-magical-trend/page/2/#post-215751

Visit Link
What is a Snippet? A snippet is a small, reusable chunk of code designed to solve specific tasks quickly. Think of it as a shortcut that helps you achieve your coding goals without reinventing the wheel. How to Use: Simply copy the snippet and paste it into your project where needed. Don't forget to tweak it to fit your context. Snippets are not just time-savers; they're also learning tools to help you become a more efficient coder.
Nicolas Master
I created ProRealCode because I believe in the power of shared knowledge. I spend my time coding new tools and helping members solve complex problems. If you are stuck on a code or need a fresh perspective on a strategy, I am always willing to help. Welcome to the community!
Author’s Profile

Comments

Search Snippets

Showing some results...
Sorry, no result found!

Snippets Categories

global
35
indicator
133
strategy
171

Recent Snippets

How to Create a Simple MTF Trend Dashboard with EMA and SMA
indicator
This indicator builds a compact multi-timeframe (MTF) dashboard that shows whether price is trading above or below a [...]
How to Display Per-Bar Volume Accumulation in Real Time (Intrabar Updates)
global
This snippet tracks and displays the current bar’s accumulated volume while the bar is still forming, instead of only [...]
Ticks Counter: Count Tick Updates Per Bar on Tick or Time Charts
global
This snippet counts how many tick updates have occurred for the current bar by incrementing a per-bar counter on each [...]
How to Build a Step-Based Trailing Stop That Moves to Break-Even First
strategy
This snippet implements a step trailing stop that advances in fixed increments once price reaches predefined profit [...]
Utilizing Arrays to Track and Compare Indicator Values Within the Same Bar in ProBuilder
indicator
This ProBuilder code snippet demonstrates how to use arrays to compare the values of an indicator (RSI in this case) [...]
Logo Logo
Loading...