How To Find Slope of Line In ThinkOrSwim

I wanted to play with the angle of a moving average line as an indicator since there seems to be a pretty distinct pattern with them. Unfortunately, the answer of "how to calculate the slope of a moving average line" was not as readily available as I would've wished. It took me a couple days to figure out how to code thinkscript to get it to return the angle. I'd like to share the process and the final code. If anyone ends up incorporating this into their thinkscript codes, I'd love to hear about it if you wish to share.

We have the use the trigonometric functions to determine what the slope is. I ended up having to go back and learn basic trigonometry that I know I ignored in High School. When we go to the ThinkScript guide, there are COS, SIN, and TAN functions, but the guide is very brief on what they do or what the number being returned means.

We start with SOH CAH TOA:

PVrVdsH.png


In a stock chart, the only side lengths we know are the opposite and adjacent. The hypotenuse is what we are solving for. So the TAN function is the only function we can use.
2WwJLPO.png


dYlddGS.png


We're going to measure the lower left angle, so the stock price is the opposite side, and the date is the adjacent side. With the adjacent side, we need to make sure that all stocks are on an even playing field by using percentages. For the periods on the adjacent side, I've used a value of 0.5 per period so that a percent increase of 50% will show a 45 degree angle.

U4AI4KD.png


A difficult part of the process was figuring out the difference between tangent vs. arc tangent:
  • Tangent = use when you have the degree already and want to find acceptable side lengths.
  • Arc Tangent = use when you have the side lengths and want to find the degree of the angle.

So we use the function "ATAN" rather than TAN. If you go into the documentation for this function and look at the example, you'll see a "180 / Double.Pi" inside ATAN and "DoublePi * 180" inside the TAN function. This is the piece we need to bridge between the lengths and the angle.

Once we do the opposite side length / adjacent side length and get the answer, we can then do the following to get the angle:
  • On the calculator: find the trigonometry functions, then find and select Tan^-1. This will return the angle.
  • In thinkscript: ATAN(opposite/adjacent) * 180 / Double.Pi

Final code:
Code:
Declare lower;
input HowManyPeriodsBackForSlopeMeasure= 1;
input SMALength = 9;
input agg = aggregationPeriod.Day;
input ShowTroubleshootLabels= no;
def SMA = Average(close(period=agg),SMALength);
def opposite = (SMA - SMA[HowManyPeriodsBackForSlopeMeasure])/SMA[HowManyPeriodsBackForSlopeMeasure];
def adjacent = HowManyPeriodsBackForSlopeMeasure * .5;
def tan = opposite / adjacent;

plot angle = ROUND(atan(tan)* 180 / Double.Pi,2);

# ---- Troubleshooting Labels ----
AddLabel(ShowTroubleshootLabels,"Recent SMA: " + SMA,color.yellow);
AddLabel(ShowTroubleshootLabels,"Prev SMA: " + SMA[HowManyPeriodsBackForSlopeMeasure],color.yellow);
AddLabel(showTroubleshootLabels,"Vertical Side: " + opposite,color.white);
AddLabel(showTroubleshootLabels,"Horizontal Side: " + adjacent,color.white);
AddLabel(showTroubleshootLabels,"Vertical/Horizontal: " + tan,color.white);
AddLabel(showTroubleshootLabels,"Angle: " + angle,color.white);
AddChartBubble(SecondsTillTime(1200)==0,if ShowTroubleshootLabels then angle else Double.NaN,angle,color.white);

# ---- Calculator Instructions ----
#With tan entered into the calculator, hit trigonometry, 2nd, and then tan^-1 to get the angle.

After testing this, I believe this is pretty accurate. When you use it on moving averages, the slopes can look alot steeper than what the degree is returning. But I believe that has to do with perspective. You can zoom in and out and the slope of the line changes, sometimes the charts start at numbers other than zero, so they can look extreme. But using the methods discussed above puts the stocks on an even playing field I believe. If you do want to turn up the sensitivity, reducing the 180 in "180 / Double.Pi" would seem to be the easiest way.
 

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

