# Calculate Running Distance Between To Moving Averages

#### ganq

##### Member
2019 Donor
Hi,

Is there a way, I could calculate the running distance between 2 moving averages?

Example: If EMA(9) is coming close to EMA(50) - The distance between the 2 EMAs reduces

Then, if and when EMA(9) gets further apart from EMA(50) - The distance between the 2 EMAs increases

I am trying to plot a signal when the approaching (Coming closer to EMA(50)) EMA(9) starts moving away from EMA(50). The study will only look at 10 (input) bars to determine if the closer approaching EMA is now moving apart?

Any help would be greatly appreciated.

Thanks!

Solution
For the past 10 bars or so above, the EMAs are coming closer but on the 11'th bar - it starts moving the other direction - Is there a way to identify that signal?
So, based on an input = 10 bars in this case, the study will look at 10 bars of decreasing gap and throw a signal if the gap increases in the 10+1 bar - is that possible?

here is an updated study,
it draws a white arrow when there is 10 smaller gaps, then a bigger one ( rule2).
i added an input to enter the quantity of bars to look back for decreasing average gaps. default is 10.
added a choice, none, to turn off rule1 arrows. default is off
left debugging bubble codes active at the end.

Ruby:
``````# avg_gap_compare_01

# compare gap of 9ema to 50ema
# look for 10 smaller...``````
Hi,

Is there a way, I could calculate the running distance between 2 moving averages?

Example: If EMA(9) is coming close to EMA(50) - The distance between the 2 EMAs reduces

Then, if and when EMA(9) gets further apart from EMA(50) - The distance between the 2 EMAs increases

I am trying to plot a signal when the approaching (Coming closer to EMA(50)) EMA(9) starts moving away from EMA(50). The study will only look at 10 (input) bars to determine if the closer approaching EMA is now moving apart?

Any help would be greatly appreciated.

Thanks!

yes, you can find the distance between 2 lines, by subtracting 1 from the other.
then look for changes in that variable. i called it a gap.
i set it up like this,
gap = ema9 - ema50
so when ema9 is above the 50, the gap is positive.

i didn't do anything with looking back 10 bars. i just found all of the signals.

i made a formula out of your rule, that the study looks for.
the gap gets smaller, then larger.
def rule1 = if ( abs_gap > abs_gap[1] and abs_gap[2] > abs_gap[1] ) then 1 else 0;

it draws an arrow when the rule1 formula is true.

has input settings for 2 averages.
defaults are 9EMA and 50EMA

can turn average lines on/off
can show all arrows, or just the first one in a series

TJX 30min

Ruby:
``````# avg_gap_compare_00c

# compare gap of 9ema to 50ema

def na = double.nan;
def bn = barnumber();

# last bar  (most recent)
# def lastbar = !isnan(close[0]) and isnan(close[-1]);
# def valid = !isnan(close);

# emas ---------------------------------------
def price = close;

input ma1_len = 9;
input ma1_type =  AverageType.EXPONENTIAL;
def ma1 = MovingAverage(ma1_type, price, ma1_len);

input ma2_len = 50;
input ma2_type =  AverageType.EXPONENTIAL;
def ma2 = MovingAverage(ma2_type, price, ma2_len);

input show_average_lines = yes;
plot z1 = if show_average_lines then ma1 else na;
plot z2 = if show_average_lines then ma2 else na;
z1.SetDefaultColor(color.cyan);
z2.SetDefaultColor(color.magenta);

#-----------------------------------
input show_avg_gap_cloud = yes;
def z1b = if show_avg_gap_cloud then ma1 else na;

#-----------------------------------
def gap = ma1 - ma2;
def abs_gap = absvalue(gap);

#-----------------------------------
# rules
# rule1: recent gap change is bigger. the change before it was smaller.
def rule1 = if ( abs_gap > abs_gap[1] and  abs_gap[2] > abs_gap[1] ) then 1 else 0;

#-----------------------------------
def gapdir = if bn == 1 then 0
else if (rule1 and gap > 0) then 1
else if (rule1 and gap < 0) then -1
else gapdir[1];

