Yearning for a chart indicator that doesn't exist yet? Why not write it yourself? All it takes is knowing your thinkScript® ABCs.
Back in the early days of thinkorswim®, traders clamored for an ever-growing catalog of technical studies and strategy tests for their charts, each with their own preferred formats and inputs. Originally, the development team wrote all these tools individually in the platform’s rather complex programming language. That was great for performance, but clunky for simpler ideas like “subtract the 10-day moving average from the 30-day moving average.”
Today, our programmers still write tools for our users. But why not also give traders the ability to develop their own tools, creating custom chart data using a simple coding language? With this lightning bolt of an idea, thinkScript was born.
From there, the idea spread. Instead of forcing our platform and our users to use predefined everything—charts, alerts, scans, orders, columns—we expanded thinkScript's capability to customize the content and format of all of these tools. If you’re so inclined, there's a whole world of customization available to you.
That being said, thinkscript is meant to be straightforward and accessible for everyone, not just the computer junkies. Ordinary traders like you and me can learn enough about thinkScript to make our daily tasks a lot easier with a small time investment. At the closing bell, this article is for regular people. Not programmers.
thinkScript is most frequently used on the Charts and the MarketWatch tabs. Think of accessing it the same way you’d add a technical study, because the thinkScript editor that lets you write the thinkScript code exists inside the Chart studies and Quotes page.
FIGURE 1: thinkScript Editor in thinkorswim Charts. For illustrative purposes only.
Note the menu of thinkScript commands and functions on the right-hand side of the editor window. That’s a thinkScript library with quick definitions of each function.
FIGURE 2: Once you've scripted your personal indicator in thinkorswim, you can view it in Charts. This chart is from the script in figure 1. For illustrative purposes only.
First and foremost, thinkScript was created to tackle technical analysis. Below is the code for the moving average crossover shown in figure 2, where you can see 10-day and 30-day simple moving averages on a chart. Follow the steps described above for Charts scripts, and enter the following:
def tenday = reference simplemovingavg (length=10);def thirtyday = reference simplemovingavg (length=30);plot data1 = tenday;plot data2 = thirtyday;
Huh? Let’s back up and clarify terms.
Find your best fit.
By the way, at the end of each line of thinkScript code you’ll notice a semicolon (“;”). That tells thinkScript that this command sentence is over. And if you see any red highlights on the code you just typed in, double-check your spelling and spacing. The platform is pretty good at highlighting mistakes in the code.
With some practice and knowledge, you could add all sorts of custom colors and styles to this crossover study to fine-tune your experience, but don’t worry about that for now. Learn just enough thinkScript to get you started. You’ll go bonkers trying to figure it all out at once.
If you want options data that doesn’t currently exist as a platform feature, why not create it yourself? Here’s another handy trick: thinkScript allows a watchlist to show just about any custom column you create yourself. You may already be familiar with the “Current IV Percentile” in the Trade page’s “Today’s Options Statistics” section. That number shows the current overall implied volatility of a stock’s options, relative to its past year’s high-to-low range. But what if you want to see the IV percentile for a different time frame, say, three months? (See figure 3.)
Following the steps described above for the Quotes scripts, enter this:
def ivol = if!isNaN(imp_volatility) then imp_volatility else ivol;def lowvol = lowest(ivol,60);def highvol = highest(ivol,60);def currentvol = imp_volatility;plot data = ((currentvol - lowvol)/(highvol - lowvol)*100);
This thinkScript code defines four things—“ivol,” “lowvol,” “highvol,” and “currentvol,” and bases them on the value of “imp_volatility.” “imp_volatility” is a study that gives you the platform’s “Vol Index” number, which is a stock’s options’ overall implied volatility. The “if !IsNaN” returns zero if the Vol Index is unavailable for a symbol. The “lowest” and “highest” are commands that order thinkScript to find the lowest or highest “ivol” over the previous 60 days. The “plot” command displays the results of a formula using the things we’ve defined.
You can change “60” to any number for the range. Keep in mind that each month has about 20 trading days, so 60 trading days is about three months. If you want to show a yearly number, use “262,” which is approximately a year of trading days. To get this into a WatchList, follow these steps on the MarketWatch tab:
thinkScript can also be used on thinkorswim charts as a technical analysis backtesting tool. With this feature, you can see the potential profit and loss for hypothetical trades generated on technical signals. Bear in mind that strategy-generated P/L values don't include theoretical commission costs.
FIGURE 4: BACKTEST WITH THINKSCRIPT. You can turn your indicators into a strategy backtest. With the script for the 10- and 30-day moving averages in Figures 1 and 2, for example, you can plot how many times they cross over a given period. For illustrative purposes only.
Refer to figure 4. Let’s review strategy results that get long (buy a stock or option) when a 10-day moving average crosses above the 30-day moving average, and get short (sell a stock or option) when a 30-day moving average crosses above a 10-day moving average. To do this, we can recycle some of the old code we used in the chart study, but we need to add to the code conditions to backtest “BUY’ and “SELL” trades.
To get to the Strategy creation menu and create one, follow these steps:
Notice the buy and sell signals on the chart in figure 4. To see profit/loss for the backtest, carefully right-click one of the chart’s trade signals. Then, select “Show Report” from the dropdown menu. The thinkScript code does this through the “Add Order” command. This code specifies “Buy_Auto” when the “sma10” is greater than “sma30,” and “Sell_Auto” when “sma10” is less than “sma30.” Together, they create the chart’s hypothetical buys and sells. thinkScript also has commands for opening and closing buy and sell orders so you can create specific testing scenarios.
The “tickColor,” “arrowColor,” and “GetColor” are commands thinkScript uses to add color to buy and sell signals. The numbers “5” and “6” refer respectively to red and green.
Being tied into the markets doesn’t mean being tied to your computer. If you’re out and about, and don’t have time to watch the SPX on your TD Ameritrade mobile trading app, the alert functionality on the thinkorswim platform lets you write custom technical indicators and have messages sent to your phone or mobile device when the indicator reaches a certain level or value.
There’s also the “Trigger if” dropdown menu that alerts you if the value of your thinkScript study meets certain conditions. Click on the Create Alert button in the lower right, and you’re almost done.
To make sure you get messages with triggered alerts:
There you have it. Use thinkScript for alerts, and you’ll never have to miss a trading signal again!
Okay, we couldn’t help but get a little bit geeky on that last script, but we’ve only scratched the surface of what thinkScript can do. Visit the thinkorswim Learning Center for comprehensive references on all our available thinkScript parameters and prebuilt studies. If you have an idea for your own proprietary study, or want to tweak an existing one, thinkScript is about the most convenient and efficient way to do it. And you just might have fun doing it.
for thinkMoney ®
Financial Communications Society 2016
for Ticker Tape
Content Marketing Awards 2016
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.
Backtesting is the evaluation of a particular trading strategy using historical data. Results presented are hypothetical, they did not actually occur and they may not take into consideration all transaction fees or taxes you would incur in an actual transaction. And just as past performance of a security does not guarantee future results, past performance of a strategy does not guarantee the strategy will be successful in the future. Results could vary significantly, and losses could result.
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. TD Ameritrade is a trademark jointly owned by TD Ameritrade IP Company, Inc. and The Toronto-Dominion Bank. © 2021 Charles Schwab & Co. Inc. All rights reserved.