Chart label for price within X% of moving average


Hi Pete, let me try again…
Can you help me create a chart label that turns green, when the 21ema is within 1/2% of price, otherwise it would be red. I’ve tried looking at examples but I can’t seem to get it right.

Marked as spam
Posted by (Questions: 3, Answers: 1)
Asked on May 7, 2022 2:11 pm
Private answer

I am borrowing some code from a previous solution to perform the percent computation:

I also added some new inputs to allow users to control the moving average parameters from the user inputs so they don't have to try and modify the code.

Aside from that I only added the AddLabel() statement. The label displays whatever has been selected as the percent threshold and the length of the moving average. This allows users to add this chart study to the chart multiple times and adjust each one to a different moving average.

input xPercent = 0.5;
input maLengthOne = 21;
input maTypeOne = AverageType.EXPONENTIAL;
input maPriceOne = close;
plot maOne = MovingAverage(maTypeOne, maPriceOne, maLengthOne);
def signal = close > maOne * (1 - xPercent * 0.01) and close < maOne * (1 + xPercent * 0.01);
AddLabel(yes, Concat(xPercent, Concat("% from ", Concat(maLengthOne, " period ma"))), if signal then Color.GREEN else Color.RED);

Marked as spam
Posted by (Questions: 37, Answers: 3851)
Answered on May 7, 2022 2:33 pm
Perfect, Thank you Pete! I very much enjoy learning from you. You're on another level.
( at May 7, 2022 2:42 pm)