Automated Trading

The complete beginner's guide to automated trading in ThinkOrSwim, with 8 different trading examples

youtube-video-thumbnail
Always Test in Paper Money

Always test your automated trading strategies in Paper Money first, to find and fix any bugs.

For the 16th episode of “How to thinkScript”, we’ll switch gears and explore writing thinkScript code to achieve as close to automated trading in ThinkOrSwim, as we can.

Now, before I move further, I want to caveat by saying that this technique still requires you to manually write code, every time you’d like the condition to trigger you either into or out of a trade. This is not a recipe to create a ThinkOrSwim algo trading bot.

There is no way (at least that we’re aware of) to have fully automated trading in ThinkOrSwim (at least the platform).

That being said, this is still an incredibly powerful way to take advantage of patterns that you may have found on longer time frame charts. The reason we focus on longer time frame chart is trade ideas here typically require you to be more patient, and to keep monitoring the charts to see whether or not your trade conditions are true.

However, if you have a process-driven approach, much of this is mechanical, and can be outsourced to the actual ThinkOrSwim platform to try and automate as much of the trading process as possible.

Keep in mind, most of this is experimental, so you should ALWAYS test out your ideas and code in PaperMoney first.

Let’s get started!

Volatility Box Invite

We are TOS Indicators.com, home of the Volatility Box.

The Volatility Box is our secret tool, to help us consistently profit from the market place. We’re a small team, and we spend hours every day, after the market close, doing nothing but studying thousands of data points to keep improving and perfecting the Volatility Box price ranges.

We have two different Volatility Boxes - a Futures Volatility Box and a Stock Volatility Box.

Futures Volatility Box - Trade Major Markets With an Edge

Designed For: Futures, Micro-Futures and Index Market Traders
Supported Models: Hourly Volatility Box models
Supported Markets: 10 Major Futures Markets

The Futures Volatility Box comes with:

  • 5 Volatility Models for each market
  • Support for 10 Futures Markets (/ES, /NQ, /YM, /RTY, /CL, /GC, /SI, /ZB, /HG, /NG)
  • Video Setup Guide
  • Trade Plan
  • Access to all members-only resources, including Squeeze Course

Learn More About the Futures Volatility Box

Trade futures and micro futures with a consistent volatility edge

Stock Volatility Box - Powerful Web Based Volatility Platform

Designed For: Stock and Options Traders
Supported Models: Hourly and Daily Volatility Box models
Supported Markets: 10,000+ Stocks and ETFs (new markets added frequently)

A Stock Volatility Box membership includes access to: 

  • Live Scanner - A powerful scanner we've built from scratch, to scan 10,000 symbols every 2 seconds for new volatility breaches
  • Dashboard - A quick and easy way to view daily volatility model levels online
  • Short Interest Scanner - Short interest, Squeeze, and EMA data to find short squeezes
  • Squeeze Course - All of our proprietary squeeze tools, including robust backtesters
  • All Members Only Indicators - We don't nickel and dime you. Everything really is included.
  • And much more!

Why Automated Trading?

Most of the time, we find trade ideas and patterns that we’ve backtested to great lengths (or that others have), which we’d like to replicate. Very little is original in terms of new trade ideas or patterns.

Much of what separates a successful trader to a non-successful trader is the ability to execute on your actual plan. And of course, we all have a plan, until it comes time to actually enter that trade.

Pros and cons of automated trading in ThinkOrSwim

One of the advantages to automated trading in ThinkOrSwim is that we can build this plan via code, and actually set in play to execute on its own, whenever those conditions are true.

This helps us not only eliminate emotions at the time of execution (i.e. will the stock keep falling further?), but it also lets us not have to sit there and worry about checking the charts of SPY daily to see whether or not the trade has triggered.

Now, multiply this by as many strategies as you have and you can start to see where the challenge arises in managing those multiple positions.

So, that brings us to the biggest advantage of this entire concept of automated trading in ThinkOrSwim – you can outsource as much of the machine work to the ThinkOrSwim platform in itself.

Of course, automated trading in ThinkOrSwim doesn’t come without its own set of shortcomings.

It's not a platform meant for auto-trading, to be clear.

Let me repeat that one more time.

It is NOT a platform meant for auto-trading.

We push the platform to its limits, and get close to semi-automated trading, but there are still a hefty set of shortcomings.

The biggest one that you’ll notice as you start to explore the functionality, is that it’s incredibly limited in terms of the studies, and built-in functions that it supports.

