Percent Distance Between EMAs or Any 2 Plots For ThinkOrSwim

MerryDay

Administrative
Staff member
Staff
VIP
Lifetime
Scan For Price Within A Percentage Of Moving Average
  1. Where price is below 100 ma
  2. Where price is rising (hl2 is greater than hl2 from 1 bars ago)
  3. Where price is within -2% of the 100 ma
The scan below utilizes @markos script from post #8
Ruby:
# MA Distance Percentage
# Paris
# 4.13.2018
# Computes percentage the current close is above/below the 200 DSMA
# Displays on a lower chart

declare lower;

input length = 200;

def data = close;
def avg = Average(data, length);
def pct = (data/avg) - 1;

plot dist = pct;
plot zero = 0;

zero.SetDefaultColor(Color.WHITE);
zero.SetLineWeight(2);
AddLabel(1, "Percentage from " + length + " MA: " + AsPercent(pct), if pct > 0 then Color.GREEN else Color.PINK);
Copy the above code
In Studies, click Create
Paste the above study
Name the study: Pct_From_MA
Save
Click on the scanner.

Where price is below ma
  1. Click on +Add filter
  2. Click on the pencil icon next to the filter you just added
  3. Click edit
  4. In the left column, click on the 1st pull-down window, click study
  5. Type in Pct_From_MA
  6. Under Plot, click on the pull-down window, choose dist
  7. In length change the 200 ma length to 100 ma length .... (or whatever moving average length that you want)
  8. In the middle column, choose Less than or equal to .... (if scanning for above ma change this to Greater than)
  9. In the right column, click on the pull-down window, click value
  10. Change 100 in the next box to 0
  11. Save

Where price is rising (hl2 is greater than hl2 from 1 bars ago)
  1. Click on +Add filter
  2. Click on the pencil icon next to the filter you just added
  3. Click edit
  4. In the left column, click on the 1st pull-down window, click price
  5. Click hl2 .... (or what ever representation of price that floats your boat)
  6. In the middle column, choose greater than or equal to
  7. In the right column, click on the pull-down window, click price
  8. Click hl2 .... (or what ever representation of price that floats your boat)
  9. In the box under hl2, change the 0 to 1 offset
  10. Save

Where price is within -2% of the ma
  1. Click on +Add filter
  2. Click on the pencil icon next to the filter you just added
  3. Click edit
  4. In the left column, click on the 1st pull-down window, click study
  5. Type in Pct_From_MA
  6. Under Plot, click on the pull-down window, choose dist
  7. In length change the 200 ma length to 100 ma length .... (or whatever moving average length that you want)
  8. In the middle column, choose greater than or equal to .... (or Less than if scanning for above ma)
  9. In the right column, click on the pull-down window, click value
  10. In the box under value, change the value from 100 to -0.02 .... (negative values represent under ma; positive values for above ma)
  11. Save .... (change the percentage to anything you want)

Remember: Change the aggregation of each filter to what you want
83orWtu.png


Here is a Shared Link: http://tos.mx/kXoe4Db
The shared link will only work if you copy and pasted the above study and named it: Pct_From_MA
A poster was having difficulty scanning for within a percentage of ma so I wrote this brief tutorial. I don't use moving average studies so I can not assist w/ how people are utilizing this in their strategies.
 
Last edited:

Joshua

Well-known member
VIP
This should show you symbols within X Percent of the moving averages.
Be aware, I just typed this freehand right here on the forum, untested.

input Percent = 1;
def Avg50 = SimpleMovingAvg(Close,50);
def Prc50 = ((Close - Avg50) / Avg50) * 100;
def Avg200 = SimpleMovingAvg(Close,200);
def Prc200 = ((Close - Avg200) / Avg200) * 100;
plot Scan = Prc50 <= Percent or Prc200 <= Percent;
 

Haulin81

New member
Hi Everyone! Is there something out there that i can add to TOS that will give me a line above my EMA that I can trade off of? I want to go short or long when the price is 20% extended from the 13 EMA. I envision the line being identical to the EMA i am using but suspended 20% above and 20% below. A script with one or the other would be fine and I think i could tweak it. I hope this makes sense.
Thank You!
 

SleepyZ

Well-known member
VIP
Lifetime
Hi Everyone! Is there something out there that i can add to TOS that will give me a line above my EMA that I can trade off of? I want to go short or long when the price is 20% extended from the 13 EMA. I envision the line being identical to the EMA i am using but suspended 20% above and 20% below. A script with one or the other would be fine and I think i could tweak it. I hope this makes sense.
Thank You!

This should allow you to tweak it to your liking

Ruby:
input percent = 20;
input length  = 13;
input price   = close;
input avgtype = averageType.EXPONENTIAL;

plot ema  = movingAverage(avgtype, price, length);
plot emah = ema + ema * percent/100;
plot emal = ema - ema * percent/100;
emah.setdefaultColor(color.red);
emal.setdefaultColor(color.green);
 

Haulin81

New member
You're the Best. Thank You SleepyZ!!!

Can i add a chart bubble to these? I plan on having a few different % lines. I have the script below for straight lines and it works fine but i can't get this to work with the script you just gave me. Thanks!

