# avg_diff_per
#https://usethinkscript.com/threads/percent-difference-between-2-moving-averages-scan.19922/
#Percent difference between 2 moving averages scan
def na = double.nan;
def bn = barnumber();
def data = close;
input avg1_type = AverageType.exponential;
input avg1_length = 8;
def avg1 = MovingAverage(avg1_type, data, avg1_length );
input avg2_type = AverageType.Simple;
input avg2_length = 20;
def avg2 = MovingAverage(avg2_type, data, avg2_length );
def avgdiffper = round(100* absvalue(avg1 - avg2)/avg2,2);
def avgdiff = round(absvalue(avg1 - avg2),2);
# % diff from avg2 , bigger avg
input average_percent_difference = 7.0;
input difference_tolerance_per = 0.2;
def diffpr = round(avg2*average_percent_difference/100,2);
def tolpr = round(avg2*difference_tolerance_per/100,2);
def near = avgdiff < (diffpr + tolpr) and avgdiff > (diffpr - tolpr);
#--------------------------------
addlabel(1, "Gap: " + average_percent_difference + " %" , color.yellow);
addlabel(1, "Tolerance: " + difference_tolerance_per + " %", color.yellow);
input show_clouds = yes;
def top = if (near[1] or near or near[-1]) then max(avg1,avg2) else na;
addcloud(top, min(avg1,avg2), color.cyan);
input test_bubble = no;
addchartbubble(test_bubble,low,
diffpr + " d\n" +
tolpr + " t\n" +
avgdiff + " dif\n" +
avgdiffper + " %"
, (if near then color.yellow else color.gray), no);
input show_avg_lines = yes;
plot zavg1 = if show_avg_lines then avg1 else na;
plot zavg2 = if show_avg_lines then avg2 else na;
zavg1.SetDefaultColor(Color.cyan);
zavg1.setlineweight(1);
zavg1.hidebubble();
zavg2.SetDefaultColor(Color.yellow);
zavg2.setlineweight(1);
zavg2.hidebubble();
#