Angle is NOT a fixed variable that can be calculated on Stock Charts!
Remember back in geometry class, the x and y axis were the same units!
On a chart, they are different units: Time and Price. so calculating an 'angle' is totally meaningless.

The "angle" is not a set, finite value.
The angle will be different depending on how your chart is displayed.

Here is a visual example
Below you will see two copies of the exact same chart, note the difference in the appearance of the "angle"
cC4By84.png

dpr976P.png


The definition of y-axis movement over x-axis on stock charts is called MOMENTUM
Generally when members start discussing 'angle' what they are actually looking for is called MOMENTUM.
The y-price change over x bars

The textbook syntax ==
def momo = (Close / Close[5]) *100 ;
read more:
https://stockcharts.com/articles/dancing/2018/10/momentum--rate-of-change.html#:~:text=Here is the formula for,have Momentum less than 100.
 
Last edited:
Changing the bottom length (adjacent side) of the triangle from .5 to something like .1 gives a little more distinction between the angle numbers.
 
I posted this on another forum not so long ago... I'll think through your post a bit more over a coffee later this morning.

Angles are funny things. To say that an angle is 45° is also to say that for every unit to the right, the line moves 1 unit up. Since our x axis units are time (often minutes) and our y axis are price (usually dollars), would a 45° angle be $1 per minute? 1¢ per 5 minutes...? You see where this is going. Expressing slopes in dollars per hour might be useful, but then so might ticks per 500 trades. As long as you are comparing apples to apples you should be ok. Figure out what ToS is giving you for units and what you're calculating and then decide what you want to see.