def nhigh = 10;
def nhigh1 = nhigh + 1;
def nlow = 10;
def nlow1 = nlow + 1;

AddChartBubble(IsNaN(close[nhigh]) and !IsNaN(close[nhigh1]), OverNightHigh, "High PreMkt", Color.GREEN, yes);

AddChartBubble(IsNaN(close[nlow]) and !IsNaN(close[nlow1]), OverNightLow, "Low PreMkt", Color.GREEN, yes);
 

Dk6400

New member
Hello,
I was wondering if someone that is familiar with code is able to slightly modify this code that labels the value of how far the price is from the moving average by percentage. Right now the default settings are the 21-Day moving average, however im looking for the 5-Day Simple moving average instead. If someone is able to modify this code so that we would be able to input any moving average in the default inputs and options I believe this would be helpful for everyone. Thank you in advance, here is the code:

# Moving Average Stats
#
# Written by: @JohnMuchow http://twitter.com/JohnMuchow
# Website: PlayTheTrade.com
#
# v1.0

def aggregationPeriod = GetAggregationPeriod();
def daily = if (aggregationPeriod >= aggregationPeriod.DAY and aggregationPeriod < aggregationPeriod.WEEK, 1, 0);
def lastPrice = close(priceType = PriceType.LAST);
def _10WeekMovingAverage = MovingAverage(AverageType.Simple, close, 10);
def _21DayMovingAverage = MovingAverage(AverageType.Exponential, close, 21);
def percentDiff10Week = (lastPrice/_10WeekMovingAverage) - 1;
def percentDiff21Day = (lastPrice/_21DayMovingAverage) - 1;

input percentBelowMA = 1;

AddLabel(daily AND percentDiff21Day > 0, " " + GetSymbol() + " is " + AsPercent(AbsValue((lastPrice/_21DayMovingAverage) - 1)) + " above 21-day value of " + Round(_21DayMovingAverage, 2) + " ", Color.GRAY);

AddLabel(daily AND percentDiff21Day <= 0, " " + GetSymbol() + " is " + AsPercent(AbsValue((lastPrice/_21DayMovingAverage) - 1)) + " below 21-day value of " + Round(_21DayMovingAverage, 2) + " ", Color.GRAY);

AddLabel(daily, " " + AsPercent(percentBelowMA/100) + " stop below 21-day: " + Round(_21DayMovingAverage * (1 - percentBelowMA/100), 2) + " ", CreateColor(90, 122, 176));

AddLabel(!daily AND percentDiff10Week > 0, " " + GetSymbol() + " is " + AsPercent(AbsValue((lastPrice/_10WeekMovingAverage) - 1)) + " above 10-week value of " + Round(_10WeekMovingAverage, 2) + " ", Color.GRAY);

AddLabel(!daily AND percentDiff10Week <= 0, " " + GetSymbol() + " is " + AsPercent(AbsValue((lastPrice/_10WeekMovingAverage) - 1)) + " below 10-week value of " + Round(_10WeekMovingAverage, 2) + " ", Color.GRAY);

AddLabel(!daily, " " + AsPercent(percentBelowMA/100) + " stop below 10-week: " + Round(_10WeekMovingAverage * (1 - percentBelowMA/100), 2) + " ", CreateColor(90, 122, 176));
 

SleepyZ

Well-known member
VIP
Lifetime
Hello,
I was wondering if someone that is familiar with code is able to slightly modify this code that labels the value of how far the price is from the moving average by percentage. Right now the default settings are the 21-Day moving average, however im looking for the 5-Day Simple moving average instead. If someone is able to modify this code so that we would be able to input any moving average in the default inputs and options I believe this would be helpful for everyone. Thank you in advance, here is the code:

# Moving Average Stats
#
# Written by: @JohnMuchow http://twitter.com/JohnMuchow
# Website: PlayTheTrade.com
#
# v1.0

def aggregationPeriod = GetAggregationPeriod();
def daily = if (aggregationPeriod >= aggregationPeriod.DAY and aggregationPeriod < aggregationPeriod.WEEK, 1, 0);
def lastPrice = close(priceType = PriceType.LAST);
def _10WeekMovingAverage = MovingAverage(AverageType.Simple, close, 10);
def _21DayMovingAverage = MovingAverage(AverageType.Exponential, close, 21);
def percentDiff10Week = (lastPrice/_10WeekMovingAverage) - 1;
def percentDiff21Day = (lastPrice/_21DayMovingAverage) - 1;

input percentBelowMA = 1;

AddLabel(daily AND percentDiff21Day > 0, " " + GetSymbol() + " is " + AsPercent(AbsValue((lastPrice/_21DayMovingAverage) - 1)) + " above 21-day value of " + Round(_21DayMovingAverage, 2) + " ", Color.GRAY);

AddLabel(daily AND percentDiff21Day <= 0, " " + GetSymbol() + " is " + AsPercent(AbsValue((lastPrice/_21DayMovingAverage) - 1)) + " below 21-day value of " + Round(_21DayMovingAverage, 2) + " ", Color.GRAY);

