Coding for Traders: Building Your Own Indicator

August 28, 2023 Advanced
The thinkorswim® platform offers a way for traders to code their own indicator customized to their specifications so they can make more informed trading decisions.

thinkScript®, one of many tools available on the thinkorswim® platform, allows traders to customize indicators to their needs, and it doesn't require any special programming knowledge to use the tool. Let's look at how to use thinkScript to create an indicator that can help traders make more informed decisions.

How to use thinkScript

thinkScript is most frequently accessed from the Charts and MarketWatch tabs. It's similar to adding a technical study because the thinkScript Editor lets traders write the thinkScript code from Charts > Studies or MarketWatch > Quotes.

How to start a script using the Charts tab

1. Select the Studies button.

2. Select Edit studies… from the drop-down list. A new window, Edit Studies and Strategies, appears in a pop-up window. 

3. Select Create in the lower left corner. The thinkScript Editor opens with a default code. Delete that code and type in your own code to start customizing (see image below).

Image shows the thinkScript Editor under the thinkorswim Charts tab. It includes an example of code as well as a menu of potential commands and functions.

Source: thinkorswim platform

For illustrative purposes only.

A menu of thinkScript commands and functions are listed on the right side of the editor window. Definitions of the commands and functions appear when a trader selects one. Selecting a function or command moves it to the script box.

How to start a script using the MarketWatch tab

1. On the MarketWatch tab, select Quotes in the top menu.

2. From the Quotes page, select the small gear at the upper right.

3. Select Customize… from the drop-down list.

4. Scroll down the list of Available Items and select one of the numbered custom choices.

5. Double-click the custom item to open a new window, Custom Quote Formula, and select the thinkScript Editor tab. 

6. Again, traders can add code items from the menu to the right. Use the Apply and OK buttons to make changes. When finished, the custom quote is added to the chart.

Sample custom indicators

Simple moving average crossover

thinkScript was originally created to enhance technical analysis. Below is the code for the simple moving average crossover demonstrated in the chart below. The chart illustrates 10-day and 30-day simple moving averages. With the thinkScript Editor open, a trader could potentially enter the following code:

Enter this example script: def tenday = reference simplemovingavg (length=10); def thirtyday = reference simplemovingavg (length=30); plot data1 = tenday; plot data2 = thirtyday;

Source: thinkorswim platform

What do these terms mean? Let's clarify:

  • def—Defines an item in thinkScript like a definition. In this instance, the direction is to "define tenday" to reference the study simplemovingavg, which uses 10 bars of data. Additionally, there's a line of code to define "thirtyday" as a simple moving average that uses 30 bars of data.
  • reference—This command pulls studies into the code already written in thinkScript. Developers have already created hundreds of studies. Using "reference" when possible might save users time and energy if a particular study has already been written. Here, thinkScript is pulling in a study called "simplemovingavg from thinkorswim Charts." 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—After inputting the code, the plot command displays what the trader wants to see. In the example above, the simple moving average crossover, there are two lines—a 10-day moving average and a 30-day moving average. To display the two lines, a trader must have two lines of code, and name them each something different. In this example, "plot data1" and "plot data2" are used.

At the end of each line of thinkScript code a semicolon (";") that tells thinkScript this command sentence is over. Red highlights on the code indicating mistakes that might prevent the code from inputting correctly.

With practice and knowledge, traders can add a range of custom colors and styles to this crossover study to fine-tune their experience.

Custom indicator example: Simple moving average crossover

Chart shows how a custom simple moving average crossover script appears on the chart.

Source: thinkorswim platform

For illustrative purposes only.

Custom volatility

Traders who want options data that doesn't currently exist as a platform feature can create it. thinkScript allows a watchlist to show almost any custom column a trader creates. One statistic from Today's Options Statistics is Current IV Percentile. That percentage shows the current overall implied volatility of a stock's options relative to its past year's high-to-low range. However, if a trader wants to see IV percentile for a different time frame, it's possible to adjust the view using thinkScript.

Image illustrates the results of writing a script that shows three months of volatility instead of 12 months.

Source: thinkorswim platform

For illustrative purposes only.

