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:
@tradingbenjamin410

There are Three Types of Alerts:
There are alerts written into studies. They only alert when the chart w/ the study is open on your screen
They cannot be sent to phone/email. They cannot have custom sounds.

There are alerts created on a chart for one specific stock that you want to alert on. The alert will only fire once. At that point, the condition has been met, the alert expires. No, this can't be changed.

There are scanned watchlist alerts which alert whenever the results of the scan changes. These alerts can be 3-7min delayed.

There isn't a 'grid' alert
 
Hello Board,

I came across Moving Average Gap Ratio (Indicator) on Trade Station.

http://help.tradestation.com/10_00/...cator/moving_average_gap_ratio_indicator_.htm

The Moving Average Gap Ratio indicator calculates and plots the percentage difference between the Price and the fast, medium, and slow moving averages for the most recent number of bars as specified by each moving average Length input. For example, the default setting is to calculate and plot the percent change based on the average of the closing prices of the last 5 bars, the last 25 bars and the last 75 bars. The shorter (also known as faster) the length of an average the more sensitive it will be to current price changes than longer (slower) averages.

I think this would help identify trade opportunities in gaps with less interference for price movement. I have search the forum and didn't see anything similar and was hoping if someone knows of this indicator to please provide link. Thanks much.

Input​


NameExpressionDefaultDescription
PriceNumeric CloseValue to be used in calculating the moving averages and percentages.
SmoothingTypeNumeric1Set to 1 to use a simple average when calculating the simple moving average; otherwise set to 2 to use an exponential average for smoothing.
FastLengthNumeric5Number of bars to include in calculating the shorter length (fast) average.
MedLengthNumeric25Number of bars to include in calculating the medium length (med) average.
SlowLengthNumeric75Number of bars to include in calculating the longer length (slow) average.
PlotFastPctInChartingNumeric1In charting, set to 1 to display the percentage of price from the fast moving average; otherwise set to 0 to not display.
PlotMedPctInChartingNumeric1In charting, set to 1 to display the percentage of price from the medium moving average; otherwise set to 0 to not display.
PlotFastPctInChartingNumeric1In charting, set to 1 to display the percentage of price from the slow moving average; otherwise set to 0 to not display.

Plot


NumberNameDefault ColorDescription
Plot1Fast%YellowPlots the percent change of the fast moving average.
Plot2Med%CyanPlots the percent change of the medium moving average.
Plot3Slow%MagentaPlots the percent change of the slow moving average.
Plot4ZeroLineGreenPlots a zero reference line.
 
@Mark1126
Bad News: fulfillment of requests for conversion from the TradeStation and other platforms seldom occur as there is no utility to do so.
I currently do not know of any contributors to the forum who are expert coder at TradeStation.

Good News: ToS just came out with: Moving Average Band Width on August 28th.
https://tlc.thinkorswim.com/center/reference/Tech-Indicators/studies-library/M-N/MovAvgBandWidth
I saw the write-up in Stock & Commodities August Issue and it 'sounds' like it could be made to be similar to what you are asking.
Otherwise, there have been several posts to this thread which have provided a work-around.
 
Last edited:
@Mark1126
Bad News: fulfillment of requests for conversion from the TradeStation and other platforms seldom occur as there is no utility to do so.
I currently do not know of any contributors to the forum who are expert coder at TradeStation.

Good News: ToS just came out with: Moving Average Band Width on August 28th.
https://tlc.thinkorswim.com/center/reference/Tech-Indicators/studies-library/M-N/MovAvgBandWidth
I saw the write-up in Stock & Commodities August Issue and it 'sounds' like it could be made to be similar to what you are asking.
Otherwise, there have been several posts to this thread which have provided a work-around.
Hello, Thanks for the reply. I'm still looking for difference in price versus moving averages, not differences between moving averages. I didn't see a post which provides price vs moving averages. I may have missed that and will look again. Have a nice day.
 
@Mark1126 The logic and math used for calculating the difference between two plots is the same, whether it is price and a moving average or it is two moving averages. Therefore, there should be several variations in this thread that can be adapted. Choose which one fits your needs the closest and just swap the plots.
Hope this helps.
 
I have this custom study that shows the distance one MDA from another MDA as a percentage.

jPzWHay.png


The problem is that at times it's difficult to tell if a MDA actually crossed another MDA due to the gap size between the "zero line" and the "plot line". A good portion of the time the gap is very small to the point you make a mistake that there was crossover type of an event.

