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:

Join useThinkScript to post your question to a community of 21,000+ developers and traders.

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.
 
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;
 
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!
 
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);
 
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);
 
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));
 
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));
 
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;
 
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:
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.
 
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);
 
Is there a way to scan for equities that are currently 1%-2% above or below the 200 EMA?
Ruby:
#input what percentage above 200ema
input what_percentage = 2;

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

plot scan_above = pct > what_percentage ;
plot scan_below = pct < what_percentage ;
How to use the scan hacker: https://usethinkscript.com/threads/how-to-use-thinkorswim-stock-hacker-scans.284/
 
Can we use this to calculate % distance from Bollinger bands or gap or another indicator as well ?

can I calculate the percent distance close from a specific line? It could be any trendline or study?
 
Can we use this to calculate % distance from Bollinger bands or gap or another indicator as well ?

can I calculate the percent distance close from a specific line? It could be any trendline or study?
Sure here ya go:


def line1 = put what you are measuring FROM here, close, bollinger band, trend line, etc...;
def line2 = put what you are measuring TO here;
def pct = round(100*(line1 - line2)/ line1, 1);

AddLabel(yes, pct, color.violet);
 
I'm looking for the distance between two “13ema and 48ema” moving averages in a percent label that changes color. Example: If 13ema cross is above 48ema, color white, and if the distance is more than 50% then color purple, and if 13ema cross is below 48ema color yellow, and if it's more than 50% color blue.
 
I'm looking for the distance between two “13ema and 48ema” moving averages in a percent label that changes color. Example: If 13ema cross is above 48ema, color white, and if the distance is more than 50% then color purple, and if 13ema cross is below 48ema color yellow, and if it's more than 50% color blue.

This code provides a couple of options.
The default == no plots, just a label. You can drag it to display on any lower or upper chart
input higherchart = yes, a label and upper chart moving averages plot colored as specified in your post.
input lowerchart = yes, drag to the lower chart, label and a histogram plot.

shared chart link: http://tos.mx/BAWfraw Click here for --> Easiest way to load shared links
8oI7MBM.png

Ruby:
# MA Distance Percentage

declare real_size ;

input HigherChart = no ;
input LowerChart = no ;
input len1 = 13;
input len2 = 48;

def data = close;
def avg1 = expAverage(data, len1);
def avg2 = expAverage(data, len2);
def pct = (avg1 - avg2) / avg1 ;

plot ma1 = if HigherChart then avg1 else double.NaN;
     ma1.AssignValueColor(
if pct > 0 and pct > .05 then color.plum else
if pct >=0  then color.white else
if pct < 0 and pct > -.05 then color.blue else
color.yellow) ;
plot ma2 = if HigherChart then avg2 else double.NaN;
     ma2.SetStyle(curve.MEDIUM_DASH);

plot dist = if LowerChart then pct else double.NaN;
     dist.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
     dist.SetLineWeight(5);
     dist.AssignValueColor(
if pct > 0 and pct > .05 then color.plum else
if pct >=0  then color.white else
if pct < 0 and pct > -.05 then color.blue else
color.yellow) ;

plot zero = if LowerChart then 0 else double.NaN;;

zero.SetDefaultColor(Color.WHITE);
     zero.SetLineWeight(2);

AddLabel(yes, "Percentage from " + len2 + "ema: " + AsPercent(pct),
if pct > 0 and pct > .05 then color.plum else
if pct >=0  then color.white else
if pct < 0 and pct > -.05 then color.blue else
color.yellow) ;
 

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

87k+ Posts
360 Online
Create Post

Similar threads

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.
Back
Top