def diffdir = gapdir <> gapdir[1];

#-----------------------------------
input show_rule1_arrows = { only_first_reversal , default all };

def arrows_all;
def arrows_first;
switch (show_rule1_arrows) {
case only_first_reversal:
arrows_all = 0;
arrows_first = 1;
case all:
arrows_all = 1;
arrows_first = 0;
}

def showup = (arrows_all and rule1 and gap > 0) or (arrows_first and rule1 and diffdir and gap > 0);
plot wup = if showup then (min(ma1, ma2)*0.995) else na;
wup.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
wup.SetDefaultColor(Color.green);
wup.setlineweight(3);
wup.hidebubble();

def showdwn = (arrows_all and rule1 and gap < 0) or (arrows_first and rule1 and diffdir and gap < 0);
plot wdwn = if showdwn then (max(ma1, ma2)*1.005) else na;
wdwn.SetPaintingStrategy(PaintingStrategy.ARROW_down);
wdwn.SetDefaultColor(Color.red);
wdwn.setlineweight(3);
wdwn.hidebubble();
#
#-------------------------------------

#input test1_bubble = no;
# gap + " gap\n" +
# gapdir + " dir\n" +
# diffdir + " diff\n" +
# rule1 + " rule"
# , color.yellow, no);

#-------------------------------------
#``````

yes, you can find the distance between 2 lines, by subtracting 1 from the other.
then look for changes in that variable. i called it a gap.
i set it up like this,
gap = ema9 - ema50
so when ema9 is above the 50, the gap is positive.

i didn't do anything with looking back 10 bars. i just found all of the signals.

i made a formula out of your rule, that the study looks for.
the gap gets smaller, then larger.
def rule1 = if ( abs_gap > abs_gap[1] and abs_gap[2] > abs_gap[1] ) then 1 else 0;

it draws an arrow when the rule1 formula is true.

has input settings for 2 averages.
defaults are 9EMA and 50EMA

can turn average lines on/off
can show all arrows, or just the first one in a series
Hi @halcyonguy - Thanks for the quick response and the code - looks pretty neat. From your screenshot:

For the past 10 bars or so above, the EMAs are coming closer but on the 11'th bar - it starts moving the other direction - Is there a way to identify that signal?

So, based on an input = 10 bars in this case, the study will look at 10 bars of decreasing gap and throw a signal if the gap increases in the 10+1 bar - is that possible?

Thanks again for your help with this!

Last edited:
For the past 10 bars or so above, the EMAs are coming closer but on the 11'th bar - it starts moving the other direction - Is there a way to identify that signal?
So, based on an input = 10 bars in this case, the study will look at 10 bars of decreasing gap and throw a signal if the gap increases in the 10+1 bar - is that possible?

here is an updated study,
it draws a white arrow when there is 10 smaller gaps, then a bigger one ( rule2).
i added an input to enter the quantity of bars to look back for decreasing average gaps. default is 10.
added a choice, none, to turn off rule1 arrows. default is off
left debugging bubble codes active at the end.

Ruby:
``````# avg_gap_compare_01

# compare gap of 9ema to 50ema
# look for 10 smaller gaps, then bigger

def na = double.nan;
def bn = barnumber();

# last bar  (most recent)
# def lastbar = !isnan(close[0]) and isnan(close[-1]);
# def valid = !isnan(close);

# emas ---------------------------------------
def price = close;

input ma1_len = 9;
input ma1_type =  AverageType.EXPONENTIAL;
def ma1 = MovingAverage(ma1_type, price, ma1_len);

input ma2_len = 50;
input ma2_type =  AverageType.EXPONENTIAL;
def ma2 = MovingAverage(ma2_type, price, ma2_len);

input show_average_lines = yes;
plot z1 = if show_average_lines then ma1 else na;
plot z2 = if show_average_lines then ma2 else na;
z1.SetDefaultColor(color.cyan);
z2.SetDefaultColor(color.magenta);

