This script calculates:
1. The running average of all up volumes,
2. The average of last x occurrences of up ,
3. The average up occurrences in last y bars.
- Made code for cases 2 and 3 into functions.
- Added examples of multiple-result functions.
avgWhenInLast(_src, _cond, _cnt) => sum(_cond ? _src : 0, _cnt) / sum(_cond ? 1 : 0, _cnt)
But maybe you know how to limit averaging period with a custom event (stop loss, take profit or opposite condition) instead of amount of bars?
For example I am trying to find a script to replace the builtin "strategy.position_avg_price" function. I need it for my study script dca alertconditions.
It would be great if you could show an example script with a "reset_condition" set to reset the values. :)
I am new with coding and it is difficult for me to imagine or develop scripts, however when I see a working one, I can understand how it works and then implement it into my strategy.
//@version=4 study("Average Since", "", true) // Returns the average of `_src` since `_cond` was last true, and the number of bars since. f_avgSince(_src, _cond) => // _src : series to average. // _cond : condition upon which average is reset. var _cumTotal = 0. var _cumCount = 0 if _cond // When condition is true, reset avg to zero. _cumTotal := _src _cumCount := 1 else // Continue calculating running numbers. _cumTotal := _cumTotal + _src _cumCount := _cumCount + 1 _avg = _cumTotal / _cumCount [_avg, _cumCount - 1] hi = highest(input(50)) // Condition which will reset our avg: when a new high is detected. newHi = hi != hi // Call our function and get 2 results from it simultaneously. [avgSinceNewHigh, barsSinceNewHigh] = f_avgSince(close, newHi) plot(avgSinceNewHigh, "avgSinceNewHigh", color.aqua, 2) plotchar(newHi, "newHi", "•", location.top) plotchar(barsSinceNewHigh, "barsSinceNewHigh", "", location.top)