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:
Hi @wtf_dude . I saw your post above and would like to know if you have a solution for the following:

I would like to add a label to my charts that tell me how far extended (above or below), expressed as a percentage, the price is from the 1 hour 9EMA without having to switch to a 1 hour chart (regardless of what time-frame chart I am on).

I have been playing with a script by @tomsk (below), however I can't figure out how to deal with the aggregation period i.e. being able to specify the 1 hour 9EMA. Any help wold be really appreciated.

Code:
# Moving Average Distance
# tomsk
# 12.13.2019

input price = close;
input length = 50;

plot avg = ExpAverage(price, length);
AddLabel(1, "Distance from " + length + " EMA = " + AsDollars(price - avg), Color.YELLOW);
AddLabel(2, "Distance from " + length + " EMA = " + Aspercent((price - avg) / price), Color.YELLOW);
# End Moving Average Distance
 

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

Hi @wtf_dude . I saw your post above and would like to know if you have a solution for the following:

I would like to add a label to my charts that tell me how far extended (above or below), expressed as a percentage, the price is from the 1 hour 9EMA without having to switch to a 1 hour chart (regardless of what time-frame chart I am on).

I have been playing with a script by @tomsk (below), however I can't figure out how to deal with the aggregation period i.e. being able to specify the 1 hour 9EMA. Any help wold be really appreciated.


# Moving Average Distance
# tomsk
# 12.13.2019

input price = close;
input length = 50;

plot avg = ExpAverage(price, length);
AddLabel(1, "Distance from " + length + " EMA = " + AsDollars(price - avg), Color.YELLOW);
AddLabel(2, "Distance from " + length + " EMA = " + Aspercent((price - avg) / price), Color.YELLOW);
# End Moving Average Distance
Ah the problem is that you cant use an aggregation period that's lower than the timeframe you're already on. So if you were in the minute charts, you could see the label BUT if you're in the daily charts you won't. Make sense? Really annoying, not sure why they still don't have a fix
 
Ah the problem is that you cant use an aggregation period that's lower than the timeframe you're already on. So if you were in the minute charts, you could see the label BUT if you're in the daily charts you won't. Make sense? Really annoying, not sure why they still don't have a fix

Thanks for the quick feedback. Got it.

