Thinkscript – An Introductory Guide

7 min read

Get 10-day Free Algo Trading Course

Last Updated on September 4, 2022

Table of contents:

  1. What is Thinkscript?
  2. Is Thinkscript Free?
  3. What is Thinkscript used for?
  4. Why should I use Thinkscript?
  5. Why shouldn’t I use Thinkscript?
  6. What is thinkorswim?
  7. How to get started with Thinkscript?
    1. Thinkscript main layout
  8. What are Thinkscript fundamentals?
  9. How to use Thinkscript fundamentals?
  10. What are Thinkscript Declarations?
  11. How to use Thinkscript Declarations?
  12. What are Thinkscript functions?
  13. How to use Thinkscript functions?
  14. What are Thinkscript Constants?
  15. How to use Thinkscript Constants?
  16. What are Thinkscript Operators?
  17. What are Thinkscript Alerts?
  18. How to set Alerts with Thinkscript?
  19. What are Thinkscript drawings?
  20. How to use Thinkscript drawings?
  21. What are Thinkscript tech indicators?
  22. What are Thinkscript patterns?
  23. How to use Thinkscript patterns?
  24. How to add simulated trades in Thinkscript?
  25. How to place orders with Thinkscript?
  26. How to create your own strategy with Thinkscript?
  27. Where can I learn more about Thinkscript?

What is Thinkscript?

Thinkscript is a programming language for the Thinkorswim trading platform that allows its users to backtest strategies and build tools such as watchlists, indicators and more.

Thinkorswim is the trading platform for the broker TD Ameritrade.

Can I trade automatically using Thinkscript?

As of 7th March 2022, no.

Is Thinkscript free?

Downloading and using Thinkscript is free, only when it comes to trading do the fees apply. The commissions follow the current TD Ameritrade Thinkorswim TOS costs.

You can find the summarized trade fees in the following table below:

Product Price
Stocks and ETFs 0
Stocks and ETFs broker-assisted
25
Options $0.65 per contract
No-load mutual funds 49.99
Treasuries at auction 25
All other bonds and CMOs, CDs
on a net yield basis
Futures
$2.25 fee per contract (plus exchange & regulatory fees)
Forex
Non-commission currency pairs trade in increments of 10,000 units. There are no additional fees or charges.

What is Thinkscript used for?

Thinkscript can be thought of as a tool that allows you to run trading analysis, backtest strategies, build watchlists and set up alerts for financial data.

Why should I use Thinkscript?

  • Thinkscript is free to play with
  • Has a backtesting feature
  • Has great charting and analysis tools
  • Offers Futures, Options, Stocks, and Forex
  • Fully customizable
  • Has paper trading
  • Has a mobile and desktop app
  • Offers educational materials

Why shouldn’t I use Thinkscript?

  • Can be a bit pricey when compared to other brokerages
  • Has a steep learning curve
  • Due to the vast amount of customizations, it can be confusing for beginners

What is thinkorswim?

Thinkorswim is the TD Ameritrade’s trading platform that allows its users to trade, analyze and chart the financial markets.

How to get started with Thinkscript?

To get started with Thinkscript, you will first need to download the app. In order to do this, go over to the following link and select your OS. Then click “install thinkorswim” and follow the installation instructions.

While you wait for the program to download and install, go over to the following link and in the upper-right corner click the green “Open New Account” sign.

After that, be sure to go over the sign-up steps in order to properly create an account. When done, open your thinkorswim app and log in with your account credentials. Then you will need to accept the ToS.

Note: when logging in you can choose if you want to use Live Trading or Paper Money.

Thinkscript main layout

On the main toolbar that is situated on top of your interface, you can find the main windows. Each of the windows has its own (sub)toolbars. Let’s go over what each of the main windows represents:

  • Monitor – tracks your trading activity and includes trading data like orders, balances, trading account status, statements, and more.
  • Trade – contains interfaces that categorize the tradable assets, i.e. Forex, Futures, Pairs, and more.
  • Analyze – has a plethora of analysis models that you can run in real, “what if” and backtesting scenarios.
  • Scan – this serves as a filter with which you can hone in on your assets of interest.
  • MarketWatch – provides you with useful market data
  • Charts – provides a graphical interface for real-time data
  • Tools – has several custom thinkorswim features.