I was wondering if there was a way to change the color of the "plot line" when ever there's an actual cross over event.
mMFcIUV.png



Code:
#percent of 9 MDA away from 50 MDA

declare lower;

input avgType = Averagetype.simple;
input avgType2 = Averagetype.simple;
input AvgLength = 10;
input AvgLength2 = 20;

def AvgPercent = MovingAverage(avgType, close, avgLength)-MovingAverage(avgType2, close, avgLength2);

plot percentDiff = (absValue(avgPercent)/movingaverage(avgtype,close,avglength)) *100;

plot ZeroLine = 0;
 
I have this custom study that shows the distance one MDA from another MDA as a percentage.

jPzWHay.png


The problem is that at times it's difficult to tell if a MDA actually crossed another MDA due to the gap size between the "zero line" and the "plot line". A good portion of the time the gap is very small to the point you make a mistake that there was crossover type of an event.

I was wondering if there was a way to change the color of the "plot line" when ever there's an actual cross over event.
mMFcIUV.png



Code:
#percent of 9 MDA away from 50 MDA

declare lower;

input avgType = Averagetype.simple;
input avgType2 = Averagetype.simple;
input AvgLength = 10;
input AvgLength2 = 20;

def AvgPercent = MovingAverage(avgType, close, avgLength)-MovingAverage(avgType2, close, avgLength2);

plot percentDiff = (absValue(avgPercent)/movingaverage(avgtype,close,avglength)) *100;

plot ZeroLine = 0;

EDIT ===================
see below - 2nd code added



you can't use an absolute value of a difference to check if there was a crossover. 2 different averages will almost never have the same value, so your percent formula will (almost) never be 0.
i changed you code, to calculate each average, to be able to compare them.
added colors that change , depending on if 1 average is above the other or vice versa.

Code:
# avgs_per_diff_00

declare lower;

input avg1Type = Averagetype.simple;
input avg2type = Averagetype.simple;
input Avg1Length = 10;
input Avg2Length = 20;

def avg1 = MovingAverage(avg1Type, close, avg1Length);
def avg2 = MovingAverage(avg2Type, close, avg2Length);
def avgup = (avg1 > avg2);

#def AvgPercent = MovingAverage(avg1Type, close, avg1Length)-MovingAverage(avg2Type, close, avg2Length);
# plot percentDiff = (absValue(avgPercent)/movingaverage(avg1type,close,avg1length)) *100;

def Avg12diff = avg1 - avg2;

plot percentDiff = (absValue(avg12diff)/avg1) *100;
percentDiff.DefineColor("Up", color.green);
percentDiff.DefineColor("Down", color.red);
percentDiff.AssignValueColor(if avgup then percentDiff.color("up") else percentDiff.color("down"));

plot ZeroLine = 0;

#addchartbubble(1,0, avg1 + "\n" + avg2 + "\n" + avg12diff, color.cyan, no);
#

MgBYBVi.jpg



EDIT ===================

here is another version that changes color, right at the smallest %

Code:
# avgs_per_diff_01
declare lower;
input avg1Type = Averagetype.simple;
input avg2type = Averagetype.simple;
input Avg1Length = 10;
input Avg2Length = 20;

def avg1 = MovingAverage(avg1Type, close, avg1Length);
def avg2 = MovingAverage(avg2Type, close, avg2Length);
def avgup = (avg1 > avg2);

#def AvgPercent = MovingAverage(avg1Type, close, avg1Length)-MovingAverage(avg2Type, close, avg2Length);
# plot percentDiff = (absValue(avgPercent)/movingaverage(avg1type,close,avg1length)) *100;

def Avg12diff = avg1 - avg2;
def per = (absValue(avg12diff)/avg1) *100;
# def Avg1x2 = if (avg1 crosses above avg2) then 1 else if (avg1 crosses below avg2) then 0 else avg1x2[1];

def x = if barnumber() == 1 then 0 else (avg1 crosses avg2);
def x3 = if barnumber() < 3 then 0 else if ( x[1] or x[0] or x[-1]) then 1 else 0;

def persmall = if barnumber() == 1 then 0 else  ( per < per[1] and per < per[-1]);


def Avg1x2b = if barnumber() == 1 then 0 else if (x3 and persmall[1]) then avg1x2b[1] + 1 else avg1x2b[1];
def avg1x2 = (avg1x2b % 2) == 0;

