MA Slope Scan For ThinkOrSwim

Yes. When you build the scan, be sure to increase the bar count "within" so many bars.

Like this:
Ruby:
MA_Slope_SCAN()."crossPositive " is true within 3 bars
can you please post the complete code. I have tried it a few times and no success. sorry it took me a while to reply but i was down with covid. fully recovered now.
 

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

Anything that calculates the angle from the low of a candle to the high the next 2 or 3 candles could definitely help here.
 
Last edited by a moderator:
can you please post the complete code. I have tried it a few times and no success. sorry it took me a while to reply but i was down with covid. fully recovered now.
Click on the scan hacker
Click on the pencil
Click on the thinkscript tab
cut&paste the code below right into the scanner.
VdNkGZm.png

Ruby:
## MA Slope SCAN

input length = 20;
input price = close;
input averageType = AverageType.SIMPLE;

def avg = MovingAverage(averageType,price,length);
def height = avg - avg[1];

def "Angle, deg" = Atan(height/length) * 180 / Double.Pi;

plot crossPositive = "Angle, deg" > 0 and "Angle, deg"[1] < 0;
 
@MasterJEK the post below contains the syntax for slope. It should provide you with a start
Thanks for the tip.
I saw it last week and modified it a bit to come up with a scanner from but it's still not giving me what I'm looking for.
This is what I have so far.

Code:
## SLOPE SCAN


def cbh = high[0];
def pbl = low[5];


def diff = AbsValue(pbl - cbh )  ;


def "Angle, deg" = Atan(diff/5) * 180 / Double.Pi;


plot OverExtended = "Angle, deg" >= 80;


Basically, I'm looking for a way to scan for overextended moves on 5min and 15min charts.
Best scenarios happen with at least 5 candles. I use trendline and go from the high or low of the 5th previous bar and the low or high of the current bar to determine the angle. Anything above 80 degrees is definitely stretched and will snap back.

Edq2uUR.jpg
 
Last edited by a moderator:
Yes. But I think it would need to be "Angle, deg" > .25
The plot for Slope is in decimal I believe. The key with the slope is to look for divergence and whether the slope is above or below 0.
If you have the time, would you explain what does the number scale represent above and below, the zero plot line? Really appreciate your thoughts about the divergence. Thank you
 
Thanks for the tip.
I saw it last week and modified it a bit to come up with a scanner from but it's still not giving me what I'm looking for.
This is what I have so far.

Code:
## SLOPE SCAN


def cbh = high[0];
def pbl = low[5];


def diff = AbsValue(pbl - cbh )  ;


def "Angle, deg" = Atan(diff/5) * 180 / Double.Pi;


plot OverExtended = "Angle, deg" >= 80;


Basically, I'm looking for a way to scan for overextended moves on 5min and 15min charts.
Best scenarios happen with at least 5 candles. I use trendline and go from the high or low of the 5th previous bar and the low or high of the current bar to determine the angle. Anything above 80 degrees is definitely stretched and will snap back.

Edq2uUR.jpg
Hi, what' your entry indicator call, is that custum.
 
Just stumbled on this when looking for something else. I am currently working on a study that uses the slope function also. My “criteria” is 4 degrees for a bullish bias and -4 degrees for a bearish bias. The issue I have is that when you get into the higher priced stocks this “4 or -4” no longer works. I think this is due to the y-axis (price) not being “equal size” as compared to the x-axis (time).

Here is an example of what I think would be the most optimal scenario…could be totally wrong. Since there are 390 minutes in the trading day, the y axis would have to be $390 tall. If it’s way higher than you get a higher angle, if it’s lower than a lower angle.

Another example. If I have a stock that trades for $50 and the slope is 4 degrees (using the ATan function) then the stock should be ripping. If I use that same function on a $30,000 stock, 4 degrees is basically flat. I actually went and looked at BRK/A and it showed my slope at 90. In troubleshooting I think the reason why is because the “boxes on the graph paper” are nowhere near equal unless your stock price is in that $390 range. (45 degrees would be $1 per minute if I remember correctly, it was a week or two ago)