To start scripting go to the Charts window, select a symbol from the symbol table, click “Studies” in the upper right corner, select “Edit Studies” and then click “Create”.

If this looks overwhelming to you, you are not the only one and by the end of this article, you will understand the basic components and available features of this program.

What are Thinkscript fundamentals?

Thinkscript fundamentals relate to the open, high, low, close, and volume values. You use these values as the foundational blocks upon which you build your custom scripts.

How to use Thinkscript fundamentals?

Thinkscript fundamentals can be seen as your basic building blocks. For example, in the opened script screen you can change the green “close” into an “open” to see the change in your graph.

Have in mind that you need to press “OK” in the down right corner of your script interface to create the script. Then click apply and you will see a blue line that appeared on your chart.

To go back into the editing mode, find your study in the left “Studies” panel. If you didn’t name it, the name should be “NewStudy0”. To open the script right-click on its name and press “Edit”

What are Thinkscript Declarations?

Thinkscript declarations are your basic operators that can change the mode or setting of your charts and values. To initialize a declaration you need to use the declare command.

The main declarations are the following:

  • hide_on_daily
  • hide_on_intraday
  • lower
  • on_volume
  • once_per_bar
  • real_size
  • upper
  • weak_volume_dependency
  • zerobase

How to use Thinkscript Declarations?

Thinkscript declarations need to be initialized with the declare command. For example, let us use the upper declaration to create a price oscillator for our closing BTC values.

We will to this by having the upper declaration place a weighted moving average plot on our main BTC chart.

declare upper;

input price = close;
input length = 9;

plot AvgWtd = wma(price, length);

P.S. if you click apply in the scripting mode you can see a glimpse of your main chart but to see it in its full glory you’ll need to close the scripting interface.

What are Thinkscript functions?

Thinkscript functions are your usual programming functions that have predefined data processing steps and outputs. In Thinkscript, they are organized into the following categories:

  • Fundamentals
  • Option Related
  • Technical Analysis
  • Mathematical and Trigonometric
  • Statistical
  • Date and Time
  • Corporate Actions
  • Look and Feel
  • Portfolio
  • Profiles
  • Stock Fundamentals and other

How to use Thinkscript functions?

In order to use Thinkscript functions you will need to navigate to their respective drop menu that is found on the right side of your scripting station. When there you can easily explore the available functions.

For an example, let us create an exponential moving average on our BTC data:

input additionalBars = 0;
plot ExpAvg = EMA2(close, additionalBars, 0.2);

I will also add an implied volatility graph that will appear in the lower section on the main Graph window:

declare lower;
plot ImpliedVolatility = imp_volatility();

What are Thinkscript Constants?

Thinkscript constants are values that you can declare that are constant aka they don’t change throughout the script. They are often used with Thinkscript functions and some of the available ones are the following:

  • AggregationPeriod
  • Alert
  • AverageType
  • ChartType
  • Color
  • CrossingDirection
  • Curve
  • Double
  • EarningTime
  • Events and more

How to use Thinkscript Constants?

To use Thinkscript constants all you need to do is to define them prior to their use in your scripts. To define a constant you can use the def command that is followed up by your custom constant name.

For our BTC chart, we will add a constant that will aggregate the candles by month and print out the closing prices for monthly periods.

def agg = AggregationPeriod.MONTH; 
plot data = close(period = agg);

What are Thinkscript Operators?

Thinkscript operators serve you to avoid writing complicated functions that reshape the data into the form you need it in. The Operators are categorized in the following way:

  • Arithmetic
  • Comparison
  • Conditional
  • Indexing
  • Logical
  • Operator Precedence

What are Thinkscript Alerts?

Thinkscript Alerts are used to notify you if a certain requirement is met. With Thinkscript, you can make your own custom alters that will scout the opportunities for you.

