Skip to main content Moving Average Pullback Backtester (FREE) - TOS Indicators Skip to main content Skip to content
Master the TTM Squeeze with our comprehensive 19-module course Start Learning →
TOS Indicators
  • Tools

    Categories

    • Indicators
    • Backtesters
    • Scans
    • Dashboards
    • thinkScript
    • Member Resources
    Browse Full Library

    Featured Tutorials

    Heiken Ashi Trend Indicator
    Heiken Ashi Trend Indicator
    Indicators

    Download our Custom Heiken Ashi indicator for ThinkOrSwim. Full ThinkScript code, formula...

    Learn more →
    Commodities Tracker
    Commodities Tracker
    Indicators

    For acceleration signals: trend-following strategies and buying pullbacks. For deceleration signals: short...

    Learn more →
    Build an Election Backtester in 10 Minutes
    Build an Election Backtester in 10 Minutes
    Backtesters

    Learn how to create a Post-Election Backtester in ThinkOrSwim to analyze market...

    Learn more →

    Popular Posts

    Unusual Volume
    Unusual Volume
    Scans

    Build 4 scans to easily find stocks with greater than...

    Learn more →
    Upcoming Earnings with High Short Interest
    Upcoming Earnings with High Short Interest
    Scans

    Build a scan to find stocks that are likely to...

    Learn more →
    Unusual Volume Pro Scans
    Unusual Volume Pro Scans
    Scans

    4 additional scans to find unusual volume overlapping with key...

    Learn more →
  • Courses
    Squeeze Course
    Squeeze Course
    19 Modules

    Scan, backtest, and trade the TTM Squeeze setup with precision.

    Unlock Course →
    Earnings Course
    Earnings Course
    3 Modules

    Master earnings plays with free indicators and proven strategies for ThinkOrSwim.

    Unlock Course →
    V-Shaped Reversals
    V-Shaped Reversals
    7 Modules

    Identify and trade powerful V-shaped reversal patterns with confidence and precision.

    Unlock Course →
    Fibonacci Trading
    Fibonacci Trading
    4 Modules

    Learn to trade Fibonacci retracements and extensions in ThinkOrSwim effectively.

    Unlock Course →
  • Products
    Futures Volatility Box Premium
    Futures Volatility Box

    Volatility models for 10 major futures markets, including micros & SPX.

    Explore Futures VB →
    Stock Volatility Box Premium
    Stock Volatility Box

    Dynamic support & resistance for 595+ stocks/ETFs, with a live scanner.

    Explore Stock VB →
    Opening Range Breakouts Premium
    Opening Range Breakouts

    Powerful live scanner & backtester for ORB strategies on 595+ stocks.

    Explore ORB Setups →
My Account
All Backtesters
Beginner-Friendly 36 mins

Moving Average Pullback Backtester

Test whether moving average pullbacks are effective, and if so, which moving average is best for your favorite markets.

Download Backtester
How to install in ThinkOrSwim →
Table of Contents
  • S&P 500 – Which Moving Average Pullback is Best?
  • Switch Statement – thinkScript Example

In this thinkScript tutorial, we’ll build a POWERFUL Moving Average Pullback Backtester for ThinkOrSwim, in less than 35 minutes.

Moving Average Pullback - TOS Indicators

 

We’ll design this backtester to help us answer the following questions:

1. Does buying / selling pullbacks into moving averages really work?

2. If so, which moving average is most effective for a particular market?

3. And, should we wait for a confirmation, or enter blindly with a pullback?

This is a beginner-friendly tutorial, and I’ll cover the following:

  • How to Build a “Back of the Napkin” Backtester Easily
  • How to Define Clear Entry and Exit Signals
  • How to Correctly Use the AddOrder() function
  • How to Use the Switch Function to Test Different Scenarios
  • How to Backtest Small Changes in a Strategy to Find BIG Improvements in P/L

I’ll walk you through step-by-step, how you can build a similar backtester, and we’ll also review some examples towards the end of the tutorial.

Let’s get started!

S&P 500 – Which Moving Average Pullback is Best?

Let’s look at an example of using the backtester inside of the S&P 500, to find which moving average pullback leads to the greatest profits.

Here are the parameters used for this backtest (if you’d like to follow along):

  • Symbol: SPY
  • Length: 5-Years
  • Type: Longs Only
  • Target: 3 * ATR
  • Stop: 2 * ATR