plot percentDiff = per;
percentDiff.DefineColor("Up", color.green);
percentDiff.DefineColor("Down", color.red);
percentDiff.AssignValueColor(if avg1x2 == 1 then percentDiff.color("up") else percentDiff.color("down"));

plot ZeroLine = 0;

#addchartbubble(1, 0.0, x3 + "\n" + persmall + "\n" + Avg1x2b + "\n" + Avg1x2 + "\n" + avg1 + "\n" + avg2 + "\n" + avg12diff, color.cyan, no);
#
 
Last edited:
Hello Board,

I came across Moving Average Gap Ratio (Indicator) on Trade Station.

http://help.tradestation.com/10_00/...cator/moving_average_gap_ratio_indicator_.htm

The Moving Average Gap Ratio indicator calculates and plots the percentage difference between the Price and the fast, medium, and slow moving averages for the most recent number of bars as specified by each moving average Length input. For example, the default setting is to calculate and plot the percent change based on the average of the closing prices of the last 5 bars, the last 25 bars and the last 75 bars. The shorter (also known as faster) the length of an average the more sensitive it will be to current price changes than longer (slower) averages.

I think this would help identify trade opportunities in gaps with less interference for price movement. I have search the forum and didn't see anything similar and was hoping if someone knows of this indicator to please provide link. Thanks much.

Input​


NameExpressionDefaultDescription
PriceNumeric CloseValue to be used in calculating the moving averages and percentages.
SmoothingTypeNumeric1Set to 1 to use a simple average when calculating the simple moving average; otherwise set to 2 to use an exponential average for smoothing.
FastLengthNumeric5Number of bars to include in calculating the shorter length (fast) average.
MedLengthNumeric25Number of bars to include in calculating the medium length (med) average.
SlowLengthNumeric75Number of bars to include in calculating the longer length (slow) average.
PlotFastPctInChartingNumeric1In charting, set to 1 to display the percentage of price from the fast moving average; otherwise set to 0 to not display.
PlotMedPctInChartingNumeric1In charting, set to 1 to display the percentage of price from the medium moving average; otherwise set to 0 to not display.
PlotFastPctInChartingNumeric1In charting, set to 1 to display the percentage of price from the slow moving average; otherwise set to 0 to not display.

Plot


NumberNameDefault ColorDescription
Plot1Fast%YellowPlots the percent change of the fast moving average.
Plot2Med%CyanPlots the percent change of the medium moving average.
Plot3Slow%MagentaPlots the percent change of the slow moving average.
Plot4ZeroLineGreenPlots a zero reference line.


i don't know tradestation programming. i didn't look at your code. i went by the description you posted and on the linked page

i didn't see you code until i clicked reply. maybe the code you copied/pasted contained formatting , that confused this page.
next time paste code into notepad , save it , then copy it. or if possible, paste as plain text.


here is a lower study that compares 3 averages to the current close, and finds the % difference

Code:
# Average_Gap_Ratio_00

# compare 3 averages to price, and find the % difference

# ================================================================

declare lower;
def na = double.nan;

# fast avg
input show_fast_average = yes;
input fast_avg_type = AverageType.EXPONENTIAL;
input fast_avg_length = 5;
def fast_avg = MovingAverage( fast_avg_type, close, fast_avg_length);

# medium avg
input show_med_average = yes;
input med_avg_type = AverageType.EXPONENTIAL;
input med_avg_length = 25;
def med_avg = MovingAverage( med_avg_type, close, med_avg_length);

# slow avg
input show_slow_average = yes;
input slow_avg_type = AverageType.EXPONENTIAL;
input slow_avg_length = 75;
def slow_avg = MovingAverage( slow_avg_type, close, slow_avg_length);

# % diffs
def fastdiffper = (fast_avg - close) / close * 100;
def meddiffper = (med_avg - close) / close * 100;
def slowdiffper = (slow_avg - close) / close * 100;

plot fast = if show_fast_average then fastdiffper else na;
fast.SetDefaultColor(Color.yellow);

plot med = if show_med_average then meddiffper else na;
med.SetDefaultColor(Color.cyan);

plot slow = if show_slow_average then slowdiffper else na;
slow.SetDefaultColor(Color.magenta);

plot z = 0;
z.SetDefaultColor(Color.green);
#
 