Following the steps described above for the Quotes scripts, a trader could enter the following code in the thinkScript Editor:

Enter this example script: 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);/

Source: thinkorswim platform

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 provides the platform's "Vol Index" number, which is the overall implied volatility of a stock's options. The "if !IsNaN" indicates that the results should return 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 defined items.

It's possible to change the 60 used in the code to any number for the range. Each month has about 20 trading days, so 60 trading days is about three months. To show a yearly number, use 262, which is approximately the number of trading days in a year. To add this to a watchlist, follow these steps on the MarketWatch tab:

1. Select the Quotes subtab.

2. Select the small gear in the upper-right corner and then select Customize … from the drop-down list to bring up the Customize Quotes box.

3. Select one of the Custom choices to open the Custom Quote Formula box and select the thinkScript Editor tab and write in the code. After a trader is finished adding in the code, they can create a name for the code that describes it. Creating a naming convention for custom codes makes it easier to find and apply the code to different charts and watchlists later.


thinkScript can also be used on thinkorswim charts as a technical analysis backtesting tool. With this feature, traders can see the potential profit and loss (P&L) for hypothetical trades generated on technical signals. Traders should remember that strategy-generated P&L values don't include theoretical commission costs.

Backtesting with thinkScript

Chart illustrates the results of turning custom indicators into a strategy backtest. With the script for the 10- and 30-day moving averages from above, it's possible to plot how many times they cross over a given period.

Source: thinkorswim platfrom

For illustrative purposes only.

The chart above shows 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 the 30-day moving average crosses above the 10-day moving average. It's possible to recycle some of the code used in the above chart study, but we need to add conditions to backtest buy and sell trades to the code.

To access the strategy creation menu, follow these steps:

1. On the Charts tab, select Studies > Edit studies… from the drop-down list.

2. From the Edit Studies and Strategies box, select the Strategies tab to the left.

3. Select Create in the lower left corner. When the thinkScript Editor opens, enter the following script:

Enter this example 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));

Source: thinkorswim platform

4. Assign the script a clear name like MovingAvgCross.

5. Select OK in the lower right to close the thinkScript Editor, then select Apply.

Notice the buy and sell signals on the above chart. To see P&L for the backtest, carefully right-click one of the chart's trade signals. Then, select Show Report from the drop-down list. The thinkScript code does this through the "addOrder" 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 a trader 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.

Script alerts

The alert functionality on the thinkorswim platform allows traders to write custom technical indicators and have messages sent to their mobile device when the indicator reaches a certain level or value.

1. On the MarketWatch tab, select the Alerts subtab, and enter a symbol.

2. Select the Study Alert button in the upper right to open the Study Alerts box. Select the thinkScript Editor tab.

3. The default script starts with "SimpleMovingAvg( )". If the trader doesn't want an alert related to the simple moving average, they can delete the script. However, by selecting Edit under the Condition Wizard tab, it's possible to add code to customize different alerts, such as the 30-day moving average moves above the 10-day moving average. There are additional controls in the Edit Condition box to customize the code.

There's also the "Trigger If" menu that can provide an alert when a thinkScript study meets the conditions set by the trader. The Create Alert button applies the custom code to trigger alerts.

To get alert notifications follow these steps:

1. Select Setup in the upper right, and then select Application Settings… from the drop-down list.

2. Select the Notifications subtab.

3. In the Notify about list, check the Alert is triggered box.

4. Check a preferred notification method under Alert settings, which appears when a Notify about item is selected.

After learning more about the features available on thinkScript, traders can set up their own preferences and alerts to better match their trading strategy and style.

The information provided here is for general informational purposes only and should not be considered an individualized recommendation or personalized investment advice. The investment strategies mentioned here may not be suitable for everyone. Each investor needs to review an investment strategy for his or her own particular situation before making any investment decision.

All expressions of opinion are subject to change without notice in reaction to shifting market conditions. Data contained herein from third-party providers is obtained from what are considered reliable sources. However, its accuracy, completeness, or reliability cannot be guaranteed.

Examples provided are for illustrative purposes only and not intended to be reflective of results you can expect to achieve.