With thinkScript, ordinary traders can create their own custom charts and data
Learn to use thinkScript for technical analysis, custom data, and backtesting
You can also script alerts for your TD Ameritrade mobile apps
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.
Let’s Get Crackin’
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.
To Start a Script for Charts
- Click on the Studies button.Select “Edit Studies” in the new window that opens up. Click on the “Create” button in the lower left-hand corner. That opens up a thinkScript editor with default thinkScript code (figure 1). You can delete that code and start typing your own.
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.
To Start a Script for Quotes
- On the MarketWatch tab, click Quotes in the top menu.From the Quotes page, click on the small gear in the upper right-hand corner, or right-click any column header (like “Symbol”).Select “Customize…” from the dropdown menu.Scroll down the list of “Available Items” and click on one of the numbered “Custom” columns.Double-click on the scroll icon to open the same thinkScript editor window that’s on Charts (figure 2).For a custom quote, click “Apply” to save the changes when you’re done writing your code. Then click “Add Item(s)” on the Customize Quotes menu to add it to your selected column set. For a custom chart study, just click “OK” when you are done coding and your new study will be automatically applied to the chart you were on. Click “OK” on the Edit Studies menu to exit.
Remember, you can script just about anything you want (within reason, of course). To get started, let’s look at a few cool examples you might want to try.
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.
1. Technical Indicator: Moving Average Crossover
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.
- def—Defines something in thinkScript. It says, “define this thing named ‘tenday’ as referencing the study ‘simplemovingavg,’ which uses 10 bars of data.” “def” also defines “thirtyday” as a simple moving average that uses 30 bars of data.
Powerful platforms, powerful tools.
- reference—A command of sorts that pulls studies into your code already written in thinkScript. As you know, developers have already created hundreds of studies. Save yourself time and use “reference” whenever you can. Here, thinkScript is pulling in a study called “simplemovingavg.” You can find “simplemovingavg” in the studies list on thinkorswim Charts. Once you find a study, reference it in your code. In this moving average crossover code, the“tenday” is telling the simplemovingavg study to use “length = 10.” That means use 10 bars of prices in the moving average calculation. The “length = 30” tells the “thirtyday” simple moving average to use 30 bars of price data.plot—Once you’ve defined the things for your chart, display them with the “plot” command. In this moving average crossover, we’re plotting two lines—a 10-day moving average and a 30-day moving average. So we’ll need to create two plots and call them different things. Here, we created “plot data1” and “plot data2” and told them to display what we just defined. “plot data1 = tenday” means “the plot command will display this thing called ‘data1,’ which we defined above as ‘tenday.’” “plot data2 = thirtyday” does the same thing for the 30-day simple moving average.
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.
2. Custom Volatility: IV Percentile
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.)
FIGURE 3: CUSTOM VOL PERCENTILE. Don’t want 12 months of volatility? Write a script to get three. For illustrative purposes only.
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:
- Click on the Quotes subtab.Click on the dot to the left of the word “Symbol” in the upper left-hand corner of the Quotes tab.Select “Customize” from the dropdown menu.When the “Customize Quotes” box opens, click on one of the “Custom” choices in the list of “Available Items.” That opens the “Custom Quote Formula” box, where you can click on the thinkScript editor tab and write in the code. Remember to name your thinkScript code so you can add it to your Quotes list! You can add columns and studies with the default “Custom” name, but once your collection starts growing, a good naming scheme makes finding them much easier.
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:
- Right-click on a chart and select “Studies,” then “Edit Studies.”This time, click the “Strategies” tab in the upper left-hand corner.Next, click “New” in the lower left-hand corner. When the thinkScript Editor tab opens, enter the following script:
def sma10 = reference simplemovingavg(length=10);
def sma30 = reference simplemovingavg(length=30);
addOrder(OrderType.BUY_AUTO, sma10 > sma30, tickColor = GetColor(6), arrowColor = GetColor(6));
addOrder(OrderType.SELL_AUTO, sma10 < sma30, tickColor = GetColor(5), arrowColor = GetColor(5));Give it a clear name like MovingAvgCross.Click OK in the lower right-hand corner to close the thinkScript editor.Hit “Apply.”
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.
Bonus Script: Script Alerts
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.
- On the Market Watch tab, click on the Alerts subtab, and enter the symbol you want to monitor.Click the Study Alert button in the upper right-hand corner.When the Study Alerts box opens, click the “thinkScript editor” tab.You’ll be presented with “SimpleMovingAvg( )” to get you started. Delete that if you don’t want to be alerted on a moving average. But as an example, this is the code you would write to be alerted if the 30-day moving average moves above the 10-day moving average. There are other controls in the Study Alerts box, like the “Aggregation” period at the top that lets you choose intraday, daily, weekly, or monthly data.
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:
- Click on Application Settings in the platform’s upper right corner.Click the “Notifications” subtab.In the “Notify about” list, choose “Alert is triggered.”Check a notification method under “Alert settings” such as email or SMS. You’ll need a confirmed email address or phone number for SMS to set up alert notifications, which you’ll do at the top of the “Notifications” subtab.
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.