find when an average line is near a candle. (within the tolerance lines)
..choose tolerance type , dollars or percent of close price
....enter values for dollars and percent
..choose price points, high and low or close
....the tolance amount is added and subtracted to the these points, to create tolerance lines.
clouds appear when average line is near, within the tolerances of a candle
alert goes off when average line is near
Code:
# near_ema_price_per
#https://usethinkscript.com/threads/alert-for-price-approaching-moving-average-in-thinkorswim.17865/
#Alert for price approaching moving average
def na = double.nan;
def bn = barnumber();
def data = close;
input tolerance_type = { default price , percent };
input tolerance_price = 0.50;
input tolerance_percent = 1.0;
def tol;
def tol_x;
switch(tolerance_type) {
case price:
tol = tolerance_price;
tol_x = 1;
case percent:
tol = close * tolerance_percent/100;
tol_x = 2;
}
input near_type = { default "high_low" , "close" };
def near_top;
def near_bot;
def near_x;
switch(near_type) {
case "high_low":
near_top = high + tol;
near_bot = low - tol;
near_x = 1;
case "close":
near_top = close + tol;
near_bot = close - tol;
near_x = 2;
}
input show_tolerance_lines = no;
plot z2 = if show_tolerance_lines then near_top else na;
plot z3 = if show_tolerance_lines then near_bot else na;
z2.SetDefaultColor(Color.magenta);
z3.SetDefaultColor(Color.magenta);
input avg1_type = AverageType.exponential;
#input avg1_type = AverageType.Simple;
input avg1_length = 10;
def avg1 = MovingAverage(avg1_type, data, avg1_length );
input show_average_line = yes;
plot zavg1 = if show_average_line then avg1 else na;
zavg1.SetDefaultColor(Color.cyan);
zavg1.setlineweight(1);
zavg1.hidebubble();
def near = near_top >= avg1 and near_bot <= avg1;
#def near = near_top crosses avg1 or near_bot crosses avg1;
input show_clouds = yes;
def cld_top = if near then near_top else na;
addcloud(cld_top, near_bot, color.light_gray);
alert(near, "near" ,alert.BAR, sound.DING);
input show_labels = yes;
addlabel(show_labels, (if near_x == 1 then "high_low" else "close"), color.yellow);
addlabel(show_labels, (if tol_x == 1 then "price" else "percent"), color.yellow);
addlabel(show_labels, "$ " + tol, color.yellow);
input test1_vert = no;
addverticalline(test1_vert and near, "-");
#
purple tolerance lines are on
cyan average line is on
clouds appear when average line is within the tolerance $ of a candle