We can use the code from this previous post and just remove the secondary agregation:
https://www.hahn-tech.com/ans/price-within-x-of-sma/
Here is the original code from that post:
declare lower;
input timeFrame = AggregationPeriod.FIFTEEN_MIN;
input xPercent = 5.0;
input length = 50;
def maOne = Average(close(Period = timeFrame), length);
plot signal = close > maOne * (1 - xPercent * 0.01) and close < maOne * (1 + xPercent * 0.01);
And here is what it looks like after the modification:
input xPercent = 6.0;
input length = 20;
def maOne = Average(close, length);
plot signal = close > maOne * (1 - xPercent * 0.01) and close < maOne * (1 + xPercent * 0.01);
Update 8/18/22: While reviewing forum posts for sharing on social media I decided to also include a chart study to compliment the scan code which is provided above. Here is the code you can as a chart study. This includes adjustable inputs, an upper and lower band and a paint-bar option to color candles what close within the bands:
input xPercent = 6.0;
input length = 20;
input averageType = AverageType.EXPONENTIAL;
input paintBars = yes;
plot maOne = MovingAverage(averageType, close, length);
plot lowerBand = maOne * (1 - xPercent * 0.01);
lowerBand.SetDefaultColor(Color.MAGENTA);
plot upperBand = maOne * (1 + xPercent * 0.01);
upperBand.SetDefaultColor(Color.CYAN);
plot signal = close > maOne * (1 - xPercent * 0.01) and close < maOne * (1 + xPercent * 0.01);
signal.SetPaintingStrategy(PaintingStrategy.BOOLEAN_WEDGE_DOWN);
signal.SetDefaultColor(Color.YELLOW);
AssignPriceColor(if paintBars and signal then Color.BLUE else Color.CURRENT);