Indicator TutorialPine Script v5

How to Build Parabolic SAR (PSAR) in Pine Script

Acceleration steps, extreme points, and practical trailing-stop usage

Parabolic SAR (Stop and Reverse) is a trend-following overlay that prints dots above or below price to suggest potential stop levels and flip points. Wilder’s method increases sensitivity as a trend extends via an acceleration factor capped by a maximum. This tutorial explains the intuition, parameters, and a full Pine Script v5 implementation using ta.sar() with optional entry markers.

What Is Parabolic SAR?

Parabolic SAR places a series of dots relative to price. In an uptrend, dots sit below price; in a downtrend, above. When price crosses the SAR dot, the system “stops and reverses,” flipping bias.

The algorithm tracks an extreme point (EP) and raises the SAR toward price using an acceleration factor (AF) that increases each time a new extreme prints, up to an AF maximum.

Why it matters

SAR shines as a trailing stop discipline tool. It is less reliable in choppy ranges where whipsaws cluster.

Why Traders Use This Indicator

  • Trail stops mechanically in trending markets without manual line dragging.
  • Visualize potential reversal flips when dots switch sides.
  • Combine SAR direction with momentum oscillators to filter chop.
  • Use as a building block in systematic breakout and trend strategies.
ParameterDefaultDescription
Start (initial AF)0.02Initial acceleration factor. Higher starts tighten the SAR faster from the first bar of a move.
Increment0.02Amount AF increases when a new extreme forms within the current trend leg.
Maximum AF0.2Caps how aggressive tightening can become; prevents SAR from hugging noise indefinitely.
Price sourceHigh / LowSAR uses bar extremes for flip tests; ta.sar() encapsulates the classic rules for you.

How Parabolic SAR Is Calculated

For each bar, SAR updates using the prior SAR, the extreme point, and the current AF. On trend initiation after a flip, SAR resets according to Wilder’s rules and AF returns to the start value.

Long leg: SAR cannot exceed the prior two lows; short leg: SAR cannot dip below the prior two highs—classic constraints that reduce invalid levels.

On each new high (in an uptrend), EP updates and AF increases by the increment until it hits the maximum.

In Pine Script v5, ta.sar(start, increment, maximum) returns the SAR series aligned with platform standards.

Signal Interpretation

Dots below price: Often interpreted as bullish bias; many traders treat the dot as a trailing stop for longs.

Dots above price: Bearish bias; potential stop for shorts or cue to cover.

Flip: When price crosses SAR, the next dot jumps to the opposite side, marking a potential stop-and-reverse event—confirm with structure or volume before automating entries.

Chop warning: Frequent flips in sideways markets signal SAR is misaligned with regime—stand down or add filters.

Combining with Other Indicators

Pair Parabolic SAR with ADX or a long moving average to ensure you only trail in trending conditions.

ATR-based position sizing complements SAR exits by scaling risk when volatility expands.

MACD or RSI can confirm momentum persistence so SAR flips are not faded blindly in strong impulses.

The Hard Way: Writing Pine Script Manually

Challenges of Manual Coding

Implement SAR from scratch and diff against ta.sar() on 5,000 bars.

Add a chop filter: ignore SAR flips when ADX is below 20.

Plot AF value as a background series for debugging (derive from your manual code).

Create alternate SAR styles: circles vs crosses, with user-selectable sizes.

Backtest a stop-and-reverse strategy with realistic slippage and compare to SAR-as-stop-only.

Pine Script v5
//@version=5
indicator("Parabolic SAR Tutorial (ta.sar)", shorttitle="PSAR", overlay=true)

// -----------------------------------------------------------------------------
// Inputs
// -----------------------------------------------------------------------------
start = input.float(0.02, "Start AF", minval=0.001, step=0.01, tooltip="Initial acceleration factor")
increment = input.float(0.02, "AF increment", minval=0.001, step=0.01)
maximum = input.float(0.2, "AF maximum", minval=0.01, step=0.01)
showFlipMarkers = input.bool(true, "Mark SAR flips")
showTrailLine = input.bool(true, "Connect SAR dots (line)")

// -----------------------------------------------------------------------------
// Core calculation
// -----------------------------------------------------------------------------
sar = ta.sar(start, increment, maximum)
isUp = sar < close
sarColor = isUp ? color.green : color.red

// -----------------------------------------------------------------------------
// Flip detection (direction change of SAR relative to close)
// -----------------------------------------------------------------------------
wasUp = sar[1] < close[1]
flipUp = not wasUp and isUp
flipDn = wasUp and not isUp

// -----------------------------------------------------------------------------
// Plots
// -----------------------------------------------------------------------------
plot(showTrailLine ? sar : na, "SAR line", color=color.new(sarColor, 30), linewidth=1, style=plot.style_linebr)
plot(sar, "PSAR", style=plot.style_cross, linewidth=2, color=sarColor)

