I think this should do the trick. I did not test it. Took me a few days to ponder a solution. Let us know.
input percent = 50.0;
def percentCloseWithinRange = if (high – low) == 0 then 0 else (close – low) / (high – low) ;
plot scan = percentCloseWithinRange * 100 <= percent; def is52WeekHigh = high > highest(high[1], 251);
rec counter = if is52WeekHigh then 0 else if percentCloseWithinRange then counter[1] + 1 else counter[1];
def ChanceofFailedMorningSpike = Round(counter / BarNumber(), 3) * 100;
AddLabel(yes, Concat(“Chanceoffailedmorningspike: “, Concat(ChanceofFailedMorningSpike, “%”)), if ChanceofFailedMorningSpike > 64.0 then Color.RED else if ChanceofFailedMorningSpike < 50.0 then Color.GREEN else Color.yellOW);
Edit: 12/24/18
After receiving feedback that the code was not working I took some time to troubleshoot and found some adjustments were still required. The code below is the updated version that computes the values correctly.
input percent = 50.0;
def percentCloseWithinRange = if (high – low) == 0 then 0 else (close – low) / (high – low) ;
def qualifiedBar = percentCloseWithinRange * 100 <= percent;
plot is52WeekHigh = high > highest(high[1], 251);
rec counter1 = if is52WeekHigh then 0 else if qualifiedBar then counter1[1] + 1 else counter1[1];
rec counter2 = if is52WeekHigh then 0 else if percentCloseWithinRange then counter2[1] + 1 else counter2[1];
def ChanceofFailedMorningSpike = Round(counter1 / counter2, 3) * 100;
AddLabel(yes, Concat(“Chanceoffailedmorningspike: “, Concat(ChanceofFailedMorningSpike, “%”)), if ChanceofFailedMorningSpike > 64.0 then Color.RED else if ChanceofFailedMorningSpike < 50.0 then Color.GREEN else Color.yellOW);
If the 52-week high isn’t possible to start counting from, a backup solution is to have the code start the count from the Highest candle on the daily chart (indicated by the HI Bubble).