AddLabel(daily, " " + AsPercent(percentBelowMA/100) + " stop below 21-day: " + Round(_21DayMovingAverage * (1 - percentBelowMA/100), 2) + " ", CreateColor(90, 122, 176));

AddLabel(!daily AND percentDiff10Week > 0, " " + GetSymbol() + " is " + AsPercent(AbsValue((lastPrice/_10WeekMovingAverage) - 1)) + " above 10-week value of " + Round(_10WeekMovingAverage, 2) + " ", Color.GRAY);

AddLabel(!daily AND percentDiff10Week <= 0, " " + GetSymbol() + " is " + AsPercent(AbsValue((lastPrice/_10WeekMovingAverage) - 1)) + " below 10-week value of " + Round(_10WeekMovingAverage, 2) + " ", Color.GRAY);

AddLabel(!daily, " " + AsPercent(percentBelowMA/100) + " stop below 10-week: " + Round(_10WeekMovingAverage * (1 - percentBelowMA/100), 2) + " ", CreateColor(90, 122, 176));

This should provide you some flexibility you wished, using the logic of the code you posted.

It defaulted to use the MovingAverage of the current chart aggregation you are viewing. If you choose manual at aggperiod, then it will use the aggper's input instead. The above/below condition was combined resulting in only one label.

Capture.jpg
Ruby:
# Moving Average Stats
#
# Written by: @JohnMuchow http://twitter.com/JohnMuchow
# Website: PlayTheTrade.com
#
# v1.0

#Modified to use 1 MovingAverage with similar labels to original
input aggperiod = {default "current chart", "manual"};
input aggper    = AggregationPeriod.MIN;
input avgtype   = AverageType.SIMPLE;
input length    = 5;

def x;
def y;
if aggperiod == aggperiod.manual {
    x = close(period = aggper);
    y = aggper / 60000;
} else {
    x = close;
    y = GetAggregationPeriod() / 60000;
}
plot ma   = MovingAverage(avgtype, x , length);
def stoppct = 1;

#Percent Change

AddLabel(1, GetSymbol() + "'s Close of " +
x + " is " +
AsPercent(AbsValue((x / ma) - 1)) + " " +
( if  x > ma > 0
  then "above "
  else "below ")
+ "" +  y + "m," + " " + length +
(if avgtype == AverageType.EXPONENTIAL then "EMA"
 else if avgtype == AverageType.HULL
 then "HMA"
 else if avgtype == AverageType.WEIGHTED
 then "WgtMA"
 else if avgtype == AverageType.WILDERS
 then "WdrsMA"
 else "SMA")
+ " value of " +
Round(ma, 2) + " ", Color.GRAY);

#Stop Loss

AddLabel(1, AsPercent(stoppct / 100) + " stop " +
( if  x < ma
  then "above "
  else "below ") +
+ y + "m, " + length + ""+
(if avgtype == AverageType.EXPONENTIAL then "EMA = "
 else if avgtype == AverageType.HULL
 then "HMA = "
 else if avgtype == AverageType.WEIGHTED
 then "WgtMA = "
 else if avgtype == AverageType.WILDERS
 then "WdrsMA = "
 else "SMA = ") +
Round(ma * (1 - stoppct / 100), 2) + " ", CreateColor(90, 122, 176));
 

Dk6400

New member
This should provide you some flexibility you wished, using the logic of the code you posted.

It defaulted to use the MovingAverage of the current chart aggregation you are viewing. If you choose manual at aggperiod, then it will use the aggper's input instead. The above/below condition was combined resulting in only one label.
Yes thank you so much! This is what I was going for. Thank you :)
 

BiggySmall

New member
Would it be possible to create chart label(s) where price is within [n]% (maybe ¼%) above or below the 21ema with 2h, Day, and Week aggregations. The idea when all three timeframes are close to the 21ema it might be a good time to go long.

This scan seems to work. Can someone turn this code into a label? Thanks
Code:
# Scan within [n]% of 21 ema

def ma = ExpAverage(close,21);
def s = ma*0.0025;
plot scan = absvalue(close - ma) is less than or equal to s;
 

JP782

Active member
I want a label that will show what the percentage is from current price/close to an EMA, SMA or whatever(I say whatever for this being adapted to other studies, or no theyd require more work?)?
Label would be like this
"Pct from EMA21: 3%"
 

Similar threads

The Market Trading Game Changer

Join 2,500+ subscribers inside the useThinkScript VIP Membership Club
  • Exclusive indicators
  • Proven strategies & setups
  • Private Discord community
  • ‘Buy The Dip’ signal alerts
  • Exclusive members-only content
  • Add-ons and resources
  • 1 full year of unlimited support

Frequently Asked Questions

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?
VIP members get exclusive access to these proven and tested premium indicators: Buy the Dip, Advanced Market Moves 2.0, Take Profit, and Volatility Trading Range. In addition, VIP members get access to over 50 VIP-only custom indicators, add-ons, and strategies, private VIP-only forums, private Discord channel to discuss trades and strategies in real-time, customer support, trade alerts, and much more. Learn all about VIP membership here.
How can I access the premium indicators?
To access the premium indicators, which are plug and play ready, sign up for VIP membership here.
Top