iSAR in Pine Script: ta.sar(step, step, maximum)

Short answer

Use ta.sar(step, step, maximum): MetaTrader always starts the acceleration at step, while Pine lets the start differ from the increment. The first trend can differ until the first reversals.

iSAR returns a handle to MetaTrader's Parabolic SAR. It takes two parameters, step and maximum; Pine Script's ta.sar(start, inc, max) takes three, because it lets the starting acceleration differ from the increment. MetaTrader always starts the acceleration factor at step, so the port is ta.sar(step, step, maximum).

What iSAR computes

The signature is iSAR(symbol, timeframe, step, maximum), with the usual defaults 0.02 and 0.2, and one buffer. Wilder's Parabolic SAR trails price in a trend: on each bar the next SAR is SAR + AF · (EP − SAR), where EP is the extreme point of the current trend (highest high in an uptrend, lowest low in a downtrend) and AF is the acceleration factor. AF starts at step, grows by step each time a new extreme is made, and is capped at maximum. In an uptrend the SAR may not rise above the lows of the previous two bars (above the highs in a downtrend). When price crosses the SAR, the trend reverses: the new SAR is the extreme of the trend that just ended and AF resets to step. The value for a bar is decided from earlier bars, so the dot on the forming bar is known at its open; only the reversal is decided by the bar's own range.

The part that is not standardised is the start. The bundled example source (ParabolicSAR.mq5) simply assumes a downtrend on the first bar; Stratlate's calibration against the built-in indicator behind iSAR found that it waits for a bar that makes both a higher high and a higher low (or both lower) before choosing a direction.

The Pine Script equivalent

ta.sar(start, inc, max) applies the same recursion, the same two-bar clamp and the same reset rule. Pass MetaTrader's step as both start and inc. Plot it with plot.style_circles to get MetaTrader's dots.

//@version=6
indicator("iSAR port", overlay = true)
step  = input.float(0.02, "Step", step = 0.01)      // iSAR step
maxAf = input.float(0.2, "Maximum", step = 0.01)    // iSAR maximum

// MetaTrader has no separate start value: the acceleration starts at `step`.
sar = ta.sar(step, step, maxAf)

plot(sar, "SAR", color.rgb(30, 144, 255), style = plot.style_circles, linewidth = 2)

The MQL5 indicator this replaces. It copies the whole series on every call, because a SAR value can only be read correctly after the handle has processed the bar.

#property indicator_chart_window
#property indicator_buffers 1
#property indicator_plots   1
#property indicator_type1   DRAW_ARROW
#property indicator_color1  clrDodgerBlue

input double InpStep    = 0.02; // step
input double InpMaximum = 0.2;  // maximum

double SarBuffer[];
int    sarHandle;

int OnInit()
  {
   SetIndexBuffer(0, SarBuffer, INDICATOR_DATA);
   PlotIndexSetInteger(0, PLOT_ARROW, 159);           // dot
   sarHandle = iSAR(_Symbol, _Period, InpStep, InpMaximum);
   if(sarHandle == INVALID_HANDLE)
      return(INIT_FAILED);
   return(INIT_SUCCEEDED);
  }

int OnCalculate(const int rates_total, const int prev_calculated, const datetime &time[],
                const double &open[], const double &high[], const double &low[], const double &close[],
                const long &tick_volume[], const long &volume[], const int &spread[])
  {
   if(BarsCalculated(sarHandle) < rates_total)
      return(0);
   // SAR values of older bars can change after a reversal, so copy the whole series
   if(CopyBuffer(sarHandle, 0, 0, rates_total, SarBuffer) <= 0)
      return(0);
   return(rates_total);
  }

Where the two differ

TopicMQL5 iSARPine ta.sar
Parametersstep, maximumstart, inc, max; use start = inc = step
First trendChosen when a bar breaks out both ways in one directionTradingView's own initial direction rule
After the startSame recursion; once both platforms have reversed on the same bars, the dots coincide
History startMatters: SAR is path-dependent, so a chart that starts on a different bar can be in a different trend for a while
DrawingDRAW_ARROW with arrow code 159plot.style_circles or plot.style_cross
Parameter checksThe example source replaces negative values with 0.02 / 0.2 and logs itValues are used as given

What the Stratlate converter emits

For the MQL5 four-argument handle form the MQL5 → Pine engine does not use ta.sar: it emits a prelude helper f_sar_mt5(step, maximum), a hand-written SAR whose source comment says it was calibrated against the built-in MT5 indicator (not the bundled example and not ta.sar) on three parameter pairs over 600 bars, and which stops with a runtime error unless 0 < step ≤ maximum. It does this only when the handle's values are copied in a form it can model: CopyBuffer(handle, 0, 0, rates_total, buffer), as in the example above, converted with no SAR warning. The common incremental pattern (rates_total − prev_calculated + 1 bars) is reported as unsupported, MQLW0500 "partial CopyBuffer windows require destination-state lowering", and the buffer is not reliably filled. The MQL4 five-argument iSAR maps to ta.sar(step, step, maximum). Compile the result and compare reversals on the MT5 chart.

Pitfalls

  • Porting as ta.sar(0.02, 0.02, 0.2) but with MetaTrader's maximum passed as inc. Argument two in Pine is the increment, not the cap; the dots accelerate ten times too fast.
  • Judging the port on the first bars of the chart. The initial direction rule differs, so the first trend can be opposite until both platforms reverse on the same bars.
  • Using the SAR value of the forming bar for a reversal signal. The dot does not move during the bar, but the reversal is decided by the bar's high or low, which can change until the close; check reversals on closed bars.
  • Reading only the latest values with a partial CopyBuffer when porting with the converter: that pattern is reported unsupported; copy rates_total values or port the SAR by hand.
  • Plotting with a line style. SAR jumps across price at each reversal, so a connected line draws vertical spikes through the candles.

FAQ

Why does ta.sar have three parameters and iSAR two?

Pine separates the starting acceleration from the increment. MetaTrader uses one value for both. Setting start and inc to the same number gives MetaTrader's behaviour.

Will the dots match MetaTrader on every bar?

After the start, usually yes: the recursion is the same. The first trend after the beginning of the loaded history can differ because the two platforms pick the initial direction differently, and the different start bars of each platform's history can do the same.

How do I detect a reversal in Pine?

Compare the SAR with price: sar < close and sar[1] > close[1] is a switch to an uptrend. That is the same test an MQL5 program writes with two copied SAR values and two closes.

Convert the whole program

Paste an MQL4 or MQL5 indicator or Expert Advisor and get Pine Script v6 with this and every other call mapped, checked against the original on the same bars, and every construct that could not be carried over reported.

Open the converter

Related