Using those parameters, here is what we found, through our backtest:

S&P 500 - Best Moving Average for a Pullback

If you used an 8-period Exponential Moving Average (EMA) to trade the SPY, your P/L would have been almost $4,300 LOWER if you did not wait for a confirmation, but instead tried to BLINDLY buy a pullback!

Put a different way – you could have increased your P/L by almost 300% by simply waiting for price to confirm the pullback entry.

On the other hand, had you used a 34-period EMA, your P/L, while still less than the 8-EMA pullback, buying blindly would have been a better idea than waiting for a confirmation.

We also find, that as we increase the length of our moving average, we also decrease the need to wait for a confirmation, and can instead take slightly more aggressive entries.

That’s what backtesting is all about. You can use it to find optimal settings for your trading strategy, and discover insights using concrete data that were hidden in plain sight.

There are other, similar examples towards the end of the tutorial, which you may find fascinating to review as well (I know I do!).

You can also take this one step further, and use our Moving Average Crossover Backtester (also free), to find early indications of a new trend forming.

 

Switch Statement – thinkScript Example

The switch statement is a simple, yet robust way to define one variable in multiple different ways, depending on each “scenario” in your trading strategy.

The best way to learn and use switch statements is through trial and error, and practice writing the actual code (the syntax is odd, and takes a bit of ‘warming up’ to get used to it).

 

Example #1: Change the Entry Moving Average Based on User Selection

We’d like for the user to be able to select which moving average they’d like to use, for the pullback entry. This same “text-only” value needs to be connected with the actual moving averages inside of the code, that hold numerical values.

Here’s how we can define our input statement, to let the user select from a variety of limited choices:

input entryMA = {default EMA8, EMA21, EMA34, SMA50, SMA200};

With just that code, the user sees a drop-down menu, when they double-click the strategy:

Moving Average Pullback Backtester Choices

The next part is defining what those different switch conditions actually change, within the code. That’s where using switch and case statements becomes useful.

Here is how we can connect the input variable to the selected moving average, within the code:

def EMA8 = ExpAverage(close, 8);
def EMA21 = ExpAverage(close, 21);
def EMA34 = ExpAverage(close, 34);
def SMA50 = SimpleMovingAvg(close, 50);
def SMA200 = SimpleMovingAvg(close, 200);

def entryPullbackMA;
switch (entryMA){
case EMA8:
    entryPullbackMA = EMA8;
case EMA21:
    entryPullbackMA = EMA21;
case EMA34:
    entryPullbackMA = EMA34;
case SMA50:
    entryPullbackMA = SMA50;
case SMA200:
    entryPullbackMA = SMA200;
}

As you should notice, each different user selection that we added in the input variable needs to be defined as a separate ‘case’, which contains a final value for the entryPullbackMA variable.

 

Example #2: Change the Entry Signal and Entry Price Based on User Selection

The user can select between one of two different moving average pullback strategies:

  1. Option #1: Enter blindly, using only the pullback as our entry signal, without waiting for price action to confirm the move. This means that the backtester would be entering any time price touches the selected moving average, as long as the overall 5 moving averages are stacked, in the direction of the trend.
  2. Option #2: Wait for price action to confirm the pullback using a simple reversal candlestick pattern, and enter when we have a close above the previous bar’s high (for long entries), or below the previous bar’s low (for short entries).

Here is how we define that, within the code, using switch and case statements:

def bullEntrySignal;
def bullEntryPrice;
def bearEntrySignal;
def bearEntryPrice;

switch(entryType){
case pullbackOnly:
    bullEntrySignal = bullishStackedMAs and low <= entryPullbackMA; bullEntryPrice = entryPullbackMA; bearEntrySignal = bearishStackedMAs and high >= entryPullbackMA;
    bearEntryPrice = entryPullbackMA;
case Confirmation:
    bullEntrySignal = bullishStackedMAs and Lowest(low,2) <= entryPullbackMA and close > high[1]; 
    bullEntryPrice = close;
    bearEntrySignal = bearishStackedMAs and Highest(high,2) >= entryPullbackMA and close < low[1]; 
    bearEntryPrice = close;
}