Last edited:
Hey all,

Hopefully got a simple one here. I searched but couldn't find what I was looking for.

I'm trying to convert this moving average scan from price to percentage:

def EMA = ExpAverage(close, 21);
plot scan = between(close, EMA-0.50, EMA+0.50);

To clarify I'm trying to find price action that is within +/- 2% of a moving average as opposed to +/- $0.50.

Thanks you lots!
 
Hey all,

Hopefully got a simple one here. I searched but couldn't find what I was looking for.

I'm trying to convert this moving average scan from price to percentage:

def EMA = ExpAverage(close, 21);
plot scan = between(close, EMA-0.50, EMA+0.50);

To clarify I'm trying to find price action that is within +/- 2% of a moving average as opposed to +/- $0.50.

Thanks you lots!
Ruby:
def EMA   = ExpAverage(close, 21);
plot scan = Between(close, EMA - (.02 * EMA), EMA + (.02 * EMA));
 
Solved: Figured out where I went wrong. this is a label that tells you how far away the low of day is in %

def Low = Lowest(low(period = AggregationPeriod.DAY)[0],1);
def PercentFromLow =absValue(((close - low)/close) * 100);
AddLabel(yes, "% From Low ="+percentFromLow + "%", color.orange);
 
Last edited by a moderator:
Hey, how to add study alert to the script when the price is within "x % or x $" range form the daily moving averages.

plot DailyEMA = ExpAverage(close(period = "DAY"), 200);

Alert
 
Last edited:
@AlexeyMironenko You have come to the right place. In this thread, you will find 7 pages of plotting, scanning, watching the percentage between two points. Pick one, change the length to 200 and the percentage to fit your need.

Then add your alert script to the bottom of your study:
Alert(Whatever you called your upsignal, "up alert", Alert.Bar, Sound.Chimes);
Alert(Whatever you called your downsignal, "down alert", Alert.Bar, Sound.Bell);
 
Hello, I have a simple quest but I am having issues with the code. All I want is the code to show as "green" if the price action is above the 50MA and the label to turn red if it is below the 50MA. The code is attached above, I know it's a simple tasks but I have little experience with scripting.

input price = close;
input length = 50;

plot avg = ExpAverage(price, length);
AddLabel(1, "" + "MA1 = " + AsPercent((price - avg)/ price), Color.white);

EDIT

I was able to figure it out on my own. Please see below for the code.

input price = close;
input length = 50;

plot avg = ExpAverage(price, length);
AddLabel(1, "" + "MA1 = " + AsPercent((price - avg)/ price), if price > avg then Color.light_GREEN else Color.pink);
 
Last edited:
Hello, I have a simple quest but I am having issues with the code. All I want is the code to show as "green" if the price action is above the 50MA and the label to turn red if it is below the 50MA. The code is attached above, I know it's a simple tasks but I have little experience with scripting.

input price = close;
input length = 50;

plot avg = ExpAverage(price, length);
AddLabel(1, "" + "MA1 = " + AsPercent((price - avg)/ price), Color.white);

EDIT

I was able to figure it out on my own. Please see below for the code.

input price = close;
input length = 50;

plot avg = ExpAverage(price, length);
AddLabel(1, "" + "MA1 = " + AsPercent((price - avg)/ price), if price > avg then Color.light_GREEN else Color.pink);
Looks like no contributor has been able to help you. It could be that it is not clear what you are asking or you did not provide enough information.

Please reply with a detail explanation of what you are trying to accomplish. or there is a risk that your post will be deleted due to inactivity.
Provide a marked-up screenshot of what a chart that displays what all your conditions would look like.
Questions without images are much less likely to get a response!
Unsure of how to upload screenshots to the forum, Here are directions.

When you are posting your question, please follow the guidelines found here:
https://usethinkscript.com/threads/answers-to-commonly-asked-questions.6006/#post-58016

Here are some other options.
gOqETY2.png



If you have this question, others will also. So if you find an answer to your question, could you post it to the forum? Your contribution will be helping a legion of like-minded traders and thinkscripters. Thanks!
 
Hey,
I was looking for some help with making a scanner that could give indication of a stock approaching the 200EMA in TOS. Say within 1 to 5% of the 200EMA but also having the previous 5 candles or so out of that range and coming from above looking for a potential bounce area.
Any help is appreciated thanks.
 

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

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

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