Final example. If I want to measure the slope of miles to minutes and anything over 45 degrees is a positive result than my most optimal chart would be 1, 2, 3, 4, 5 miles etc on the y axis and 1, 2, 3, 4, 5 minutes on the x axis. If I suddenly switch the y axis to 1200, 1800, 2400, 3000, 3600 than my slope is now going to look much different. (Makes sense in my head)

The true equation for slope as I understand it is (y2-y1) / (x2-x1). Example 1: (3-1) / (3-1) = 1 vs Example 2: (2400-1200) / (3-1) = 600

Caveat, I have looked at so many different websites trying to figure this out so if I am confusing radians for degrees or slope for linear regression etc than please excuse me.

I guess I’m just hoping that someone else came to my same conclusion and found a workaround for the y-axis issue and getting a slope result that can be used to determine a bullish or bearish bias using a set number, like 4 in my example on stocks with wide ranging prices.
 
Just stumbled on this when looking for something else. I am currently working on a study that uses the slope function also. My “criteria” is 4 degrees for a bullish bias and -4 degrees for a bearish bias. The issue I have is that when you get into the higher priced stocks this “4 or -4” no longer works. I think this is due to the y-axis (price) not being “equal size” as compared to the x-axis (time).

Here is an example of what I think would be the most optimal scenario…could be totally wrong. Since there are 390 minutes in the trading day, the y axis would have to be $390 tall. If it’s way higher than you get a higher angle, if it’s lower than a lower angle.

Another example. If I have a stock that trades for $50 and the slope is 4 degrees (using the ATan function) then the stock should be ripping. If I use that same function on a $30,000 stock, 4 degrees is basically flat. I actually went and looked at BRK/A and it showed my slope at 90. In troubleshooting I think the reason why is because the “boxes on the graph paper” are nowhere near equal unless your stock price is in that $390 range. (45 degrees would be $1 per minute if I remember correctly, it was a week or two ago)

Final example. If I want to measure the slope of miles to minutes and anything over 45 degrees is a positive result than my most optimal chart would be 1, 2, 3, 4, 5 miles etc on the y axis and 1, 2, 3, 4, 5 minutes on the x axis. If I suddenly switch the y axis to 1200, 1800, 2400, 3000, 3600 than my slope is now going to look much different. (Makes sense in my head)

The true equation for slope as I understand it is (y2-y1) / (x2-x1). Example 1: (3-1) / (3-1) = 1 vs Example 2: (2400-1200) / (3-1) = 600

Caveat, I have looked at so many different websites trying to figure this out so if I am confusing radians for degrees or slope for linear regression etc than please excuse me.

I guess I’m just hoping that someone else came to my same conclusion and found a workaround for the y-axis issue and getting a slope result that can be used to determine a bullish or bearish bias using a set number, like 4 in my example on stocks with wide ranging prices.

my 2 cents, searching for angles and slopes , on a stock chart, will drive one crazy. you say you want 4 degrees. but what are you really after. an angle measures a slope. a slope measures a change in y during a change in x. why not look for a percent change in price , over 1 bar, or 10 bars, or...


this checks if the percent rise of price, over 3 bars, is less than 0.25%.
https://usethinkscript.com/threads/...a-and-ideally-200ma-is-flat.10769/#post-94825
test flatness of signal
def slope = 0.25;
def Slp = (Absvalue(SMA - SMA[3]) / sma[3]) * 100 < Slope; ;


https://usethinkscript.com/threads/draw-automatic-45-degree-angles.9159/#post-86990


https://usethinkscript.com/threads/how-to-find-slope-of-line-in-thinkorswim.8936/
 
Just stumbled on this when looking for something else. I am currently working on a study that uses the slope function also. My “criteria” is 4 degrees for a bullish bias and -4 degrees for a bearish bias. The issue I have is that when you get into the higher priced stocks this “4 or -4” no longer works. I think this is due to the y-axis (price) not being “equal size” as compared to the x-axis (time).

