Parabolic SAR

Build a smarter Parabolic SAR indicator that predicts when the PSAR dots are likely to reverse.

youtube-video-thumbnail
Table of Contents
    Add a header to begin generating the table of contents
    Table of Contents
      Add a header to begin generating the table of contents

      Introduction

      The Parabolic SAR (Stop And Reverse) indicator is a popular tool, useful for identifying potential reversals in the market.

      However, it’s only useful when used correctly.

      Despite its widespread use, I’ve found most traders don’t have a good grasp on how the Parabolic SAR indicator works, or what’s going on under the hood. We’re going to fix that in this video series.

      In this guide, I’ll show you how to build a better, smarter version of the Parabolic SAR indicator. We’ll start with the basics, building a good foundation of the indicator and formulas, before moving on to more advanced concepts.

      Once we have a good foundation, we’ll use that to build a better Parabolic SAR indicator, with built-in bullish and bearish predictive signals. These signals will help you with early entries, before reversals take place.

      After building the indicator, we’ll turn that into two ThinkOrSwim scans. One scan will be dedicated to finding all of the bullish setups triggering, on any time frame. The other scan will be for all of the bearish setups.

      Finally, in Part 4, we are going to use all of this knowledge to build a robust backtester that allows us to test how effective this Parabolic SAR strategy really is. For Volatility Box members, I have a special “Pro” version of the backtester, in which we’ll add in stat labels to let ThinkOrSwim do most of the heavy lifting for us.

      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!

      Learn More About the Stock Volatility Box

      Trade stocks and options with a consistent volatility edge

      How to Read the Parabolic SAR Dots

      The Parabolic SAR (Stop and Reverse) is a technical indicator used to identify potential reversals in an asset’s price trend. While the visual dots plotted by the indicator are easy to interpret, understanding the underlying calculations is key to using it effectively. In this post, we’ll dive deep into the Parabolic SAR code to truly grasp how it operates.

      If you haven’t already, I would recommend following along with our video tutorial for Part 1 of our Parabolic SAR video series, which is a good resource alongside this post:

       

      The Parabolic SAR plots dots above or below the price action, indicating the potential trend direction.

      • Dots below price action represent a bullish bias (cyan dots in our version)
      • Dots above price action represent a bearish bias (pink dots in our version)

      The primary purpose of the Parabolic SAR is to identify trend reversals.

      When the dots switch positions relative to the price, it’s a signal that the trend may be reversing. However, the indicator can also be used for trend continuation, as the dots continuing to plot in the same direction suggest that the existing trend is still healthy.

       

      Code Walkthrough

      To truly understand the Parabolic SAR, it’s essential to examine the code that powers the indicator. Let’s walk through the code step by step, to take a look under the hood!

      Input Variables

      The Acceleration Factor (AF) and Acceleration Limit (AL) are the two input variables that users can adjust from the study settings menu.

      Think of the Acceleration Factor as the gas pedal, controlling the speed at which the indicator responds to price movements. The Acceleration Limit acts as the maximum speed, ensuring that the indicator’s responsiveness doesn’t exceed a certain threshold.

      input accelerationFactor = 0.02;
      input accelerationLimit = 0.2;

      The code starts by defining two user input variables:

      • accelerationFactor: This controls the initial acceleration or sensitivity of the indicator to price changes. The default value is 0.02. It acts as our “gas pedal” to control our car’s speed.
      • accelerationLimit: This sets the maximum acceleration allowed for the indicator, preventing over-sensitivity. The default value is 0.2. This is the max speed limit of our car.

       

      Variable Initialization

      def state = {default init, long, short};
      def extreme;
      def SAR; 
      def acc;

      The code then initializes four key variables:

      1. state: A def (short for define) variable that can hold one of three values: “init”, “long”, or “short”. This tracks the current indicator state.
      2. extreme: A def variable that will store the highest or lowest price since the last state change.
      3. SAR: A def variable that will hold the calculated SAR value to be plotted.
      4. acc: A def variable that will track the current acceleration value.

       

      Switch Function – Initialization State

      The switch function is where the magic happens.

      The core logic of the Parabolic SAR indicator is implemented in a switch function that updates the state and variables based on the price action.

      case init:
      state = state.long;
      acc = accelerationFactor;
      extreme = high;
      SAR = low;

      In the initialization case…

      • The state is set to “long”
      • acc is set to the user input accelerationFactor variable
      • extreme is set to the current high price
      • SAR is set to the current low price

      This assumes the start of a potential uptrend.

       

      Switch Function – Short State

      In the short state, the code checks if the SAR value crosses below the current high price, indicating a potential trend reversal. If so, it switches to the long state and updates the relevant variables.

      case short:
      if (SAR[1] < high)
      then {
      state = state.long;
      acc = accelerationFactor;
      extreme = high;
      SAR = extreme[1];
      } else {
      state = state.short;
      if (low < extreme[1])
      then {
      acc = min(acc[1] + accelerationFactor, accelerationLimit);
      extreme = low;
      } else {
      acc = acc[1];
      extreme = extreme[1];
      }
      SAR = max(max(high, high[1]), SAR[1] + acc * (extreme - SAR[1]));
      }

      In the short case:

      1. If the previous SAR value crosses above the current high price, it anticipates a trend reversal to long. The state is flipped, acc/extreme/SAR are reset.
      2. Else, it means the short trend is continuing:
        • If the current low is lower than the previous extreme low, it increases acc (acceleration) up to the accelerationLimit as the downtrend is strengthening.
        • extreme is also updated to the new low.
        • If the current low is not lower than the previous extreme, acc and extreme are unchanged.
      3. The new SAR value is calculated as the maximum of:
        • The current high price
        • The previous high price
        • The previous SAR plus the current acceleration multiplied by the difference between extreme and previous SAR

       

      Switch Function – Long State

      In the long state, the code checks if the SAR value crosses above the current low price. If it does, it anticipates a potential trend reversal and switches to the short state, resetting the acceleration and updating the extreme and SAR values accordingly.

      case long:
      if (SAR[1] > low)
      then {
      state = state.short;
      acc = accelerationFactor;
      extreme = low;
      SAR = extreme[1];
      } else {
      state = state.long;
      if (high > extreme[1])
      then {
      acc = min(acc[1] + accelerationFactor, accelerationLimit);
      extreme = high;
      } else {
      acc = acc[1];
      extreme = extreme[1];
      }
      SAR = min(min(low, low[1]), SAR[1] + acc * (extreme - SAR[1]));
      }

      The long case is essentially the inverse of the short case:

      1. If the previous SAR value crosses below the current low price, it anticipates a trend reversal to short. The state is flipped, acc/extreme/SAR are reset.
      2. Else, it means the long trend is continuing:
        • If the current high exceeds the previous extreme high, it increases acc (acceleration) up to the accelerationLimit as the uptrend is strengthening.
        • extreme is also updated to the new high.
        • If the current high does not exceed the previous extreme, acc and extreme are unchanged.
      3. The new SAR value is calculated as the minimum of:
        • The current low price
        • The previous low price
        • The previous SAR plus the current acceleration multiplied by the difference between extreme and previous SAR

      Plotting the PSAR Dots

      Finally, the code plots the calculated SAR value on the chart using the plot function:

      plot parSAR = SAR;
      parSAR.SetPaintingStrategy(PaintingStrategy.POINTS);
      parSAR.SetDefaultColor(GetColor(5));

      The code plots the dots as points, and sets the default color, which we can use as a starting point for our indicator customization.

      By this point, you should have a good understanding of how the Parabolic SAR indicator works behind the scenes, and all of the calculations that are taking place.

      In the next section, we’ll start by customizing the indicator, and make a BETTER version of the Parabolic SAR indicator.

       

      Parabolic SAR Colored Dots

      With a solid understanding of the code, we can now customize the Parabolic SAR to make it more user-friendly and effective.

      These are the improvements that we will be building in our custom indicator:

      1. Intuitive PSAR dots, so it’s easy to visually recognize bullish vs. bearish trends
      2. Predictive PSAR reversal signals (before the dots switch colors) — you’ll see how having a good foundation of the code is VERY helpful here!
      3. Allowing the user to choose how they’d like to see the buy and sell signals

       

      Coloring the Dots

      One simple customization is to color the dots based on the indicator’s state, making it easier to distinguish between long and short signals.

      Here’s an example of how to modify the code:

      if state == "long":
      color = cyan
      elif state == "short":
      color = pink
      else:
      color = default

      By checking the state variable and assigning the appropriate color, we can visually differentiate between bullish and bearish signals.

      We can replace the following line in the plot code, with the following, and have the dots be far more visually intuitive.

      Replace this:

      parSAR.SetDefaultColor(GetColor(5));

      With this:

      parSAR.AssignValueColor(if state == state.long then color.cyan else if state == state.short then color.pink else color.current);

       

      Build a Smarter Parabolic SAR Indicator

      In the first part of this series, we dove deep into understanding the inner workings of the Parabolic SAR (Stop and Reverse) indicator.

      We explored how it identifies potential trend reversals by plotting dots above or below the price action. While useful, the standard Parabolic SAR can sometimes be late in signaling these reversals.

      In this section, we’ll make this indicator better by having it provide earlier signals for impending trend changes.

      By monitoring the acceleration factor and overbought/oversold conditions, we can anticipate reversals before the Parabolic SAR dots actually flip.

      Let’s get coding!

       

      The “Hidden” Pattern

      Our goal is to detect when the following conditions are met:

      • The acceleration factor (ACC) has hit the user-defined maximum limit.
      • Price momentum is showing signs of waning through overbought or oversold signals.

      When both conditions are true, it suggests the current trend is exhausting and a reversal may be imminent, even before the Parabolic SAR dots change positions.

      Coding the Pattern

      Let’s start by adding some new user inputs to control how the signals will be visualized:

      input plotMethod = {default "Arrows", "Chart Bubbles"};
      input arrowThickness = {default "1", "2", "3", "4", "5"};

      Here, we allow the user to choose between displaying the signals as arrows or chart bubbles. If arrows are selected, the user can also set the thickness.

      Next, we’ll create switch statements to convert these inputs into numeric values our code can use:

      def plotChoice;
      switch(plotMethod){
      case "Arrows": plotChoice = 1;
      case "Chart Bubbles": plotChoice = 2;
      }
      
      def arrowWeight; 
      switch(arrowThickness){
      case "1": arrowWeight = 1;
      ...
      case "5": arrowWeight = 5;
      }
      

      Now we can check if maxSpeedReached by comparing acc to accelerationLimit:

      def maxSpeedReached = acc == accelerationLimit;
      

      For overbought/oversold detection, we’ll use the built-in RSI indicator’s up/down signals:

      def upSignal = RSI().upSignal;
      def downSignal = RSI().downSignal;
      

      Putting it all together, we can define conditions for an exhausting uptrend and downtrend:

      def upTrendExhausting = maxSpeedReached and downSignal;
      def downTrendExhausting = maxSpeedReached and upSignal;
      

      To visualize the signals, we’ll use a combination of AddChartBubble and plot:

      AddChartBubble(plotChoice == 2 and upTrendExhausting, close, "Likely Downtrend \nPSAR Reversal", color.light_red);
      
      plot sellSignal = plotChoice == 1 and upTrendExhausting;
      sellSignal.setPaintingStrategy(PaintingStrategy.Boolean_Arrow_Down);
      sellSignal.setLineWeight(arrowWeight);
      sellSignal.SetDefaultColor(Color.Light_Red);
      

      The code for the uptrend (buy) signals is essentially the same, just with reversed conditions and colors.

      And there you have it!

      We’ve coded a new pattern that can anticipate potential Parabolic SAR reversals ahead of time.

       

      Final Demo – Smarter Parabolic SAR Indicator 

      The light red arrows and bubbles mark potential sell signals, while the light green ones highlight potential buy signals. As you can see, these signals often precede the actual Parabolic SAR reversal dots by one or more bars.

      Of course, not all signals will be perfect. There are some false breakouts and weak signals mixed in. In an upcoming pro version for Volatility Box members, we’ll add additional filters to improve accuracy.

      You can also experiment with different timeframes. Lower timeframes like 1-minute may have too few signals, while higher timeframes like 30-minutes could suit swing traders better.

       

      Parabolic SAR Scans for ThinkOrSwim (Bull and Bear)

      In the third part of our Parabolic SAR video series, we’ll learn how to turn the Parabolic SAR indicator code from Part 2 into a powerful ThinkOrSwim scan.

      This allows us to scan for buy and sell signals across a broad range of stocks and markets.

      The process is quite simple. We start by copying the indicator code into the ThinkOrSwim scan editor (available in the live money version). A key step is modifying the code to have only a single plot variable – either the buy signal or sell signal condition we want to scan for.

      For the buy scan, we keep just the buySignal plot line:

      plot buySignal = plotChoice == 1 and downTrendExhausting;

      This will scan for cases where our Parabolic SAR algorithm detects a potential uptrend reversal.

      Running this scan picked up symbols like Canopy Growth (CGC) and Paramount Global where we see a green arrow plotted anticipating the SAR dots switching from a downtrend to an uptrend.

      For the sell scan, we instead use the sellSignal plot:

      plot sellSignal = plotChoice == 1 and upTrendExhausting;

      This identified stocks like Medical Properties Trust, C4 Therapeutics, and Coupang – all showing a red sell arrow where the algorithm expects an uptrend to reverse lower.

      By morphing our indicator code into a scan, we’ve harnessed ThinkOrSwim’s processing power to quickly find potential buy and sell opportunities across a wide range of stocks and markets.

      In Part 4, we’ll take this a step further by converting these signals into a backtester to evaluate their effectiveness.

      The key takeaway is that with some simple code modifications, you can turn almost any ThinkOrSwim indicator into a powerful scan tailored to your trading strategy.

      Give it a try with your own indicators and strategies!

       

      Parabolic SAR Backtester for ThinkOrSwim

      In the fourth section of our Parabolic SAR video series, we’ll learn how to take the Parabolic SAR indicator code from Part 2 and transform it into a POWERFUL backtesting tool within ThinkOrSwim.

      Backtesting allows us to see actual performance metrics and evaluate whether a trading strategy is viable before risking capital in live markets.

      We’ll start by looking at a demo of the completed Parabolic SAR backtester tool. Within ThinkOrSwim, I have the Parabolic SAR indicator loaded on a chart, along with the custom backtester we’ll be building.

      The backtester provides a floating profit and loss (P&L) chart at the bottom displaying the equity curve over time if we had traded these signals live.

      For the free version, we can right-click and select “Show Report” to see details like the total net profit, number of winners versus losers, and more.

      However, for Volatility Box members, I’ve created a “pro” version that saves time by automatically displaying key metrics like average winner, average loser, and win rate percentage via labels overlaid on the chart itself.

      With that sneak preview, let’s dive into actually coding this powerful backtesting tool step-by-step.

       

      Converting Indicator to Backtester Code

      We begin in ThinkOrSwim by navigating to the Strategies tab and creating a new strategy.

      I’ll paste in the full Parabolic SAR indicator code we built previously. This provides the trading signals we want to backtest, but some additional code is needed to run it as a proper backtest within ThinkOrSwim’s Strategy engine.

      The key functions we need to add are the AddOrder() conditions specifying:

      1. The entry signal for new long positions (buySignal)
      2. The exit signal to close those long positions
      3. The entry signal for new short positions (sellSignal)
      4. The exit signal to close those short positions

      For the long entries, the code looks like this:

      AddOrder(OrderType.BUY_TO_OPEN, longEntries and buySignal, close, quantity);
      AddOrder(OrderType.SELL_TO_CLOSE, state == state.short and state[1] != state.short, close, quantity);

      The first line specifies we want to open a new long position (BUY_TO_OPEN) when both the longEntries input is true AND the buySignal condition is true.

      It uses the closing price for the entry, and the user-specified quantity.

      The second line then exits (SELL_TO_CLOSE) that long position when two criteria are met:

      1. The current state is short, and
      2. The previous state was not short (meaning it just switched from long to short)

      We add similar logic for the short entries:

      AddOrder(OrderType.SELL_TO_OPEN, shortEntries and sellSignal, close, quantity);
      AddOrder(OrderType.BUY_TO_CLOSE, state == state.long and state[1] != state.long, close, quantity);

      With those key pieces of code, we now have a working backtest of the Parabolic SAR strategy!

      Once I click “Apply” and look at my charts, I can now see buy/sell entries plotted along with the floating P&L pane tracking hypothetical profits.

      To avoid tracking conflicts, I’ve added input settings to disable one side and only track either long entries OR short entries for a given backtest run.

       

      Evaluating Backtest Results Over Different Markets

      With the coding work done, we can now begin rigorously testing the Parabolic SAR strategy across various markets and timeframes to evaluate its performance.

      Let’s start with the S&P 500 index (SPY) on the daily chart over a 30-day period.

      Right-clicking and selecting “Show Report” reveals the backtest generated 2 winning trades and 1 losing trade, with an overall positive P&L.

      Switching over to NVDA on a 5-minute intraday chart for the past 30 days shows 10 total trades, but this time with an overall negative P&L according to the report.

      The reports display all the key metrics like trade entries/exits, profit/loss, and more.

      However, having to right-click and pull up the report every time is a bit cumbersome for rapidly analyzing results.

      For Volatility Box members, the “pro” version saves time by automatically displaying performance metrics via labels overlaid on the chart itself.

      With a single glance, we instantly know the win rate, average winner, average loser, and more, updating in real-time as different markets/timeframes are analyzed. This version provides a huge productivity boost when rigorously backtesting a strategy across a basket of symbols.

      Either way, the key point is we can now put the Parabolic SAR strategy under a comprehensive performance microscope.

      Does it have an acceptable win rate? Are profits reasonably higher than losses?

      What does the equity curve look like – is there a severe drawdown period that makes the overall risk/reward unacceptable?

      These are the types of critical questions that can be answered through backtesting before ever risking a dollar of real capital.

       

      Parabolic SAR Backtester Stat Labels

      The Pro version of the Parabolic SAR Backtester (with the Stat labels) are included for free with a Volatility Box membership. Join the Volatility Box here and take advantage of our limited-time bundle discount!

       

      Series Recap

      This four-part video series has provided a comprehensive foundation for understanding, coding, scanning, and backtesting the Parabolic SAR trading indicator within ThinkOrSwim:

      • Part 1: Understood the underlying Parabolic SAR calculation methodology
      • Part 2: Coded an “enhanced” Parabolic SAR indicator to plot buy/sell signals
      • Part 3: Converted indicator into a scan to find those buy/sell signals across markets
      • Part 4: Created a backtester to analyze the performance of the Parabolic SAR strategy

      With the power to backtest literally any trading strategy at their fingertips, traders now have the tools to validate new trading ideas with an empirical performance track record before risking real capital.

      Parabolic SAR for ThinkOrSwim - Free Video Series

      Through this robust process, strategies can be objectively accepted or rejected, settings refined, and the risk of any deployment minimized through comprehensive historical simulation.

      downloads

      Download the Parabolic SAR Indicator, Backtester, and Scans for ThinkorSwim.

      The download contains STUDY.ts and STRATEGY.ts files, which you can directly import into your ThinkOrSwim platform.

      Download Tools

      Download the Parabolic SAR Indicator, Backtester, and Scans for ThinkorSwim.

      The download contains STUDY.ts and STRATEGY.ts files, which you can directly import into your ThinkOrSwim platform.

      Have your own idea?

      Let us help you turn your trading strategy into a powerful indicator, scan and backtester.