The bullish entrySignal variable changes, depending on if the user wants the backtester to enter blindly (Option 1), or wait for a confirmation of price action (Option2 ).

Here is a link to the ThinkOrSwim documentation, which details switch and case statements a bit more.

If you’d like to practice, you can try defining other entry and exit strategies, that all center around using moving averages and finding pullback trades (example list from Investopedia).

Featured Tools:
Stock Volatility Box

Stock Volatility Box

Spot reversal zones across 600 stocks & ETFs.

  • Hourly & daily models
  • Powerful Live Scanner
  • Built for day traders
Futures Volatility Box

Futures Volatility Box

Pinpoint reversal zones in 10 major futures markets.

  • 5 models (incl. Scalper)
  • ThinkOrSwim & TradingView
  • SPX traders
ORB Setups

ORB Setups

Find the best Opening Range Breakout setups.

  • Powerful real-time scanner
  • Instant backtests
  • 2+ years data

Get Free Access

Create a free account for downloads and new tutorial alerts.

Create Free Account

More Tutorials Like This

SPY Meltdown Backtester

SPY Meltdown Backtester

Beginner-Friendly • 8 mins
Opening Range Breakout

Opening Range Breakout

Intermediate • 36 minutes
Santa Claus Rally Backtester

Santa Claus Rally Backtester

Beginner • 14 minutes

Ready to Trade With an Edge?

Join 40,000+ traders using institutional-grade tools for ThinkOrSwim.

Get the Bundle
TOS Indicators

Premium thinkorswim indicators, scans, and trading tools to help you trade smarter.

ThinkOrSwim Tools

  • Indicators
  • Scans
  • Backtesters
  • Dashboards
  • thinkScript
  • Browse All

Courses

  • Squeeze Course
  • Earnings Course
  • V-Shaped Reversals
  • Fibonacci Trading

Products

  • Futures Volatility Box
  • Stock Volatility Box
  • ORB Setups
  • Shop All

Guides

  • TTM Squeeze
  • Automated Trading
  • Volatility Trading
  • Opening Range Breakouts
  • Trade Reports
  • Contact Us

© 2026 TOS Indicators. All rights reserved.

Privacy Policy Terms of Service Disclaimer

The information contained on this website is solely for educational purposes, and does not constitute investment advice. The risk of trading in securities markets can be substantial. You must review and agree to our Terms of Service prior to using this site.

U.S. Government Required Disclaimer - Commodity Futures Trading Commission. Futures and options trading has large potential rewards, but also large potential risk. You must be aware of the risks and be willing to accept them in order to invest in the futures and options markets. Don't trade with money you can't afford to lose. This website is neither a solicitation nor an offer to Buy/Sell futures or options. No representation is being made that any account will or is likely to achieve profits or losses similar to those discussed on this website. The past performance of any trading system or methodology is not necessarily indicative of future results.

Individual results may vary, and testimonials are not claimed to represent typical results. All testimonials are by real people, and may not reflect the typical purchaser's experience, and are not intended to represent or guarantee that anyone will achieve the same or similar results.

TOS Indicator's Traders and employees will NEVER manage or offer to manage a customer or individual's options, stocks, currencies, futures, or any financial markets or securities account. If someone claiming to represent or be associated with TOS Indicator solicits you for money or offers to manage your trading account, do not provide any personal information and contact us immediately.

CFTC RULE 4.41 - HYPOTHETICAL OR SIMULATED PERFORMANCE RESULTS HAVE CERTAIN LIMITATIONS. UNLIKE AN ACTUAL PERFORMANCE RECORD, SIMULATED RESULTS DO NOT REPRESENT ACTUAL TRADING. ALSO, SINCE THE TRADES HAVE NOT BEEN EXECUTED, THE RESULTS MAY HAVE UNDER-OR-OVER COMPENSATED FOR THE IMPACT, IF ANY, OF CERTAIN MARKET FACTORS, SUCH AS LACK OF LIQUIDITY, SIMULATED TRADING PROGRAMS IN GENERAL ARE ALSO SUBJECT TO THE FACT THAT THEY ARE DESIGNED WITH THE BENEFIT OF HINDSIGHT. NO REPRESENTATION IS BEING MADE THAT ANY ACCOUNT WILL OR IS LIKELY TO ACHIEVE PROFIT OR LOSSES SIMILAR TO THOSE SHOWN.