For example, as you try to reference some of the previously built studies that we have, such as the Market Pulse or VScore, you’ll be met with a flood of errors. Some around the complexity of the study. Some around how rec usage is not supported.

All of this to say – the automated trading triggers pane is more limited, in terms of the coding depths it supports, compared to the ThinkOrSwim studies menu.

Apart from that, the other obvious disadvantage is losing the ability to revise any decision making at the actual time of entry, given the additional data that you now have on your charts (both in terms of price action, volume, and your own indicator studies).

Based on your trading style though, if you are usually more fearful to do things like buy pullbacks in trends, well – this should then help you eliminate that fear, by creating an auto-trade condition to buy Microsoft any time it pulls back into the 34 EMA, as an example.

So, how can we most efficiently use the automated trading in ThinkOrSwim to benefit our trading?

 

What is the Automated Trading Triggers Window?

To navigate to the automated trading window, you need to first have an order that you’re building inside of ThinkOrSwim.

Automated Trading in ThinkOrSwim - Triggers Window

Once you have an order in the “Trade” tab, you can then click the settings gear icon, to open up the automated trading panel:

Automated Trading Triggers Window Description by TOS Indicators

Let’s go through some of these options to see what you can control:

  • Limit Linked To – this lets you control whether you’d like to link the execution price to the bid, ask, mid-price, last, etc. If you were looking to buy on a pullback, you may have your limit linked to the “Bid” or “Mid” to avoid overpaying at the market.
  • Conditions – you can customize the method to be a study, where we can input custom thinkScript code and reference previously build studies to incorporate our own set of automated trading conditions

Let’s brainstorm some potential ideas, that we would want to auto-trade. Of course, these are just examples to help you get started.

 

8 Trigger Scenarios That We Will Build

  • Scenario 1: Buy MSFT if it crosses above $175 in the first 15 minutes
  • Scenario 2: Sell HD Iron Condor when price is between $195 and $200
  • Scenario 3: Sell a covered call on pre-existing 100 shares in LVGO when price hits the 2.00 extension to collect “rent” on a profitable position
  • Scenario 4: Buy a pre-selected put when RSI is showing breakout signals
  • Scenario 5: Buy stock if we get a pullback to the 34 EMA, with the moving averages all being stacked, triggered with an OCO order
  • Scenario 6: Close my position when squeeze momentum starts to decline
  • Scenario 7: Buy pre-selected call if we have a squeeze, with greater than avg. volume, and EMAs agreeing with the direction
  • Scenario 8: Buy on Implied Volatility pullbacks in a strong uptrend for the stock. Simultaneously, place a GTC exit order whenever moving averages are no longer stacked, on a lower time frame.

 

Scenario 1: Nightly Trending List

So the built-in study is going to be our base. It seems to match even the s

For Scenario 1, we’ll use our Nightly Trending List that we e-mail to our Stock Volatility Box subscribers as a sample condition.

Each day, we go through the day’s trading activity to find stocks and ETFs that are likely to trend the next day. This list is e-mailed to all Stock Volatility Box members ahead of the next day's trading activity.

 

 

We’d like to buy Microsoft (MSFT), as an example, if it crosses above $179.18 within the first 15 minutes.

No code is required here, but instead, just some simple customizing of the conditions in the Automated Trading Triggers pane in ThinkOrSwim.

MSFT Automated Trading in ThinkOrSwim, using Volatility Box Trending List

And that’s scenario 1, all done. Moving onwards to Scenario 2.

 

Scenario 2: Iron Condor When in Consolidation

For Scenario 2, let’s assume that you’re looking at a period of potential consolidation in HD we’d like to sell an Iron Condor whenever price is between $195 and $200.

That happens to also overlap with the Market Pulse indicator line, which gives you reason to believe we'll chop sideways for a bit.

Again, keep in mind, these are all just for demonstrative purposes - NOT real trades, so please don't go placing them.

HD Consolidation - Automated Trading, Iron Condor.

You may be looking at a period of consolidation in Home Depot, but want to get a slightly better entry on the Iron Condor so you’d like to wait for price to fall.

Here, the code for the automated trading in ThinkOrSwim is quite simple:

plot signal = if close >= 195 and close < 200 then 1 else 0; 

This lets us place the order conditions, and you may link it to something like the ask to avoid overpaying or even the mid-price, and set this as a GTC order.

