
Thinkorswim moving average crossover scripts are a powerful tool for backtesting and trading strategies. These scripts can help you identify when a short-term moving average crosses above or below a long-term moving average, signaling potential buying or selling opportunities.
The key to a successful moving average crossover script is to set the right parameters, such as the time frames for the short-term and long-term moving averages. For example, a 50-period moving average can be used as the short-term indicator, while a 200-period moving average serves as the long-term indicator.
A well-designed script can also include additional features, such as alerts and stop-loss orders, to help you stay on top of your trades. By automating these tasks, you can focus on higher-level decision-making and avoid emotional trading decisions.
Thinkorswim's platform offers a range of tools and resources to help you create and backtest moving average crossover scripts.
Setting Up the Crossover Script
To set up the crossover script, we need to define our requirements. We should be able to change the moving average length from 8 to 13 or 34 or any other number we wanted. This means we can customize the script to fit our trading strategy.
We also need to be able to change the moving average type, from Exponential to Simple, Hull, Wilders, etc. This is crucial because different types of moving averages can provide varying levels of sensitivity and accuracy.
To achieve this, we can use the MovingAverage() thinkScript function, which allows us to specify the average type, price type, and length. For example, we can use the format MovingAverage(averageType, priceType, length); to define our moving averages.
Here's a breakdown of the requirements we need to meet:
By meeting these requirements, we can create a customizable crossover script that fits our trading needs.
Creating a Custom Indicator
ThinkScript is a powerful tool that allows you to create custom indicators, and it's originally created to enhance technical analysis. You can use the "MovingAverage()" function to define a moving average, which is a key component of many custom indicators.
To define a moving average, you can use the "MovingAverage(averageType, priceType, length);" format. This is where you plug in the input variables, such as the average type, price type, and length. For example, you can use the "MovingAverage()" function to create two moving averages, like the fastMA and slowMA, which can be set as a "plot" variable to show on your ThinkOrSwim charts.
Here's a quick reference to the key terms you need to know when creating a custom indicator:
- def—Defines an item in thinkScript like a definition.
- reference—This command pulls studies into the code already written in thinkScript.
- plot—This command displays what the trader wants to see.
Avg Crossover Requirements
To create a custom indicator, you need to define the requirements of your strategy. This involves identifying the key elements that will drive your indicator's behavior.
A good starting point is to consider the type of moving average crossover you want to implement. For example, using an 8 period EMA crossing with a 21 period EMA as a starting point.
To make your custom indicator flexible, you should be able to change the moving average length from 8 to 13 or 34, or any other number you want. You should also be able to change the moving average type from Exponential to Simple, Hull, Wilders, etc.
Here are the key requirements to consider:
- We should be able to change the moving average length.
- We should be able to change the moving average type.
- We should be able to test moving average crossovers to the bullish side, along with the bearish side.
By defining these requirements, you can create a custom indicator that meets your specific needs and allows for easy experimentation with different settings.
How to Create a Custom Indicator in ThinkScript
To create a custom indicator in ThinkScript, you need to define the variables that will give context clues about the indicator you want to build.
The "MovingAverage()" function is used to define a moving average in ThinkScript, and its format is "MovingAverage(averageType, priceType, length);".
You can use the "MovingAverage()" function to create multiple moving averages, such as fastMA and slowMA, by plugging in the input variables in the appropriate places. These moving averages can be set as "plot" variables to show them on your ThinkOrSwim charts.
ThinkScript input variables allow users to control and change parameters directly via the study's menu, making it easier to modify the code without needing to open and edit it.
To organize your input variables, create a list of all the variables you'll need to define, such as "FastMALength" and "SlowMALength", which allow you to change the length of the fast and slow moving averages.
You can also use the "AverageType" variable to unlock different moving averages supported by ThinkOrSwim, including Simple, Exponential, Weighted, Wilder's, and Hull.
Here's a list of common input variables used in ThinkScript indicators:
- FastMALength: changes the length of the fast moving average
- SlowMALength: changes the length of the slow moving average
- AverageType: unlocks different moving averages (Simple, Exponential, Weighted, Wilder's, and Hull)
- Strategy specific variables: includes quantity for shares/contracts used in backtest P/L reports, longsOnly, and shortsOnly
Step 3: Plot Numbers

Now that we've set up our moving average parameters, it's time to plot the numbers.
You can add the two moving averages directly to the chart, showing how the fast (8-period) and slow (21-period) lines interact.
As market prices fluctuate, these averages provide a dynamic way to track trend shifts.
By plotting the moving averages, you can visually see how they respond to price movements, helping you make more informed trading decisions.
Configuring the Crossover
To configure the crossover, you'll need to define the studies you want to use, such as the 10-day and 30-day simple moving averages. This is done using the "def" command, which defines an item in thinkScript like a definition.
The "reference" command is used to pull studies into the code, and in this case, it's pulling in the "simplemovingavg" study from thinkorswim Charts. This can save users time and energy if a particular study has already been written.
To display the two lines of the simple moving average crossover, you'll need to use the "plot" command, which displays what the trader wants to see. In the example, there are two lines – a 10-day moving average and a 30-day moving average – which are displayed using two lines of code.
Here's a breakdown of the commands used to configure the crossover:
- def: defines an item in thinkScript
- reference: pulls studies into the code
- plot: displays what the trader wants to see
Each line of thinkScript code ends with a semicolon (;), which tells thinkScript that the command sentence is over.
Simple Crossover
The Simple Crossover is a versatile and effective trading strategy that can be tailored to suit different trading styles. It's based on the concept of two moving averages crossing each other, indicating a potential buy or sell signal.
To create a Simple Crossover, you can use the thinkScript Editor to input the following code: def tenday = reference simplemovingavg(length = 10); def thirtyday = reference simplemovingavg(length = 30); plot data1 = tenday; plot data2 = thirtyday;

The key to a successful Simple Crossover is to choose the right moving average lengths. For short-term trading, smaller values like 3 and 8 are ideal, while larger values like 50 and 200 are better suited for long-term investing.
Here are some common moving average lengths used in Simple Crossover strategies:
By adjusting the moving average lengths, you can fine-tune your Simple Crossover strategy to suit your trading style and preferences.
Crossover Labels
Configuring the Crossover is a crucial step in creating a reliable trading strategy.
The Add Label ThinkOrSwim function is used to display the moving average crossover scenario we're testing.
Each moving average type has a key identifier associated with it, which will be helpful when deciding what to show on our labels.
Here's a list of each AverageType and its identifier value:
- Simple Moving Average = 0
- Exponential Moving Average = 1
- Weighted Moving Average = 2
- Wilder’s Moving Average = 3
- Hull Moving Average = 4
We can use these integer values to create a boolean test in the labels, which displays the appropriate moving average in text form.
Testing and Backtesting
Testing and backtesting are essential components of creating a successful thinkorswim moving average crossover script. The backtester we've built can test different moving average crossover strategies on the S&P 500 (SPY) with a daily time frame chart going back 5 years.
You can use thinkScript to test various moving average crossover strategies, such as the 8 EMA x 21 EMA crossover, which resulted in a P/L of $5,662. By tweaking one variable, like changing the slower moving average from 21 to 34, you can see how it affects the P/L.
Backtesting can also be done on thinkorswim charts as a technical analysis tool, allowing traders to see the potential profit and loss (P&L) for hypothetical trades generated on technical signals. This feature can be accessed by right-clicking on a chart's trade signal and selecting Show Report from the drop-down list.
Testing S&P 500
The S&P 500, tracked by the SPY ETF, is a popular choice for backtesting moving average crossover strategies. We tested the 8 EMA x 21 EMA crossover on the SPY Daily Chart and saw a P/L of $5,662 over a 5-year period.
Using a daily time frame chart, we found that changing the slower moving average from 21 to 34 resulted in a slight decrease in P/L. This shows that tweaking one variable can have a significant impact on the strategy's performance.
We also tested the 8 EMA x 34 EMA crossover, which led to a slight decrease in P/L, indicating that the original 8 EMA x 21 EMA crossover was more effective. This highlights the importance of thoroughly testing different variables in a backtesting strategy.
In another test, we changed the slower moving average's length from 34 to 13, resulting in a significant increase in P/L. This suggests that a shorter slower moving average can be more effective than a longer one.
The 8 Simple Moving Average crossing above the 13 Simple Moving Average was the most effective crossover tested, with a P/L of $5,654 over the same time period. This demonstrates the potential for simple moving averages to outperform exponential moving averages in certain scenarios.
Backtesting
Backtesting is a crucial step in testing a trading strategy, and thinkScript makes it surprisingly easy. It allows you to see the potential profit and loss (P&L) for hypothetical trades generated on technical signals.
To backtest a strategy, you can use the thinkScript code to add conditions for buy and sell trades. This is done by using the "addOrder" command, which specifies "BUY_AUTO" and "SELL_AUTO" based on the conditions you set.
The thinkScript code can also be used to add color to buy and sell signals, making it easier to visualize the results. The "tickColor", "arrowColor", and "GetColor" commands can be used to customize the appearance of the signals.
Backtesting can be done on thinkorswim charts, and the results can be viewed by right-clicking on one of the chart's trade signals and selecting Show Report. This will give you a detailed report of the P&L for the backtest.
You can also use thinkScript to recycle code and create new strategies by adding conditions to the existing code. This is shown in the example where a strategy is created using a 10-day moving average crossing above the 30-day moving average to get long, and a 30-day moving average crossing above the 10-day moving average to get short.
The thinkScript code for this strategy is entered into the thinkScript Editor, where you can customize the appearance of the signals and add conditions for buy and sell trades.
Experimenting with Types
ThinkOrSwim provides several moving average types, each with unique characteristics. You can test different types to tailor the indicator to specific market conditions and trading strategies.
The MovingAverage() thinkScript function allows you to experiment with various types. By plugging in different input variables, you can create custom moving averages that suit your needs.
To get started, you can use the format: MovingAverage(averageType, priceType, length);. This will give you a solid foundation for testing different types.
Some types to consider include exponential, simple, and weighted moving averages. Each type has its own strengths and weaknesses, so it's essential to understand their characteristics before making a decision.
Here are some common moving average types and their characteristics:
Weighted
By testing different types, you can refine your moving average strategy and make more informed trading decisions.
Advanced Features
To write a custom technical indicator script, start on the MarketWatch tab and select the Alerts subtab, then enter a symbol.
You can customize different alerts by selecting Edit under the Condition Wizard tab and adding code to the script.
The default script starts with "SimpleMovingAvg( )", but you can delete it if you don't want an alert related to the simple moving average.
To apply custom code and trigger alerts, select the Create Alert button.
To get alert notifications, select Setup in the upper right and then select Application Settings… from the drop-down list.
Check the Alert is triggered box in the Notify about list and select a preferred notification method under Alert settings.
Trading Applications
The Moving Average Clouds Indicator is a powerful tool for traders, offering a range of practical uses for trading.
Identifying trend changes is one of the most useful applications of this indicator. Crossovers between the fast and slow moving averages often signal shifts in trend direction.
A fast MA crossing above the slow MA may signal a buying opportunity, while a cross below could indicate it’s time to sell.
Tracking trend strength is also crucial for traders. When the fast and slow MAs diverge, it usually indicates a strong trend.
If the fast MA continues to stay above the slow MA, it reflects sustained bullish momentum. This can be a strong indication of a trend's strength.
The cloud color gives an immediate view of trend conditions. Green clouds suggest an uptrend, while red clouds indicate a downtrend.
Spotting reversals is another key application of the Moving Average Clouds Indicator. After a sustained uptrend, a crossover of the fast MA below the slow MA could indicate the start of a bearish reversal.
Frequently Asked Questions
What is the best moving average for crossover?
There is no single "best" moving average for crossover, as different combinations work better for various traders, markets, and timeframes. Popular combinations include 9/21/55, 5/10/20, and 20/50/200 EMAs, but the optimal choice depends on individual trading needs and preferences.
What is the best moving average crossover for a 5 minute chart?
For a 5-minute chart, using a 13-period and 200-period moving average crossover is a good starting point, as it has shown promising results in various studies. This combination can be a solid foundation for further exploration and optimization.
How to show moving average in Thinkorswim?
To show a moving average in Thinkorswim, select Studies > Add study > Moving Averages and choose SimpleMovingAvg. This will plot the Simple Moving Average (SMA) on your chart.
Sources
- https://tosindicators.com/backtesters/moving-average-crossover
- https://www.schwab.com/learn/story/coding-traders-building-your-own-indicator
- https://usethinkscript.com/threads/moving-average-crossovers-for-thinkorswim.229/
- https://tosindicators.com/indicators/moving-average-clouds
- https://easycators.com/download/moving-average-crossover/
Featured Images: pexels.com