About the issues encountered while using the whenvalue() function

Jose u

New Member
Hello everyone, I have a programming problem that has been bothering me for a while and I couldn't find a solution. I encountered a new issue while using the whenvalue() function, and I would like to seek your help. Thank you!
—— I want to obtain the recent highest point (HHV) of a technical indicator and the corresponding closing price. However, when using the whenvalue() function, I often get values from many days ago instead of the number of days required by HHV().
To investigate this, I wrote a simple script. I first calculated the recent high point (15 days) using MACD() as the technical indicator and then used whenvalue() to find the corresponding closing price. To verify, I also found the barindex of this calculated closing price to see its actual position.
I used the S&P 500 as a filter for an exploration and found that some results are correct, while others have whenvalue() calculated closing prices that are far from the days calculated by the HHV() function.
I apologize for not having a programming background, making it difficult for me to understand why this is happening. I would appreciate any insights.
Thank you very much!

Code:
``````//Here using a simple indicator to verify the issue with whenvalue() function

ml = MACD(12, 26);
periods = 15;
highestValue = HHV(ml, periods); // 15day highest
cond = highestValue == ml ; //condition
highestValueBar = ValueWhen(cond, BarIndex()); //the bar with the highest point
pp = ValueWhen(cond,C); // the price at point
Total_bar = ValueWhen(C, BarIndex()); //total bar
Barnumber = Total_bar - highestValueBar ; // how many bars between
Ref_PRICE = Ref(C,-Barnumber); //
Ref_Indicator = Ref(ml,-Barnumber);

AddColumn(pp, "price", 1.2); // the corresponding price use whenvalue()