If it gets filled, fantastic.

You can even set an expiration date, if you’d only like this order to be valid through the end of this week.

 

Scenario 3: Automatic Covered Call for Income at Fib Extensions

Here, let’s assume that you already own 100 shares of Livongo Health (LVGO). LVGO has made a pretty nice move to its 1.618 retracement.

LVGO Automated Trading - Covered Call Strategy in ThinkOrSwim

Now let’s say that you don’t think it can go much higher above the 2.000 retracement at $44.88.

You use the Covered Call Calculator to also find the $45 calls to have some relatively "juicy" premium associated with it.

Instead of having to sit there and watch the position (or even set an alert to revisit the thought later), you’d like to automatically sell a covered call against your pre-existing 100 shares.

You'd like to use the automated trading in ThinkOrSwim to automatically sell a $45 strike call, when price hits the 2.00 retracement level at $44.88.

Think of this as collecting rent, on an already profitable position.

Let’s create that.

Again, we don’t need any code here.

We can build the conditions using the editor.

First, we head to the options chain to choose the $45 strike call, and we go to edit the options of the automated trading pane:

LVGO Automated Trading ThinkOrSwim Triggers Window Setup

We’d like to join the bid to collect the greatest credit we can (or even the mid, if you prefer), and you can set the order to GTC.

 

Scenario 4: Buy Put When RSI Shows Bearish Breakout Signals

For Scenario 4, we’ll use the built in RSI signals to buy a put whenever we have a bearish breakout signals. Now, the larger the time frame, the more powerful the signal should be.

Let’s assume we’re doing this on a daily SPY chart, so we may want to buy a Put that is at least 90 days out, to give not only ourselves time, but also the trade without needing to re-update the Trigger conditions (with the next month’s strike).

Here, our code is fairly simple, and we attach this to the Triggers pane of the put we’d like to use:

plot signal = RSI().DownSignal[1];

That tiny, one-liner of code is enough to trigger the automated trading in ThinkOrSwim to place an order whenever we have that down signal.

We use the array "[1]" to reference the previous bar, to confirm that the signal has actually finished printing, instead of still being in progress.

 

Scenario 5: Buy Stock on Pullbackto 34 EMA

This time, we’ll write some thinkScript to enter into a stock that has stacked moving averages (8 EMA x  21 EMA x 34 EMA). If we have stacked moving averages, let’s say bullish, then we can assume that we have a bullish trend.

This is a concept we've talked about in previous tutorials, including the Simple Breakout Tool tutorial.

And with a trend, we can buy trend pullbacks, to whichever EMA we prefer (in this case, we’re using the 34 EMA).

Automated Trading AAPL Trend Pullback

Here is the code, all written out so that it's easy to copy/paste:

def EMA8 = ExpAverage(close, 8);
def EMA21 = ExpAverage(close, 21);
def EMA34 = ExpAverage(close, 34);
def stacked = if EMA8>EMA21 and EMA21>EMA34 then 1 else 0;

plot signal = if stacked and close <= EMA34 then 1 else 0;

 

Scenario 6: Sell Position When Squeeze Loses Momentum

In our second to last scenario, we’ll assume that you’re already in a position, ideally because of the TTM_Squeeze.

Once the squeeze fires, you’d like to get out as soon as the histogram bars show us that we’re starting to lose momentum.

If you've already watched our Squeeze Course, you know that the squeeze firing has usually been a good time to exit any trades. You're usually able to lock in the most profit, using that method.

Automated Trading With the TTM Squeeze and the Histogram

Here, you're using the automated trading in ThinkOrSwim to let you manage an existing position, instead of enter a new one.

Let’s write the code :

plot signal = if TTM_Squeeze().Histogram[1] < TTM_Squeeze().Histogram[2] then 1 else 0; 

 

Scenario 7: Layering on Multiple Indicators

For the 7th scenario in this semi-automated trading series, we’re going to take a look at combining multiple conditions into one trigger.

The concept that I’m really trying to get across here is less about the actual conditions I’ve chosen, and more about the idea that you can layer on multiple “basic” indicators, and bypass some of the complexity errors in ThinkOrSwim.

The specific condition we’re going to look at here is buying a pre-selected call if:

  • We have a TTM Squeeze
  • Greater than average volume
  • EMAs agreeing with the overall trend

Here's the code that we use for the above conditions:

