Cool Scripts: Create a Stock Momentum Tool with a Twist

Learn to use simple moving averages (SMAs) to track stock momentum by creating scripts with thinkScript® on the thinkorswim® trading platform from TD Ameritrade.

https://tickertapecdn.tdameritrade.com/assets/images/pages/md/Sloping road: use momentum indicators with thinkScript on thinkorswim
3 min read
Photo by Getty

Key Takeaways

  • Understand how to identify momentum in a trend by looking at the slope of a simple moving average
  • Learn how to use thinkScript® to plot a moving average as a subchart
  • You can use thinkScript to scan for stocks and set alerts

What’s a trend? To some it might mean donning loungewear in bright colors and prints to feel trendy while working from home. To others, it could mean something that happens in a similar way enough times so that you could, with a fairly low level of analysis, predict the general details of the next occurrence. This is how trends in the stock market work, generally. But what looks like a trend to one trader may not necessarily look like a trend to another. That said, let’s look at price trends in the stock market from a slightly different angle. 

Many traders and investors overlay a simple moving average (SMA) on price bars to figure out if prices are indeed in a trend. Trends ride on momentum, but how much momentum does momentum have? One way to do it is to look at the slope of an SMA. A steeper slope may mean more momentum, whereas a shallower slope could mean weaker momentum. One way to do this is to plot the SMA’s slope as a lower indicator on a chart in the thinkorswim® platform from TD Ameritrade. And that might mean creating the indicator using thinkScript®. Although there are hundreds of indicators and tools available in thinkorswim, sometimes you may want to create your own indicator or trading tool that’s tailored to your needs

The Script

To locate the thinkScript Editor, select Charts > Studies > Edit studies... and the Edit Studies and Strategies window will open. Select Create... and this opens up the Editor window. You’ll see a predefined script in line 1. Start by deleting the script in line 1 and enter the following code exactly as you see here, including all spaces and characters.

1. declare lower;

2. input length = 20;

3. input price = close;

4. input averageType = AverageType. SIMPLE;

5. def avg = MovingAverage(averageType, price, length);

6. def height = avg - avg[1];

7. plot “Angle, deg” = Atan(height/length) * 180 / Double.Pi;

8. “Angle, deg”.AssignValueColor (if “Angle, deg” >=0 then color.ORANGE else color.BLUE);

What It All Means

Line 1. This tells the editor that this script should be displayed on the lower subgraph below a chart.

Line 2. The number of bars needed to build your average. This can vary depending on how far back you want to go to calculate the average. A 20-period SMA will likely be closer to the price bars than, say, a 100-day SMA. 

Line 3. This allows you to choose the data point to calculate the SMA. This could be the high, low, open, or close. So, if you want the average of the closing price, you’d enter “close.” 

Line 4. Here, you select your favorite type of moving average. So you could choose simple, exponential, weighted, or any other moving average type.

Line 5. This function calculates the average. Depending on the length, price, and moving average type you chose, the MovingAverage function will do the math.

Line 6. To create a slope, you need to know a height and distance. Slope equals rise over run. In this case, rise is the difference between one average point to the next.

Line 7. Now on to Trigonometry 101. The Atan function is short for arctangent and gives the angle of height over the length that’s used to calculate the moving average. The second half of this line converts the angle into degrees. Adding quotations around the variable “Angle, deg” creates a variable name with a space.

Line 8. Finally, let’s make the chart pretty. The AssignValueColor function allows you to assign different colors to a positive slope and negative slope. This makes it easier to see the difference between the two.

Once you’ve entered the code, select Apply and voila! Your indicator is plotted on the subchart (see figure 1).

simple moving average slope in thinkscript
FIGURE 1: A DIFFERENT WAY OF LOOKING AT SIMPLE MOVING AVERAGES. Using thinkScript in thinkorswim, you can view a simple moving average in a subchart. This could give you a different perspective of how strong a trend might be and perhaps a new type of confirming indicator. When looking at the slope of the SMA below the chart you may be able to see extremes in the price action more clearly, which indicates possible turning points. Chart source: the thinkorswim platform from TD AmeritradeFor illustrative purposes only. Past performance does not guarantee future results.

Script It!

In thinkorswim, look under the Education tab > Learning Center > Technical Analysis > thinkScript. Then, simply follow the on-screen instructions.

There are different ways to apply a moving average when it’s plotted in a subchart. One way is to look at the slope. When the slope of the moving average is relatively steeper, it could suggest the trend has more momentum. If the SMA slope starts moving lower, it could indicate a slowdown, which might mean the trend may reverse.

You could take this a step further. Try adding this script as a Study filter in the thinkorswim Stock Hacker and adding a line to plot the slope that you want to scan. You could also use the script as an alert for your TD Ameritrade mobile apps.

There’s all sorts of things you can do with thinkScript. But, careful! Once you get started, it may get addictive.

Print

Key Takeaways

  • Understand how to identify momentum in a trend by looking at the slope of a simple moving average
  • Learn how to use thinkScript® to plot a moving average as a subchart
  • You can use thinkScript to scan for stocks and set alerts

Do Not Sell or Share My Personal Information

Content intended for educational/informational purposes only. Not investment advice, or a recommendation of any security, strategy, or account type.

Be sure to understand all risks involved with each strategy, including commission costs, before attempting to place any trade. Clients must consider all relevant risk factors, including their own personal financial situations, before trading.

adChoicesAdChoices

Market volatility, volume, and system availability may delay account access and trade executions.

Past performance of a security or strategy does not guarantee future results or success.

Options are not suitable for all investors as the special risks inherent to options trading may expose investors to potentially rapid and substantial losses. Options trading subject to TD Ameritrade review and approval. Please read Characteristics and Risks of Standardized Options before investing in options.

Supporting documentation for any claims, comparisons, statistics, or other technical data will be supplied upon request.

This is not an offer or solicitation in any jurisdiction where we are not authorized to do business or where such offer or solicitation would be contrary to the local laws and regulations of that jurisdiction, including, but not limited to persons residing in Australia, Canada, Hong Kong, Japan, Saudi Arabia, Singapore, UK, and the countries of the European Union.

TD Ameritrade, Inc., member FINRA/SIPC, a subsidiary of The Charles Schwab Corporation. © 2024 Charles Schwab & Co. Inc. All rights reserved.

Scroll to Top