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:

StockGuru71

New member
I am looking for a scanner that allows you to search stocks by choosing a percent away from the 50 or 200 day average. I believe it can be useful when looking for bounces in the markets for trading maneuvers. Thanks to anyone that can help.
 

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));
 

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;
 

Andygray8

Member
I have the following code for stock prices within a certain % of a moving avg BUT wanted to see how I could modify to scan for stocks that are a certain percentage BELOW a particular moving avg:

###############
declare lower;

input percentWithin = 3.3;
input price = close;
input length = 100;
input avgType = AverageType.Simple;

def ma = MovingAverage(avgType, price, length);

plot WithinPercent = Between(price,
ma * (1.02 - (percentWithin / 100)),
ma * (1.02 + (percentWithin / 100)));
#################

Any help much appreciated, thanks!

Andy
 
Last edited by a moderator:

merc2226

New member
VIP
Thanks for posting this.
Can you help with this?
i'm trying to do the same except I'm looking for + or - .125% over and below 50 ema.
I have it drawn one the chart but can't figure out how to show up arrow and alert when it crosses my % up or down arrow and alert when it crosses below my .125%.
it keeps me out of chop on day trades.
thanks for your help.

I’m sorry if I’m missing it.
I see scans but does anyone have a script that is basically a ema cross over alert but when the close of a candle is at .125% above or below the actual 50 ema.
It would create a alert and an arrow up or down on the chart.
It helps keep me out of day trading chop.
 

SleepyZ

Well-known member
VIP
Lifetime
Is there a way to calculate how far the price is from 200SMA as a percent or the price difference. Any suggestions is much appreciated. Thanks

Here is a label code

Code:
plot sma = SimpleMovingAvg(close, 200);
def "diff$" = close - sma;
def "diff%" = ("diff$" / sma);
AddLabel(1, "Close to SMA200 || $Diff: " + AsDollars("diff$") + " || %Diff: " + AsPercent("diff%"), if "diff%" > 0 then Color.GREEN else Color.RED);
 

JustDoIt

New member
VIP
Here is a label code
Is there a way to calculate how far the price is from 200Exponential the price difference. If price above 200Exponential Bullish under Bearish and assign colors. Thank you

i fixed a few things in your study
. add 100* to percent formula.
. add round() to the pct formula.
. change > on negative numbers , pct < -1.
. change numbers for < > , add a < 0.
. move pct to be the first thing displayed in the label. for sorting and so the % will always be visible.
. add a leading 0 to single digit numbers, so text sorting will be similar to number sort.
. add a negative sign to negative numbers (needed because of leading zero).
. remove plot code. only need 1 output in a column study.
. change label color. in a column, label color is the font color.
. add function to change the cell background color, green or red.


Ruby:
# zemaper

input length = 200;
def data = close;
def expavg = expAverage(data, length);
def pct = round(100*(data-expavg)/data, 1);

AddLabel(1, (if pct <0 then "-" else "") +
( if pct > -10 and pct < 10 then "0" else "")
+ absvalue(pct) + "% " +
( if pct > 10 then "Strong" else
if pct > 1 then "Bullish" else
if pct > 0 then "Holding 200" else
if pct < 0 then "losing 200" else
if pct < -1 then "Bearish" else
if pct < -10 then "Selloff" else
"-")
, color.black);

assignbackgroundcolor( if pct > 0 then color.green else color.red );
#

WlLToJs.jpg
Is there a way to calculate how far the price is from 200Exponential the price difference. If price above 200Exponential Bullish under Bearish and assign colors. Thank you
 

crscrs85

New member
Can someone write a code that scans for the high or low bar of a 1 minute chart coming within .02 cents of a daily Exponential moving average with a input that allows the daily expMA to be changed?
 

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