def EMA8 = ExpAverage(close, 8);
def EMA21 = ExpAverage(close, 21);
def EMA34 = ExpAverage(close, 34);
def bullish = if EMA8 > EMA21 and EMA21 > EMA34 then 1 else 0;
def squeeze = if TTM_Squeeze().SqueezeAlert == 0 then 1 else 0;
def greaterVol = VolumeAvg().Vol > VolumeAvg().VolAvg and close > close[1];

def conditions = bullish and squeeze and greaterVol;
plot signal = conditions[1]; 

 

Scenario 8a: Buy on Implied Volatility Pullbacks (Entry)

For our last and final scenario, we have two parts. In part 8a, we’re going to look at coding the entry components, which is going to be around the idea of buying on Implied Volatility pullbacks to the 34 EMA.

Yes, you read that correctly.

We’re going to run exponential moving averages using Implied Volatility as the data input, in lieu of the close price, and buy on IV trend pullbacks in otherwise strong trends on the actual underlying.

And, that is going to be built into code for automated trading in ThinkOrSwim.

You can also backtest this using our free Moving Average Pullback Backtester, if you'd like to test the strategy.

The goal to convey here is that you can go multiple layers deep in terms of analysis, and can very easily see when these trigger conditions were true, and what happened after.

The thing we’ll do differently here is “Buy custom” and link a close order with our entry order (i.e. Buy Custom with Stop)

MSFT Buy Custom to set up the Automated Trading Window

Here's our entry code:

def EMA8 = ExpAverage(close, 8);
def EMA21 = ExpAverage(close, 21);
def EMA34 = ExpAverage(close, 34);
def stacked = if EMA8 > EMA21 and EMA21 > EMA34 then 1 else 0;
	
def ImpVol = IMP_VOLATILITY();
def IV8 = ExpAverage(impVol, 8);
def IV21 = ExpAverage(impVol, 21);
def IV34 = ExpAverage(impVol, 34);
def IVstacked = if IV8 > IV21 and IV21 > IV34 then 1 else 0;

def conditions = if stacked and IVstacked and ImpVol<= EMA34 then 1 else 0;
plot signal = conditions[1];
MSFT Automated Trading Entry - TOS Indicators Tutorial

 

Scenario 8b: Sell When Trend Breaks

And finally, we’d like to add some custom code to the second component of the order – the sell order, as part of that custom order type we had built.

Here, we’ll link the closing order to the EMAs.

This is our exit code:

def EMA8 = ExpAverage(close, 8);
def EMA21 = ExpAverage(close, 21);
def EMA34 = ExpAverage(close, 34);
def stacked = if EMA8 > EMA21 and EMA21 > EMA34 then 1 else 0;
	
def conditions = if stacked[2] and !stacked[1] then 1 else 0;
plot signal = conditions;

This is to say that when the 3 EMAs are no longer stacked, we will close out the trade, either for a gain or a loss.

MSFT Sell Side Automated Trading - ThinkOrSwim Tutorial

This is what the final trigger order should look like, with both the buy and sell custom codes:

MSFT Automated Trading with Entries and Exits - ThinkOrSwim Tutorial

And voila!

We're done.

We walked through 8 different "scenarios" that are fairly close to realistic setups that you may have, and we tried to get as close as we could to a ThinkOrSwim auto trading bot (the closeset you will get to a ThinkOrSwim bot).

The system is still not perfect, but it should still serve to be convenient and reward the hard work of finding the setup in the first place.

 

What Else Can I Do?

Now that you have the fundamental knowledge with regards to using automated trading in ThinkOrSwim functionality, you can take this in whichever direction you'd like.

Some examples include:

  • Test your own setups
  • Try automating some of our setups, like the V-Shaped Reversal setup
  • If you face “complex” errors, break apart the indicator components to see if you can find another way to calculate the same trigger
  • Use PaperMoney as a sandbox environment
  • Use GTC orders to run experimental trade setup ideas you may be looking at to test their expectancy and probabilities (“free semi-automated backtesting”)
  • Expand into ThinkOrSwim forex and futures markets to test (with 24/7 trading hours)
  • Push the capabilities of the platform and test different order types, multiple TRG brackets with custom studies, etc.

 

Download

Click the button below to download the PDF with code snippets for Semi Automated Trading in ThinkOrSwim.

Learn More About the Stock Volatility Box

Trade stocks and options with a consistent volatility edge

Table of Contents
    Add a header to begin generating the table of contents

    Trade Like a Pro, With the Pros