Here is an example of what I think would be the most optimal scenario…could be totally wrong. Since there are 390 minutes in the trading day, the y axis would have to be $390 tall. If it’s way higher than you get a higher angle, if it’s lower than a lower angle.

Another example. If I have a stock that trades for $50 and the slope is 4 degrees (using the ATan function) then the stock should be ripping. If I use that same function on a $30,000 stock, 4 degrees is basically flat. I actually went and looked at BRK/A and it showed my slope at 90. In troubleshooting I think the reason why is because the “boxes on the graph paper” are nowhere near equal unless your stock price is in that $390 range. (45 degrees would be $1 per minute if I remember correctly, it was a week or two ago)

Final example. If I want to measure the slope of miles to minutes and anything over 45 degrees is a positive result than my most optimal chart would be 1, 2, 3, 4, 5 miles etc on the y axis and 1, 2, 3, 4, 5 minutes on the x axis. If I suddenly switch the y axis to 1200, 1800, 2400, 3000, 3600 than my slope is now going to look much different. (Makes sense in my head)

The true equation for slope as I understand it is (y2-y1) / (x2-x1). Example 1: (3-1) / (3-1) = 1 vs Example 2: (2400-1200) / (3-1) = 600

Caveat, I have looked at so many different websites trying to figure this out so if I am confusing radians for degrees or slope for linear regression etc than please excuse me.

I guess I’m just hoping that someone else came to my same conclusion and found a workaround for the y-axis issue and getting a slope result that can be used to determine a bullish or bearish bias using a set number, like 4 in my example on stocks with wide ranging prices.
You are on right track if someone implements this would be awesome. Currently I look based on individual stock price.
 
I see lots of interest in this topic, but not too many solutions as of yet. I want to scan for a "x" (20) period type of moving average (EMA) and make it color coded for when it is going up or down at a 45 degree angle or more. Red when 20 EMA is sloping down at 45 or more and green when 20 EMA sloping 45 or more up. I would like to also add in the "within 3 days" part also. I realize most if not all the pieces are probably in this thread, but I still am lost, and I got the feeling others looking at this thread are too. Any help is appreciated. Thanks
 
I see lots of interest in this topic, but not too many solutions as of yet. I want to scan for a "x" (20) period type of moving average (EMA) and make it color coded for when it is going up or down at a 45 degree angle or more. Red when 20 EMA is sloping down at 45 or more and green when 20 EMA sloping 45 or more up. I would like to also add in the "within 3 days" part also. I realize most if not all the pieces are probably in this thread, but I still am lost, and I got the feeling others looking at this thread are too. Any help is appreciated. Thanks
Here is the next link in your quest:
https://usethinkscript.com/threads/how-to-find-slope-of-line-in-thinkorswim.8936/
as I mentioned previously, the great minds of the forum have not found a way to incorporate slope into our trading.
 
# Computes the slope of the SMA100

Ruby:
# Computes the slope of the SMA100

input HowManyPeriodsBackForSlopeMeasure = 3;
input agg = AggregationPeriod.DAY;

def opposite = (SimpleMovingAvg(100) - SimpleMovingAvg(100)[HowManyPeriodsBackForSlopeMeasure]) / SimpleMovingAvg(100)[HowManyPeriodsBackForSlopeMeasure];

def adjacent = HowManyPeriodsBackForSlopeMeasure * .6;
def tan = opposite / adjacent;
def angle100 = Round(ATan(tan) * 180 / Double.Pi, 2);

# Computes the trend strength
def UpTrend = close > SimpleMovingAvg(100) and angle100 >= .02;
def DownTrend = close < SimpleMovingAvg(100) and angle100 <= -.02;

# Plot a line based on the slope calculation
plot SlopeLine = tan;
SlopeLine.SetLineWeight(2);
SlopeLine.AssignValueColor(if SlopeLine > 0.02 then Color.GREEN else if SlopeLine < -0.02 then Color.RED else Color.YELLOW);
SlopeLine.HideBubble();