#-----------------------------------
input show_avg_gap_cloud = yes;
def z1b = if show_avg_gap_cloud then ma1 else na;

#-----------------------------------
def gap = ma1 - ma2;
def abs_gap = absvalue(gap);

# gap is smaller
def gap_decres = abs_gap[1] > abs_gap[0];
# gap is bigger
def gap_incres = abs_gap[1] < abs_gap[0];

input show_rule1_arrows = { only_first_reversal , all, default none };
input show_rule2_arrows = yes;

input rule2_min_qty_smaller_gaps = 10;

#-----------------------------------
# rules
# rule1:  recent gap change is bigger. the change before it was smaller.
def rule1 = if ( abs_gap > abs_gap[1] and  abs_gap[2] > abs_gap[1] ) then 1 else 0;

# rule2:  10 bars of decreasing gap, then a bigger gap
def rule2 = if (
sum(gap_decres[1], rule2_min_qty_smaller_gaps) == rule2_min_qty_smaller_gaps
and abs_gap[0] > abs_gap[1] )
then 1 else 0;

#-----------------------------------
def gapdir = if bn == 1 then 0
else if (rule1 and gap > 0) then 1
else if (rule1 and gap < 0) then -1
else gapdir[1];

def diffdir = gapdir <> gapdir[1];

#-----------------------------------
#input show_rule1_arrows = { only_first_reversal , default all, none };

def arrows_all;
def arrows_first;
switch (show_rule1_arrows) {
case only_first_reversal:
arrows_all = 0;
arrows_first = 1;
case all:
arrows_all = 1;
arrows_first = 0;
case none:
arrows_all = 0;
arrows_first = 0;
}

def showup = (arrows_all and rule1 and gap > 0) or (arrows_first and rule1 and diffdir and gap > 0);
plot wup = if showup then (min(ma1, ma2)*0.995) else na;
wup.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
wup.SetDefaultColor(Color.green);
wup.setlineweight(3);
wup.hidebubble();

def showdwn = (arrows_all and rule1 and gap < 0) or (arrows_first and rule1 and diffdir and gap < 0);
plot wdwn = if showdwn then (max(ma1, ma2)*1.005) else na;
wdwn.SetPaintingStrategy(PaintingStrategy.ARROW_down);
wdwn.SetDefaultColor(Color.red);
wdwn.setlineweight(3);
wdwn.hidebubble();
#
#-------------------------------------

# rule2 - 10 smaller gaps, then a bigger
#input show_rule2_arrows = yes;

plot xbars_down = if (show_rule2_arrows and rule2) then (min(ma1, ma2)*0.990) else na;
xbars_down.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
xbars_down.SetDefaultColor(Color.white);
xbars_down.setlineweight(3);
xbars_down.hidebubble();

#-------------------------------------

input test_rule1_bubble = no;
gap + " gap\n" +
gapdir + " dir\n" +
diffdir + " diff\n" +
rule1 + " rule1"
, (if rule1 then color.yellow else color.gray), yes);

input test_rule2_bubbles = no;
gap + " gap\n" +
rule2 + " rule2"
, (if rule2 then color.cyan else color.gray), yes);

#-------------------------------------
#``````

87k+ Posts
272 Online

## The Market Trading Game Changer

Join 2,500+ subscribers inside the useThinkScript VIP Membership Club
• Exclusive indicators
• Proven strategies & setups
• Private Discord community
• Exclusive members-only content
• 1 full year of unlimited support

What is useThinkScript?

useThinkScript is the #1 community of stock market investors using indicators and other tools to power their trading strategies. Traders of all skill levels use our forums to learn about scripting and indicators, help each other, and discover new ways to gain an edge in the markets.

How do I get started?

We get it. Our forum can be intimidating, if not overwhelming. With thousands of topics, tens of thousands of posts, our community has created an incredibly deep knowledge base for stock traders. No one can ever exhaust every resource provided on our site.

If you are new, or just looking for guidance, here are some helpful links to get you started.

What are the benefits of VIP Membership?