How to set Alerts with Thinkscript?

To set an alert with Thinkscript you will need to use the Alert() command inside of which you specify the condition, text, alert type, and sound. There are different alert types that you can set and they are the following:

  • Alert.BAR – triggers only once per bar
  • Alert.ONCE – triggers only once after adding the study
  • Alert.TICK – triggers on each alert tick

The sounds that are available for you alerts are chimes, bells, dings, rings, or soundless.

Now, let’s create an alert that will notify us when the asset reaches the closing price of $300. We’ll want the alert to display a message, alert us on each tick and do a ding sound.

Alert(open == 300, "Open price reached $300!", alert.TICK, Sound.Ding);

What are Thinkscript drawings?

Thinkscript drawings are used to add visual indicators to your charts that can help you in your technical analysis. The drawings are categorized in the following way:

  • Basic
  • Fibonacci
  • Regression
  • Advanced

How to use Thinkscript drawings?

Thinkscript Drawings can be used by right-clicking on your main graph in the Chart window and then selecting the “Add a drawing” button. There you will find a menu of all available drawings.

I’ll add a few random lines to the chart:

What are Thinkscript tech indicators?

Thinkscript tech indicators are pre-determined studies and strategies that you can use for various calculation, charting, and backtesting purposes. Studies and Strategies come with their own libraries that you can try out.

What are Thinkscript patterns?

Thinkscript patterns are a way to display your data that can help you with noticing current and/or future trends in the asset of choice. There are mainly three patterns and they are the following:

  • Candlestick patterns
  • Fibonacci patterns
  • Classical patterns

How to use Thinkscript patterns?

In order to use Thinkscript patterns, you will need to access your Charts window and in the upper right corner, you will find a “Patterns” button. Be sure to click it and when there you can press “Select patterns”.

I’ll select a Classic Flag pattern that is a formation that appears as a small channel after a steep trend. It will indicate an opposite direction of the said trend.

How to add simulated trades in Thinkscript?

To add a simulated trade in Thinkscript, you will go to the Analyze window and then select the “Add Simulated Trades” button. Then select the asset you would want to trade. I’ll go for the Google stock.

To simulate a trade just click on the Bid to sell, or to the Ask to buy, and underneath your orders will appear where you will be able to set up the number of shares.

To step up the game, you can click on a specific time period and change the calls by adding different strike values, custom quotes, instrument details, and much more.

How to place orders with Thinkscript?

To place an order with Thinkscript, all you need to do is to go over to the Trade window where you can select your asset and then buy or sell it by clicking the Bid and/or Ask buttons.

As you have clearly noticed, the interface looks the same as in our previous simulated trading demonstration. This was done by the developers to not induce confusion in the users.

To place an order via code you will need to use the following function:

AddOrder(type, condition, price, tradeSize, tickColor, arrowColor, name); 

How to create your own strategy with Thinkscript?

Now that we have grasped the basics behind Thinkscript, we are ready to create a simple trading strategy. For this, we will use the Dropbox asset. We will want to buy when the asset crosses above the 20 SMA and vice versa.

Each time the asset crosses the 20 SMA we will be notified by an alert. The buy orders will be displayed in green while the sell order will be displayed in red. We will only want to buy 20 shares of the stock upon each cross.

input price = close;
input length = 20;

def AVG = Average(price, length);

Alert(AVG < price, "The closing price is bellow the 20 SMA: "+price, alert.TICK, Sound.Ding);
Alert(AVG > price, "The closing price is above the 20 SMA: "+price, alert.TICK, Sound.Ding);

AddOrder(OrderType.BUY_AUTO, price crosses above avg, open[-1], 20, Color.GREEN, Color.GREEN, “Buy”);
AddOrder(OrderType.SELL_AUTO, price crosses below avg, open[-1], 20, Color.RED, Color.RED, “Sell”);

Now that the strategy is done, we can apply it and check for its performance by right-clicking the signal and selecting “Show report”.

Where can I learn more about Thinkscript?

To learn more about Thinkscript, you can go over to their Learning Center

Igor Radovanovic