# Label based on the slope direction
AddLabel(yes, Concat("Slope SMA ", HowManyPeriodsBackForSlopeMeasure),
if tan > 0.02 then Color.GREEN else if tan < -0.02 then Color.RED else Color.YELLOW);
Hi Antwerks,

Here is an adjusted version that seems to show what was intended.
MAslope-Antwerks-chart-4-27-24.png


Code:
# MAslope_AntwerksNew
# Computes the slope of the SMA100
# posted by Antwerks on 4-25-24 but concern that it defined but didn’t use UpTrend and Downtrend, didn't use the agg, and produced no line on the chart; the label wasn't fixed.

declare lower;

input HowManyPeriodsBackForSlopeMeasure = 3;
input anglecutoff = 0.02;

def price = close (period = AggregationPeriod.DAY);
def opposite = (SimpleMovingAvg(price, 100) - SimpleMovingAvg(price, 100)[HowManyPeriodsBackForSlopeMeasure]) / SimpleMovingAvg(price, 100)[HowManyPeriodsBackForSlopeMeasure];

def adjacent = HowManyPeriodsBackForSlopeMeasure * .6;
def tan = (opposite / adjacent);
def angle100 = Round(ATan(tan) * 180 / Double.Pi, 2);

# Computes the trend strength
def UpTrend = close > SimpleMovingAvg(price, 100) and angle100 >= anglecutoff;
def DownTrend = close < SimpleMovingAvg(price, 100) and angle100 <= -anglecutoff;

# Plot a line based on the slope calculation
plot SlopeLine = tan;
SlopeLine.SetLineWeight(2);

SlopeLine.DefineColor("Up", Color.BLUE);
SlopeLine.DefineColor("Down", Color.RED);
SlopeLine.AssignValueColor(if UpTrend then SlopeLine.color(“Up”) else if DownTrend then SlopeLine.color(“Down”) else Color.WHITE);

SlopeLine.HideBubble();

# Label based on the slope direction
AddLabel(yes, Concat("Slope SMA ", HowManyPeriodsBackForSlopeMeasure),
if tan > 0.02 then Color.GREEN else if tan < -0.02 then Color.RED else Color.YELLOW);
 
Last edited by a moderator:
For Rockdog,
If you happen to catch this I was able to reproduce the problem with ES you mentioned and it happened on lower timeframes too. I think it was solved by normalizing the moving average to the current ATR. The version below (ending with _ATR) normalizes the MA to the current ATR to prevent y-axis/timeframe problems, adjusts the Angle degree cutoff to be a user-changeable input, and adds a zeroline. It seems to give the same results as the original though the cutoff value had to be adjusted as shown.

In the chart, MAslopeRockdog is the original plot that didn't always turn yellow during uptrends when it should have. The plot called MAslopeRockdog_ATR is the new one.


Screenshot (1729).png


Code:
# MAslopeRockdog_ATR
# original by Rockdog10 on 9-24-21; concern that it works in NQ & YM but not ES; appears to be affected by timeframe changes
# this version (_ATR) normalizes the MA to the current ATR to prevent y-axis/timeframe problems, adjusts the Angle degree cutoff to be an input, and adds a zeroline.

declare lower;

input length = 34;
input price = close;
input averageType = AverageType.Exponential;
input cutoff = 0.04;

input ATRlength = 14;
input averageType2 = AverageType.WILDERS;
def ATR = MovingAverage(averageType2, TrueRange(high, close, low), ATRlength);

def avg = MovingAverage(averageType, price, length);
def height = (avg  – avg[1]) / ATR;
plot Angledeg = Atan(height/length) * 180 / Double.Pi;
plot zeroline = 0;

Angledeg.AssignValueColor (if Angledeg >= cutoff then color.ORANGE else color.white);
Angledeg.SetLineWeight(2);

ZeroLine.SetDefaultColor(Color.LIGHT_GREEN);
ZeroLine.SetLineWeight(1);
 