I trade primarily off the 5 min chart and higher. Would it be possible to have what I've described appear on, for example, the 5 or 15 min chart? My goal is to know how much the price is extended (above or below) (as a %) the hourly 9EMA regardless of whether I'm on a 5min chart or lower. It wold be like what my chart setup is for the 9EMAs (the fact that I can see them on all of the various time-frames (here is a link to my chart setup: http://tos.mx/bybssEz).
 
Thanks for the quick feedback. Got it.

I trade primarily off the 5 min chart and higher. Would it be possible to have what I've described appear on, for example, the 5 or 15 min chart? My goal is to know how much the price is extended (above or below) (as a %) the hourly 9EMA regardless of whether I'm on a 5min chart or lower. It wold be like what my chart setup is for the 9EMAs (the fact that I can see them on all of the various time-frames (here is a link to my chart setup: http://tos.mx/bybssEz).
Not sure if I get you, but give this a shot:

Code:
declare upper;

input price = close;
input length = 9;
input Agg= AggregationPeriod.HOUR;
input Avg_Type = averageType.EXPONENTIAL;


def MyPrice = close(period = Agg);
def avg = MovingAverage(Avg_Type, Myprice, length);

AddLabel(yes, "Dollar Dist. from " + length + " EMA = " + AsDollars(close - avg), Color.YELLOW);
AddLabel(yes, "Percent Dist. from " + length + " EMA = " + Aspercent((close - avg) / price), Color.YELLOW);
# End Moving Average Distance
 
I was trying to code up a similar indicator as to the one posted, so thanks for sharing. I am trying to modify the code to show price distance in $ instead of %. Also I would like to see the label on a 1 minute chart but showing the difference of price above or below the 8 EMA of a 15 minute time frame. I am close but the label is showing the price above the 1 minute 8EMA instead of the 15. I don't know where to add in the AggregationPeriod.Fifteen_min to get it to work. I keep getting errors. Any help would be much appreciated! Here is what my code looks like now.

INPUT Period = AGGregationPeriod.FIFTEEN_MIN;
input price = close;
input LENGTH = 8;
input AverageType = AverageType.EXPONENTIAL;

def MA = movingAverage(AverageType, PRICE, LENGTH);

def PD = Round(PRICE - MA);

AddLabel(yes, "PRICE FROM 15 $ " + PD, if PD > 0 then Color.GREEN else Color.RED);
 
Hi Christo,

The following script plots an arrow on a price bar when the 200 SMA crosses above the 50 SMA by 10% or more. The lengths and types of moving averages can be adjusted in the inputs.

I did a scan of all stocks over $1.00 and got 6 achieving this within the last day (1st image).

I then did a scan for all stocks achieving this within the last 10 days and got 108 hits (2nd image).

Hope this does what you wanted it to...

2021-07-02-Watch-List-Scanner-1day.png


2nd scan - last 10 days:

2021-07-02-Watch-List-Scanner-10days.png



Code:
# SMA200_over_SMA50
# mrchristo request

input price = close;
input fastLength = 50;
input slowLength = 200;
input avgtype = averagetype.SIMPLE;

def fastMA = MovingAverage(avgtype, close, fastLength);
def slowMA = MovingAverage(avgtype, close, slowLength);

def SlowOverFastMA = slowMA crosses above (fastMA + (0.1 * fastMA));

plot SMAcross = SlowOverFastMA;

SMAcross.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
SMAcross.SetDefaultColor(Color.MAGENTA);
SMAcross.SetLineWeight(3);
 
I’m trying to find an indicator to determine moving averages within a certain % of each other.

For example:

10 day SMA
21 day EMA
50 day SMA

This is the Power of 3 setup. We want the moving averages within 1.5% of each other, tighter is better, and ideally best setup are within 0.5% of each other.

Buy point as price undercuts and then retakes all the averages.


Any help would be appreciated or guidance.
 
Hey guys,

I'm using the below indicator. I need the code for a scan line that will return daily candles that are within 5% of the dot painted by the indicator. I need the code for both long and short trades. Basically, I don't want my scan to return stocks that have gapped BIG away from the average daily range. Link at bottom of post shows what I need. Any help would be VERY appreciated! 😬

Code:
## Volatility Trailing Stop
## Version 1.1
## By Steve Coombs
## This ATR Trailing Stop is calculated using the Highest Close in an uptrend or
## the Lowest Close in a downtrend, rather than just the Close that is used
## in the standard TOS ATRTrailing Stop

#input StopLabel = yes; #ATRStop Label is Stop value from yesterdays ATR calculation
input ATRPeriod = 10;
input ATRFactor = 1.5;
input firstTrade = {default long, short};
input averageType = AverageType.SIMPLE;

Assert(ATRFactor > 0, "'atr factor' must be positive: " + ATRFactor);
def trueRange = TrueRange(high, close, low);
def loss = ATRFactor * MovingAverage(averageType, trueRange, ATRPeriod);

def state = {default init, long, short};
def trail;
def mclose;
switch (state[1]) {
case init:
    if (!IsNaN(loss)) {
        switch (firstTrade) {
        case long:
            state = state.long;
            mclose = close;
            trail =  close - loss;
        case short:
            state = state.short;
            mclose = close;
            trail = close + loss;
    }
    } else {
        state = state.init;
        trail = Double.NaN;
        mclose = Double.NaN;
    }
case long:
    if (close > trail[1]) {
        state = state.long;
        mclose = Max(mclose[1], close);
        trail = Max (trail[1], mclose - loss);
    } else {
        state = state.short;
        mclose = close;
        trail = mclose + loss;
    }
case short:
    if (close < trail[1]) {
        state = state.short;
        mclose = Min(mclose[1], close);
        trail = Min(trail[1], mclose + loss);
    } else {
        state = state.long;
        mclose = close + 0;
        trail =  mclose - loss;
    }
}

#AddLabel(StopLabel, "ATR Stop =" + Round(trail[1], 2), color = Color.BLUE);
plot TrailingStop = trail;

TrailingStop.SetPaintingStrategy(PaintingStrategy.POINTS);
TrailingStop.SetLineWeight(lineWeight = 3);
TrailingStop.DefineColor("Buy", GetColor(5));
TrailingStop.DefineColor("Sell", GetColor(1));
TrailingStop.AssignValueColor(if state == state.long
    then TrailingStop.Color("Sell")
    else TrailingStop.Color("Buy"));

https://docs.google.com/presentation/d/1AmnQocnczzUjNboODCCCHvtSUjVCmZCnXWswY0FSvro/edit?usp=sharing
 
Last edited:
Welcome @mrchristo I think you want to ask for a few more conditions? You want the price to be approaching the volatility stop in a positive upward trend? You want to be with 5% of the cross but you don't want to include stocks that have already crossed?

Creating scans:
1. The PLOT statement contains the field name for the 'dots'​
In this script, the field is TrailingStop
2. Percentage calculated using high school math: def pct= (TrailingStop/close) - 1;
3. This is your request: In an Uptrend, within 5% but does not cross:​
plot scan = Uptrend and pct<= .05 and pct>0 ;

This is the final code. Cut&Paste it to the bottom of the script.
Ruby:
#Upward trend is defined as:
def UpTrend = close > close from 1 bar ago ;

#High school math:
def pct= (TrailingStop/close) - 1;

#This is the request:
plot scan = Uptrend and pct<= .05 and pct>0;
####################
#when adding a scan plot to a study the following line is necessary so the scan doesn't plot on your chart:
scan.hide();

In your scanner, click on the name of your study, click on the drop down box in the left-hand column, click on scan ; in the center column click on i is true .
a2.png

Hopefully, this has given you an understanding of what logic and information needs to be provided for a scan to be created.
 
Hello @MerryDay. Thank you for taking the time to work on this--I really appreciate it(y). I'll try to be more clear: I don't think I need the volatility stop indicator changed. I'm not working with any type of "cross" strategy.

I want a condition in my scan to make sure that stocks are omitted that have drifted too far away from the volatility stop dot. So, my logic for my downtrend/short scan is this: "in addition to all my other scan criteria in stock hacker, only show me stocks with a current daily price not more than 5% away from the volatility stop dot."
 
@Andygray8 I think there may be a flaw in your logic... When I run the logic against my short watchlist every symbol, all 22, meets that criteria... When I run against All Symbols it found 10,777 results... Are you sure you want within 5% of the lower Bollinger Band...???

Here is the code I'm testing with... It tests for symbols within 5% of the lower band while still being above the lower band...

Ruby:
def pct = 5;
def lbv = BollingerBands(close, 0, 20, -2.0, 2.0, AverageType.SIMPLE)."LowerBand";
def range = lbv * (1 + (pct / 100));
plot near = (close > lbv) and (close < range);
 
@mrchristo The filters you are requesting are: w/in 5% above or 5% below trailing stop?
Ruby:
#High school math:
def pct= (TrailingStop/close) - 1;

#This is the request:
plot scan = pct<= .05 and pct> -.05;
####################
#when adding a scan plot to a study the following line is necessary so the scan doesn't plot on your chart:
scan.hide();
 
@mrchristo The filters you are requesting are: w/in 5% above or 5% below trailing stop?
Ruby:
#High school math:
def pct= (TrailingStop/close) - 1;

#This is the request:
plot scan = pct<= .05 and pct> -.05;
####################
#when adding a scan plot to a study the following line is necessary so the scan doesn't plot on your chart:
scan.hide();
Given your experience, do you think it would be possible to show only scan results where the volatility dot is touching part of the price?
 
Given your experience, do you think it would be possible to show only scan results where the volatility dot is touching part of the price?
No... A price or an indicator is either crossing or it isn't... The clause crosses above is the same as >= and crosses below is the same as <=, just in self-documenting text based scripting language...
 
Im interested in an "alert" when the price is within "x % or x $" range form the daily moving averages, some script to where it will alert on my setup 4hr,1hr,15m,5m chart grid. Is there any setup similiar already and I may have missed it. Thx (this alert would be similiar to an alert you set for a Price Target, to notify you via text or email etc. on a particular stock (mainly a 50dma and 200 dma)
 

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

87k+ Posts
396 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