plotshape(showFlipMarkers and flipUp, "Bullish flip", shape.triangleup, location.belowbar, color.new(color.green, 0), size=size.small, text="SAR↑")
plotshape(showFlipMarkers and flipDn, "Bearish flip", shape.triangledown, location.abovebar, color.new(color.red, 0), size=size.small, text="SAR↓")

// Distance to SAR (risk proxy)
distPct = 100 * math.abs(close - sar) / close
plot(distPct, "Distance % (data window)", display=display.data_window)

// -----------------------------------------------------------------------------
// Alerts
// -----------------------------------------------------------------------------
alertcondition(flipUp, "SAR bullish flip", "Parabolic SAR flipped bullish (dot below price)")
alertcondition(flipDn, "SAR bearish flip", "Parabolic SAR flipped bearish (dot above price)")

// -----------------------------------------------------------------------------
// Simple regime tag for data window
// -----------------------------------------------------------------------------
regime = isUp ? "Uptrend trail" : "Downtrend trail"
var table t = table.new(position.top_right, 1, 2, frame_color=color.new(color.gray, 70), bgcolor=color.new(color.black, 75))
if barstate.islast
    table.cell(t, 0, 0, regime, text_color=color.white)
    table.cell(t, 0, 1, "Dist %: " + str.tostring(distPct, "#.##"), text_color=color.silver)

// -----------------------------------------------------------------------------
// Optional: highlight wide stop distance (volatile bars)
// -----------------------------------------------------------------------------
wideStop = distPct > input.float(3.0, "Wide stop % threshold", step=0.1)
bgcolor(wideStop ? color.new(color.orange, 92) : na)

Maintenance Note: SAR flip frequency depends heavily on start/increment/maximum. Re-tune per asset class; crypto intraday often needs different AF caps than daily FX. After Pine updates, confirm ta.sar() parity on historical charts.

The Easy Way: Build with Pineify Visual Editor

What if you could create the same indicator without writing a single line of code? Pineify is a visual editor designed for TradingView users who want professional-grade indicators through an intuitive interface.

FeatureManual Pine ScriptPineify Visual Editor
Parameter tuningTrial-and-error edits across many script versions.Structured inputs and presets speed up AF tuning workflows.
Chop handlingHard to layer regime filters without growing code size.Composable filters keep SAR logic readable.
VisualizationCustom markers and tables require repetitive boilerplate.Faster UI polish with reusable plotting patterns.
Risk overlaysCombining SAR with sizing rules clutters small scripts.Modular risk blocks scale as strategies grow.
Team reuseCopy-paste snippets diverge across contributors.Single exported source reduces drift.

Generate SAR-based indicators and strategies with less hand-written glue code.

Iterate AF presets and filters visually before exporting Pine.

Keep alerts, plots, and tables consistent across projects.

Scale to multi-condition systems without losing readability.

Step-by-Step Tutorial

1

Create an overlay indicator

SAR belongs on the main chart; set overlay=true in the builder scaffold.

2

Insert ta.sar()

Map start, increment, and maximum inputs directly to ta.sar().

3

Style plots

Choose crosses or circles, colors for bull/bear, and optional connecting line.

4

Add flip alerts

Detect direction changes with boolean logic tied to price vs SAR.

5

Layer a trend filter

Gate alerts with ADX, MA slope, or higher-timeframe alignment.

6

Export and paper trade

Validate flip frequency and stop distance on your symbols before going live.

Trading Strategies & Pro Tips

Trend trail exit

Enter on breakout confirmation; exit longs when SAR flips above price; re-enter only if structure resets.

Pro Tip: Add time-based exit if SAR never triggers in sluggish trends.

SAR + ADX gate

Take SAR flips only when ADX exceeds 25 and DI direction agrees with the new SAR side.

Hybrid stop

Use the tighter of chandelier exit and SAR to reduce giveback in parabolic moves.

Pro Tip: Document which stop wins to avoid lookahead in backtests.

Multi-timeframe SAR

Require 15m and 1h SAR alignment before accepting a flip on 5m execution charts.

Common Mistakes to Avoid

  • Running SAR without a trend filter in range-bound markets.
  • Setting AF maximum too high on noisy symbols, causing constant whipsaws.
  • Treating every flip as an automatic reverse entry without slippage modeling.
  • Ignoring that SAR ignores gap risk management on equities.
  • Mixing SAR exits with conflicting mean-reversion entries on the same timeframe.

Frequently Asked Questions

Build SAR systems faster with Pineify

  • Compose SAR exits, filters, and alerts without boilerplate.
  • Export clean Pine v5 for TradingView publishing.
  • Iterate acceleration presets with structured workflows.

Disclaimer: Trading involves significant risk. The indicators, code, and strategies provided are for educational purposes only and do not constitute financial advice. Past performance is not indicative of future results.