Last edited by a moderator:
Raghee Horner's Wave was mentioned in connection with the 34 period EMA used above... here is a version of the indicator (ending in _ATRhilo) that includes the slopes of all three of her lines and all must change slope to get a color switch. The angles don't have to be the same for the three lines and can be edited in the inputs.

Screenshot (1691).png

Code:
# MAslopeRockdog_ATRhilo
# original by Rockdog10 on 9-24-21; concern that it works in NQ & YM but not ES; appears to be affected by timeframe changes
# previous version (_ATR) normalized the MA to the current ATR to prevent y-axis/timeframe problems, adjusted the Angle degree cutoff to be an input, and added a zeroline.
# this version (_ATRhilo) adds the requirement that all three moving averages (close, high and low) change their angle for the indicator line’s color to change to orange (not just a change of angle of the moving average of the close). The precise angles by which the close, high and low must change are now inputs and can be different for each one.

declare lower;

input length = 34;
input price = close;
input averageType = AverageType.Exponential;
input cutoffC = 0.04;
input cutoffH = 0.04;
input cutoffL = 0.04;

input ATRlength = 14;
input averageType2 = AverageType.WILDERS;
def ATR = MovingAverage(averageType2, TrueRange(high, close, low), ATRlength);

def avg = MovingAverage(averageType, price, length);
def heightC = (avg  – avg[1]) / ATR;
def heightH = (Average(high, length) – Average(high, length)[1]) / ATR;
def heightL = (Average(low, length) – Average(low, length)[1]) / ATR;

def AngledegH = Atan(heightH/length) * 180 / Double.Pi;
def AngledegL = Atan(heightL/length) * 180 / Double.Pi;
plot AngledegC = Atan(heightC/length) * 180 / Double.Pi;
plot zeroline = 0;

AngledegC.AssignValueColor (if AngledegC >= cutoffC and AngledegH >= cutoffH and AngledegL >= cutoffL then color.ORANGE else color.white);
AngledegC.SetLineWeight(2);
ZeroLine.SetDefaultColor(Color.LIGHT_GREEN);
ZeroLine.SetLineWeight(1);



I'm been lurking for some time, first time posting. I am trying to create a slope indicator of the 34 EMA in which I have color coded (green, yellow, red) the return angle, similar to Raghee Horner double green indicator. I got /NQ and /YM to work perfectly. If they return angle is greater than 15 degree, then green, if it is less than -15 degree then red, and yellow in between. For some reason, all other stocks and /ES doesn't work correctly. The angle return is in the 0.001 range (possibly radian) and not degrees. I've been racking my head around this for a few days and thought it was an issue with ToS. Does anyone else have this issue with the atan function, or am I missing something? I posted by code below. Thanks in advance for the help.

declare lower;

input length = 34;
input price = close;
input averageType = AverageType. Exponential;
def avg = MovingAverage(averageType, price, length);
def height = avg - avg[1];
plot “Angle, deg” = Atan(height/length) * 180 / Double.Pi;
“Angle, deg”.AssignValueColor (if “Angle, deg” >=.833333333 then color.ORANGE else color.white);


def Candle = if “Angle, deg” > 15 then 2 else if “Angle, deg” < -15 then -2 else 0;
def plotcandle = if candle > 3 then 100 else 10;
plot DiffPlot = plotcandle;
DiffPlot.AssignValueColor(if Candle < -1 then Color.RED else if Candle > 1 then Color.GREEN else Color.YELLOW);
 
Last edited by a moderator:
Hi Antwerks,

Here is an adjusted version that seems to show what was intended.
View attachment 21713

Code:
# MAslope_AntwerksNew
# Computes the slope of the SMA100
# posted by Antwerks on 4-25-24 but concern that it defined but didn’t use UpTrend and Downtrend, didn't use the agg, and produced no line on the chart; the label wasn't fixed.

declare lower;

input HowManyPeriodsBackForSlopeMeasure = 3;
input anglecutoff = 0.02;

