- Since you are requesting a solution that works in a custom watchlist column I had to move your question out of the "Chart Studies" topic and into the "Watch Lists" topic.
- Your description left out a lot of detail. There are many different ways your requests can be interpreted. So I will have to explain the assumptions I was forced to make to help the rest of our viewers understand how to interpret the output of this code.
- In this case, previous high or low is based on a pivot in price action. A price pivot for this purpose is determined using three bars.
- For a swing high pivot the price action must make a higher or equal high, followed by a lower high. The counts continue only so long as each successive bar makes a lower or equal high compared to the previous bar. (there is another way to define this but this is how I have written this specific solution)
- For a swing low pivot the price action must make a lower or equal low, followed by a higher low. The counts continue only so long as each successive bar makes a higher or equal low compared to the previous bar. (there is another way to define this but this is how I have written this specific solution)
So you see there is an awful lot more detail required than you included in your request. And I haven't even covered all of it here because I am running out of time for completing this response.
Here is the code that is used to display these counts in a custom watchlist column. The column can only display one value at a time. So at the bottom of the code I have included two different plot statements. One to display the counts since high and another to display the counts since low. Just move the "#" symbol to select which one to display. You will have to add two custom columns to the watchlist and set each one to a different plot statement.
def oneBarPivotHigh = high[1] >= high[2] and high < high[1];
def oneBarPivotLow = low[1] <= low[2] and low > low[1];
rec countSinceHigh = if oneBarPivotHigh then 1 else if high <= high[1] then countSinceHigh[1] + 1 else 0;
rec countSinceLow = if oneBarPivotLow then 1 else if low >= low[1] then countSinceLow[1] + 1 else 0;
# use this to display the bar count since recent high pivot
plot data = countSinceHigh;
# use thhis to display the bar count since recent low pivot
#plot data = countSinceLow;