EDIT:
This is taken directly from the docs here:
https://tlc.thinkorswim.com/center/reference/thinkScript/Functions/Math---Trig/ATan
and will give you the slope in degrees of a line with a known x and y (run and rise, and in our case length and change in price). Such that over three bars (that's the length and the x axis value) the change (here our y axis and change in price) is the SMA[final] - SMA[initial]. The ATAN function returns the value in radians, which are converted to degrees.

Code:
declare lower;
input length = 3;
def avg = Average(close, length);
def height = avg - avg[length];
plot "Angle, deg" = ATan(height/length) * 180 / Double.Pi;


Happy trading,
Mashume
 
Last edited:
I've been comparing it to just using the change % of the moving average line, and they both seem to be identical. So maybe it was all for naught. I'll have to play around with them and see if there are any advantages or disadvantages.

Code:
declare lower;
input length = 9;
input agg = aggregationPeriod.Day;

def avg1 = Average(close(period=agg), length);
#plot avg = avg1-avg1[1];
plot zerobase = 0;
Zerobase.SetDefaultColor(Color.white);
Zerobase.SetStyle(Curve.Short_Dash);
plot NumChange;
NumChange = (avg1-avg1[1])/avg1[1] *100;
 
I'm currently trying to figure out how ThinkOrSwim calculates the greeks and Implied Volatility. If anyone has any insight on how it does this and would share, I would be very greatful.

here are some links on option greeks that might help

options data, greeks, delta, theta,

https://usethinkscript.com/threads/black-scholes-options-model-by-mobius-for-thinkorswim.326/
custom
Black Scholes Options Model by Mobius for ThinkorSwim
markos
Jul 10, 2019

post7
Here are some threads that mention the SeriesVolatility function
https://www.one-tab.com/page/jQhBYwoGTi-zEaCB7pMgjQ

--------------------------------

https://usethinkscript.com/threads/option-greeks-calculation-labels-for-thinkorswim.399/#post-2643
indicators
Option Greeks Calculation Labels for ThinkorSwim
markos
Jul 25, 2019

===========================
options, 2nd order greeks

vanna
https://spotgamma.com/options-vanna-charm/

https://www.thebalance.com/vanna-explanation-of-the-options-greek-1031331

2nd order greeks
https://medium.com/hypervolatility/options-greeks-vanna-charm-vomma-dvegadtime-77d35c4db85c

Options Greeks: Vanna, Charm, Vomma, DvegaDtime

https://spotgamma.com/options-vanna/

https://financetrainingcourse.com/education/2014/06/vega-volga-and-vanna-the-volatility-greeks/

option basics
https://www.thebalance.com/options-definition-3305952

------------------------
xls file
calc greeks
https://financetrainingcourse.com/e...ks-using-solver-to-hedge-vega-gamma-exposure/
In this chapter we start with building a simple Excel spreadsheet that will us allow us to hedge Gamma and Vega exposure for a single short position in a call option contract.
 
I wanted to play with the angle of a moving average line as an indicator since there seems to be a pretty distinct pattern with them. Unfortunately, the answer of "how to calculate the slope of a moving average line" was not as readily available as I would've wished. It took me a couple days to figure out how to code thinkscript to get it to return the angle. I'd like to share the process and the final code. If anyone ends up incorporating this into their thinkscript codes, I'd love to hear about it if you wish to share.

We have the use the trigonometric functions to determine what the slope is. I ended up having to go back and learn basic trigonometry that I know I ignored in High School. When we go to the ThinkScript guide, there are COS, SIN, and TAN functions, but the guide is very brief on what they do or what the number being returned means.

We start with SOH CAH TOA:

PVrVdsH.png


In a stock chart, the only side lengths we know are the opposite and adjacent. The hypotenuse is what we are solving for. So the TAN function is the only function we can use.
2WwJLPO.png


dYlddGS.png


We're going to measure the lower left angle, so the stock price is the opposite side, and the date is the adjacent side. With the adjacent side, we need to make sure that all stocks are on an even playing field by using percentages. For the periods on the adjacent side, I've used a value of 0.5 per period so that a percent increase of 50% will show a 45 degree angle.

U4AI4KD.png


A difficult part of the process was figuring out the difference between tangent vs. arc tangent:
  • Tangent = use when you have the degree already and want to find acceptable side lengths.
  • Arc Tangent = use when you have the side lengths and want to find the degree of the angle.

So we use the function "ATAN" rather than TAN. If you go into the documentation for this function and look at the example, you'll see a "180 / Double.Pi" inside ATAN and "DoublePi * 180" inside the TAN function. This is the piece we need to bridge between the lengths and the angle.

Once we do the opposite side length / adjacent side length and get the answer, we can then do the following to get the angle:
  • On the calculator: find the trigonometry functions, then find and select Tan^-1. This will return the angle.
  • In thinkscript: ATAN(opposite/adjacent) * 180 / Double.Pi

Final code:
Code:
Declare lower;
input HowManyPeriodsBackForSlopeMeasure= 1;
input SMALength = 9;
input agg = aggregationPeriod.Day;
input ShowTroubleshootLabels= no;
def SMA = Average(close(period=agg),SMALength);
def opposite = (SMA - SMA[HowManyPeriodsBackForSlopeMeasure])/SMA[HowManyPeriodsBackForSlopeMeasure];
def adjacent = HowManyPeriodsBackForSlopeMeasure * .5;
def tan = opposite / adjacent;

plot angle = ROUND(atan(tan)* 180 / Double.Pi,2);

# ---- Troubleshooting Labels ----
AddLabel(ShowTroubleshootLabels,"Recent SMA: " + SMA,color.yellow);
AddLabel(ShowTroubleshootLabels,"Prev SMA: " + SMA[HowManyPeriodsBackForSlopeMeasure],color.yellow);
AddLabel(showTroubleshootLabels,"Vertical Side: " + opposite,color.white);
AddLabel(showTroubleshootLabels,"Horizontal Side: " + adjacent,color.white);
AddLabel(showTroubleshootLabels,"Vertical/Horizontal: " + tan,color.white);
AddLabel(showTroubleshootLabels,"Angle: " + angle,color.white);
AddChartBubble(SecondsTillTime(1200)==0,if ShowTroubleshootLabels then angle else Double.NaN,angle,color.white);

# ---- Calculator Instructions ----
#With tan entered into the calculator, hit trigonometry, 2nd, and then tan^-1 to get the angle.

After testing this, I believe this is pretty accurate. When you use it on moving averages, the slopes can look alot steeper than what the degree is returning. But I believe that has to do with perspective. You can zoom in and out and the slope of the line changes, sometimes the charts start at numbers other than zero, so they can look extreme. But using the methods discussed above puts the stocks on an even playing field I believe. If you do want to turn up the sensitivity, reducing the 180 in "180 / Double.Pi" would seem to be the easiest way.

Let me know if you find this useful or anything else to note.

I'm currently trying to figure out how ThinkOrSwim calculates the greeks and Implied Volatility. If anyone has any insight on how it does this and would share, I would be very greatful.
Man, O, Man! You have done good work! This is exactly what I always look for in a stock chart on TOS. I did not know how to write a script, I am new to trading stocks, etc., and have been exploring TOR swim regularly over the last 3 months or so. Here is what I do to get the slop of the 20SMA of a stock: I click on the "style" subtab on the Charts tab and then click on "Show Price as percentage". This gives you % growth over your chosen period, say 3 years, 5 years or 1 year. I choose 3 years and look at the % figure corresponding to the 20SMA and make a list of the stocks with their % growth no. (the only problem with this is that when your Y-axis is % growth, you cannot see the stock price and vice versa and that is annoying). Then I do to TDA, TipRanks, Barchart, and Trading view to get their report/opinion on the stock. If I get 3 out of 4 ratings as strong/strong buy (TipRanks, TDA, Trading View) or 88+buy (barchart), I consider it as buy for me. The last thing I do is assign my selection checkmark based on the highest % no. and minimum 3 highest buy ratings. These stocks are my buys when I get a buy signal. It takes me about 30 minutes to do all these for, say, about 20 stocks. I have been looking for the slop instead of growth no. in %. I will try your method out and hope to report back to you.
 
I've been comparing it to just using the change % of the moving average line, and they both seem to be identical. So maybe it was all for naught. I'll have to play around with them and see if there are any advantages or disadvantages.

Code:
declare lower;
input length = 9;
input agg = aggregationPeriod.Day;

def avg1 = Average(close(period=agg), length);
#plot avg = avg1-avg1[1];
plot zerobase = 0;
Zerobase.SetDefaultColor(Color.white);
Zerobase.SetStyle(Curve.Short_Dash);
plot NumChange;
NumChange = (avg1-avg1[1])/avg1[1] *100;
I wanted to play with the angle of a moving average line as an indicator since there seems to be a pretty distinct pattern with them. Unfortunately, the answer of "how to calculate the slope of a moving average line" was not as readily available as I would've wished. It took me a couple days to figure out how to code thinkscript to get it to return the angle. I'd like to share the process and the final code. If anyone ends up incorporating this into their thinkscript codes, I'd love to hear about it if you wish to share.

We have the use the trigonometric functions to determine what the slope is. I ended up having to go back and learn basic trigonometry that I know I ignored in High School. When we go to the ThinkScript guide, there are COS, SIN, and TAN functions, but the guide is very brief on what they do or what the number being returned means.

We start with SOH CAH TOA:

PVrVdsH.png


In a stock chart, the only side lengths we know are the opposite and adjacent. The hypotenuse is what we are solving for. So the TAN function is the only function we can use.
2WwJLPO.png


dYlddGS.png


We're going to measure the lower left angle, so the stock price is the opposite side, and the date is the adjacent side. With the adjacent side, we need to make sure that all stocks are on an even playing field by using percentages. For the periods on the adjacent side, I've used a value of 0.5 per period so that a percent increase of 50% will show a 45 degree angle.

U4AI4KD.png


A difficult part of the process was figuring out the difference between tangent vs. arc tangent:
  • Tangent = use when you have the degree already and want to find acceptable side lengths.
  • Arc Tangent = use when you have the side lengths and want to find the degree of the angle.

So we use the function "ATAN" rather than TAN. If you go into the documentation for this function and look at the example, you'll see a "180 / Double.Pi" inside ATAN and "DoublePi * 180" inside the TAN function. This is the piece we need to bridge between the lengths and the angle.

Once we do the opposite side length / adjacent side length and get the answer, we can then do the following to get the angle:
  • On the calculator: find the trigonometry functions, then find and select Tan^-1. This will return the angle.
  • In thinkscript: ATAN(opposite/adjacent) * 180 / Double.Pi

Final code:
Code:
Declare lower;
input HowManyPeriodsBackForSlopeMeasure= 1;
input SMALength = 9;
input agg = aggregationPeriod.Day;
input ShowTroubleshootLabels= no;
def SMA = Average(close(period=agg),SMALength);
def opposite = (SMA - SMA[HowManyPeriodsBackForSlopeMeasure])/SMA[HowManyPeriodsBackForSlopeMeasure];
def adjacent = HowManyPeriodsBackForSlopeMeasure * .5;
def tan = opposite / adjacent;

plot angle = ROUND(atan(tan)* 180 / Double.Pi,2);

# ---- Troubleshooting Labels ----
AddLabel(ShowTroubleshootLabels,"Recent SMA: " + SMA,color.yellow);
AddLabel(ShowTroubleshootLabels,"Prev SMA: " + SMA[HowManyPeriodsBackForSlopeMeasure],color.yellow);
AddLabel(showTroubleshootLabels,"Vertical Side: " + opposite,color.white);
AddLabel(showTroubleshootLabels,"Horizontal Side: " + adjacent,color.white);
AddLabel(showTroubleshootLabels,"Vertical/Horizontal: " + tan,color.white);
AddLabel(showTroubleshootLabels,"Angle: " + angle,color.white);
AddChartBubble(SecondsTillTime(1200)==0,if ShowTroubleshootLabels then angle else Double.NaN,angle,color.white);

# ---- Calculator Instructions ----
#With tan entered into the calculator, hit trigonometry, 2nd, and then tan^-1 to get the angle.

After testing this, I believe this is pretty accurate. When you use it on moving averages, the slopes can look alot steeper than what the degree is returning. But I believe that has to do with perspective. You can zoom in and out and the slope of the line changes, sometimes the charts start at numbers other than zero, so they can look extreme. But using the methods discussed above puts the stocks on an even playing field I believe. If you do want to turn up the sensitivity, reducing the 180 in "180 / Double.Pi" would seem to be the easiest way.

Let me know if you find this useful or anything else to note.

I'm currently trying to figure out how ThinkOrSwim calculates the greeks and Implied Volatility. If anyone has any insight on how it does this and would share, I would be very greatful.
Thank you for this coding. I am finding it useful. As the SMA crosses above the zero line (entry), the exits work well with the TMO indicator with a crossing below the zero line as the final exit. By the way, I added the following to your code to assist with the visual:

plot centerLine = 0;
AddCloud(angle, centerLine, Color.GREEN, Color.RED);
 
Last edited by a moderator:
This is from my post, not to take away from anything any of the other authors put in that thread, but I know what to change in what I wrote...
Code:
declare lower;
input length = 3;
def avg = Average(close, length);
def height = avg - avg[length];
plot "Angle, deg" = ATan(height/length) * 180 / Double.Pi;
in that code, there is an average of the clsoe price -- this is what we are calculating the angle of.
ToS has a function: LinearRegCurve() which will, I think, create a series of values.
We can substitute the moving average with the linear regression function:
Code:
declare lower;
input length = 3;
def data = LinearRegCurve(price = close, length = length);
def height = data - data[length];
plot "Angle, deg" = ATan(height/length) * 180 / Double.Pi;
and it should give you the slope of the regression curve in degrees.

hope that helps make some more sense of it for you.

-mashume
 
This is from my post, not to take away from anything any of the other authors put in that thread, but I know what to change in what I wrote...
Code:
declare lower;
input length = 3;
def avg = Average(close, length);
def height = avg - avg[length];
plot "Angle, deg" = ATan(height/length) * 180 / Double.Pi;
in that code, there is an average of the clsoe price -- this is what we are calculating the angle of.
ToS has a function: LinearRegCurve() which will, I think, create a series of values.
We can substitute the moving average with the linear regression function:
Code:
declare lower;
input length = 3;
def data = LinearRegCurve(price = close, length = length);
def height = data - data[length];
plot "Angle, deg" = ATan(height/length) * 180 / Double.Pi;
and it should give you the slope of the regression curve in degrees.

hope that helps make some more sense of it for you.

-mashume
Linear Regression Curve has a length and two angles. Where can I adjust these parameters?
 
Code:
declare lower;
input length = 9;
def agg = getaggregationPeriod();

def avg1 = LinearRegCurve(price = close, length = length);
plot zerobase = 0;
Zerobase.SetDefaultColor(Color.white);
Zerobase.SetStyle(Curve.Short_Dash);
plot NumChange;
NumChange = (avg1-avg1[1])/avg1[1] *100;

Change Avg1 to your moving average or curve. Then update the inputs. This will return the change % from the prior bar to the current bar. In my testing, the line is identical to the code in the first reply that he linked.

If, instead of looking at the change from prior to current, you want to look at 10 bars back to current, you can change the [1] in the NumChange to 10.

Edit: So the code might look like this:

Code:
declare lower;
input lengthOfLine = 9;           # this is the # of periods the line is using. 9SMA = 9.
def agg = getaggregationPeriod();
def HowManyBarsBack = 10;    # How many bars back is the first point to the last point. 1 is recommended if you want to view the line slope.

def avg1 = LinearRegCurve(price = close, length = length);  #This is where you change the line type.
plot zerobase = 0;
Zerobase.SetDefaultColor(Color.white);
Zerobase.SetStyle(Curve.Short_Dash);
plot NumChange;
NumChange = (avg1-avg1[HowManyBarsBack])/avg1[HowManyBarsBack] *100;
 
I don't have it open right now, but in the ThinkScript editor, you can be sure to toggle on the Reference library/Inspector part of the window and edit the parameters of the function that way. I'll post up a screen shot tomorrow. The docs on LinearRegCurve:
https://tlc.thinkorswim.com/center/reference/Tech-Indicators/studies-library/G-L/LinearRegCurve
only show two input parameters. If you're using something else, you will need to adjust your parameters.

The same code can be used to give the slope of any function... at least any regular function that is continuous and does not explode.
 
bro couldn't you literally just do

(y1 - y0)/(x1 - x0)

and then use a threshold in relation to that? for instance, if the slope is 1 then the angle is 45 degrees.
 
bro couldn't you literally just do

(y1 - y0)/(x1 - x0)

and then use a threshold in relation to that? for instance, if the slope is 1 then the angle is 45 degrees.
That won't give you an accurate indication of degree of change. When you are comparing price (which is one scale) and time periods (1,2,3, etc.) they don't have a direct correlation. If we could assign a scale on a graph of 1:x then that would be possible, but when you are switching chart periods (5m, D, etc.) and symbols, it would be nigh unto impossible to hard code that scale into anything that would be useful. This is what @mashume was talking about in his post above. If someone who didn't struggle through calculus has a better answer, I'd welcome it, but that would be pretty advanced mathematics, imo.
 
I am finding that the atan function isn't return a consistent angle across products i.e. seems to return a max of 3.0 with /MCL and goes up to 30 with /MES. Not sure if there is something wrong with my code or a different way to code this? Basically I am making an indicator that signals if the slope of a 22 period SMA is above or below 20 degrees.

def SMA10 = SimpleMovingAvg(close, 10);
def SMA22 = SimpleMovingAvg(close, 22);
def SMA62 = SimpleMovingAvg(close, 62);
def SMA200 = SimpleMovingAvg(close, 200);
def SMA1000 = SimpleMovingAvg(close, 1000);

#calculate height of fast and slow moving averages
def height10 = (SMA10 - SMA10[3]);
def height22 = (SMA22 - SMA22[3]);

#calculate the angle of the slope of the fast and slow moving averages

def "Angle22,deg" = ATan(height22 / 2) * 180 / Double.Pi;

#def strongtrend = Angle10 > 25 and Angle22 > 20;
def strongtrend = "Angle22,deg" > 20 and SMA10 > SMA22;
def downtrend = "Angle22,deg" <-20 and SMA10 < SMA22;

plot Flag = strongtrend;
Flag.SetPaintingStrategy(PaintingStrategy.BOOLEAN_POINTS);
Flag.SetLineWeight(5);
Flag.SetDefaultColor(Color.Green);

plot Flag1 = downtrend;
Flag1.SetPaintingStrategy(PaintingStrategy.BOOLEAN_POINTS);
Flag1.SetLineWeight(5);
Flag1.SetDefaultColor(Color.Orange);
 
Angle is NOT a fixed variable that can be calculated on Stock Charts!
Remember back in geometry class, the x and y axis were the same units!
On stock charts, they are different units: Time and Price. so calculating an angle / slope is totally meaningless.

The angle / slope is not a set, finite value.
The angle / slope will be different depending on how your chart is displayed.

Here is a visual example
Below you will see two images of the exact same chart, note the difference in the appearance of the angle / slope.
cC4By84.png

dpr976P.png


What you are actually looking to script is the slope of y-axis movement over x-axis.
On stock charts, this calculation is called MOMENTUM
The y-price change over x amount of time bars

The textbook syntax ==
def momo = (Close / Close[5]) *100 ;
this is the percentage move of current price over price from 5 bars ago.

read more:
https://stockcharts.com/articles/dancing/2018/10/momentum--rate-of-change.html#:~:text=Here is the formula for,have Momentum less than 100.

In the next post, @3AMBH provides another example for calculating momentum

@DaveTrades
 
Last edited:
I am finding that the atan function isn't return a consistent angle across products i.e. seems to return a max of 3.0 with /MCL and goes up to 30 with /MES. Not sure if there is something wrong with my code or a different way to code this? Basically I am making an indicator that signals if the slope of a 22 period SMA is above or below 20 degrees.

def SMA10 = SimpleMovingAvg(close, 10);
def SMA22 = SimpleMovingAvg(close, 22);
def SMA62 = SimpleMovingAvg(close, 62);
def SMA200 = SimpleMovingAvg(close, 200);
def SMA1000 = SimpleMovingAvg(close, 1000);

#calculate height of fast and slow moving averages
def height10 = (SMA10 - SMA10[3]);
def height22 = (SMA22 - SMA22[3]);

#calculate the angle of the slope of the fast and slow moving averages

def "Angle22,deg" = ATan(height22 / 2) * 180 / Double.Pi;

#def strongtrend = Angle10 > 25 and Angle22 > 20;
def strongtrend = "Angle22,deg" > 20 and SMA10 > SMA22;
def downtrend = "Angle22,deg" <-20 and SMA10 < SMA22;

plot Flag = strongtrend;
Flag.SetPaintingStrategy(PaintingStrategy.BOOLEAN_POINTS);
Flag.SetLineWeight(5);
Flag.SetDefaultColor(Color.Green);

plot Flag1 = downtrend;
Flag1.SetPaintingStrategy(PaintingStrategy.BOOLEAN_POINTS);
Flag1.SetLineWeight(5);
Flag1.SetDefaultColor(Color.Orange);
I am not a coder and have no idea what to contribute here other than to say when ever I am fortunate enough to capture what I call Waterfall Trade, that trade can be monumental and the waterfall is mostly about angle. Here is an indicator that helps me detect a waterfall: http://tos.mx/QsufQ6n its not perfect. Hope you guys are successful!

Ruby:
#hint: recognizes and signals waterfall trading opportunities.
input length = 3;
#hint length:number of consecutive up/down high/lows required for a sell/buy signal.
input ascendingRsiFilter = 0;
#hint ascendingRsiFilter: if rsi is not greater than or equal this level then the reverse waterfall signal is suppressed.
input descendingRsiFilter = 100;
#hint descendingRsiFilter: if rsi is less than or equal this level then the falling waterfall signal is suppressed.
input buyAlert = {default On, Off};
input buyAlertSound = Sound.Bell;
input sellAlert = {default On, Off};
input sellAlertSound = Sound.Ding;
input rsiLength = 14;

def r = RSI(length = rsiLength);

def descHiCnt = CompoundValue(1,
    if high < high[1] then descHiCnt[1] + 1
    else if high == high[1] then descHiCnt[1]
    else 0,
    0
);
def ascLoCnt = CompoundValue(1,
    if low > low[1] then ascLoCnt[1] + 1
    else if low == low[1] then ascLoCnt[1]
    else 0,
    0
);
#Limit plot of cond to count, based upon Linus' logic
input Count = 3;
def cond = descHiCnt[1] >= length && high > high[1] && r <= descendingRsiFilter ;
def dataCount = CompoundValue(1, if cond==1 then dataCount[1] + 1 else dataCount[1], 0);
def dc = if dataCount[1] != dataCount then dataCount else Double.NaN;
plot buy = if !IsNaN(dc) and HighestAll(dataCount) - dataCount <= Count - 1 then low
 else Double.NaN;
buy.SetDefaultColor(Color.White);
buy.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
buy.SetLineWeight(5);
Alert(condition = buy && buyAlert == buyAlert.On, text = "Waterfall Buy", "alert type" = Alert.BAR, sound = buyAlertSound);

def cond1 = ascLoCnt[1] >= length && low < low[1] && r >= ascendingRsiFilter;
def dataCount1 = CompoundValue(1, if cond1==1 then dataCount1[1] + 1 else dataCount1[1], 0);
def dc1 = if dataCount1[1] != dataCount1 then dataCount1 else Double.NaN;
plot sell = if !IsNaN(dc1) and HighestAll(dataCount1) - dataCount1 <= Count - 1 then high
 else Double.NaN;
sell.SetDefaultColor(Color.White);
sell.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
sell.SetLineWeight(5);
Alert( sell && sellAlert == sellAlert.On, "Waterfall Sell", "alert type" = Alert.BAR, sound = sellAlertSound);

AssignPriceColor(
    if !IsNaN(buy) then buy.TakeValueColor()
    else if !IsNaN(sell) then sell.TakeValueColor()
    else Color.CURRENT
);

My simple method that works for me is the MACD as the primary and the Waterfall as confirmation although I often think that the only indicator I need is the MACD. In combination the 1 minute works best for me. See below..white arrows are the waterfall and the maroon is the Upper Macd
PDneLqq.png
 
Last edited by a moderator:
Thank you for the quick replies. I was utilizing the below article code to get the degrees of the angle of the slope of a moving average. You are saying this cannot be done accurately across different products and charts? It is a form of looking for momentum, however I am more looking for a chart formation.

I am looking for a prior steepness of the underlying's move as one criteria for entry. I utilize moving averages and want a certain slope moving average. I.e. scanning for a move on the 5 minute with a steepness of 20 degrees on the moving average slope up etc..will get me looking for an entry on a consolidation. In a way I am looking for trends and/or flag patterns that have already formed the flag pole part of the pattern.

https://tickertape.tdameritrade.com...average-thinkscript-stock-momentum-tool-15190
 

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

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