def price = close (period = AggregationPeriod.DAY);
def opposite = (SimpleMovingAvg(price, 100) - SimpleMovingAvg(price, 100)[HowManyPeriodsBackForSlopeMeasure]) / SimpleMovingAvg(price, 100)[HowManyPeriodsBackForSlopeMeasure];

def adjacent = HowManyPeriodsBackForSlopeMeasure * .6;
def tan = (opposite / adjacent);
def angle100 = Round(ATan(tan) * 180 / Double.Pi, 2);

# Computes the trend strength
def UpTrend = close > SimpleMovingAvg(price, 100) and angle100 >= anglecutoff;
def DownTrend = close < SimpleMovingAvg(price, 100) and angle100 <= -anglecutoff;

# Plot a line based on the slope calculation
plot SlopeLine = tan;
SlopeLine.SetLineWeight(2);

SlopeLine.DefineColor("Up", Color.BLUE);
SlopeLine.DefineColor("Down", Color.RED);
SlopeLine.AssignValueColor(if UpTrend then SlopeLine.color(“Up”) else if DownTrend then SlopeLine.color(“Down”) else Color.WHITE);

SlopeLine.HideBubble();

# Label based on the slope direction
AddLabel(yes, Concat("Slope SMA ", HowManyPeriodsBackForSlopeMeasure),
if tan > 0.02 then Color.GREEN else if tan < -0.02 then Color.RED else Color.YELLOW);
THANK YOU!!! You guys really help us out!!! much appreciated. Can you make the simpleMovingAvg an input to where one could change that along with all that it attaches to?
 
THANK YOU!!! You guys really help us out!!! much appreciated. Can you make the simpleMovingAvg an input to where one could change that along with all that it attaches to?
In the new version (...AntwerksNew2), the type and length of the moving average are now inputs and there is a zeroline. Label still wasn't fixed yet.

In the chart below, the lower indicator window shows use of Exponential MA instead of Simple MA that was used in the first version.
Screenshot (1698).png


Code:
# MAslope_AntwerksNew2
# Computes the slope of the SMA100
# posted by Antwerks on 4-25-24 but concern that it defined but didn’t use UpTrend and Downtrend, didn't use the agg, and produced no line on the chart; the label wasn't fixed.
# this New2 version allows one to select the type and the length of the moving average as an input & adds zeroline.

declare lower;

input HowManyPeriodsBackForSlopeMeasure = 3;
input MAlength = 100;
input anglecutoff = 0.02;
input averagetype = AverageType.SIMPLE;

def price = close (period = AggregationPeriod.DAY);
def opposite = (movingaverage(averagetype, price, MAlength) - movingaverage(averagetype, price, MAlength)[HowManyPeriodsBackForSlopeMeasure]) / movingaverage(averagetype, price, MAlength)[HowManyPeriodsBackForSlopeMeasure];

def adjacent = HowManyPeriodsBackForSlopeMeasure * .6;
def tan = (opposite / adjacent);
def angle100 = Round(ATan(tan) * 180 / Double.Pi, 2);

# Computes the trend strength
def UpTrend = close > movingaverage(averagetype, price, MAlength) and angle100 >= anglecutoff;
def DownTrend = close < movingaverage(averagetype, price, MAlength) and angle100 <= -anglecutoff;

# Plot a line based on the slope calculation
plot SlopeLine = tan;
plot zeroline = 0;

SlopeLine.SetLineWeight(2);
SlopeLine.DefineColor("Up", Color.BLUE);
SlopeLine.DefineColor("Down", Color.RED);
SlopeLine.AssignValueColor(if UpTrend then SlopeLine.color(“Up”) else if DownTrend then SlopeLine.color(“Down”) else Color.WHITE);
zeroline.SetDefaultColor(Color.GREEN);
zeroline.SetLineWeight(1);

SlopeLine.HideBubble();

# Label based on the slope direction
AddLabel(yes, Concat("Slope SMA ", HowManyPeriodsBackForSlopeMeasure),
if tan > 0.02 then Color.GREEN else if tan < -0.02 then Color.RED else Color.YELLOW);
 
Last edited by a moderator:

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

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