About the issues encountered while using the whenvalue() function

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!

//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()
AddColumn(highestValue,"Indicator highest",1.2); // 15day highest
AddColumn(highestValueBar, "HHV BAR", 1.0); //the bar with the highest point
AddColumn(Total_bar,"TOTAL BAR",1.0);
AddColumn(Barnumber,"BAR NUMBER",1,IIf(Barnumber < 15,colorGreen,colorRed)); //Check if the number of bars is within 15(HHV condition)
AddColumn(Ref_PRICE,"ref price",1.2); //Check if the price matches HHV
AddColumn(Ref_Indicator,"ref indicator HHV",1.2); //Check if the indicator value matches HHV

Filter = 1 ;



Similar threads