ta.sar in MQL5: iSAR arguments, seeding and the live bar

Short answer

iSAR(symbol, timeframe, step, maximum) matches only when start equals the increment, because it uses step for both; the usual 0.02/0.02/0.2 maps directly. With a different start, write Wilder's SAR by hand, and expect a different first trend and forming-bar handling.

ta.sar(start, inc, max) is Wilder's Parabolic SAR: a stop level that trails price and accelerates toward the extreme of the current trend, flipping sides when price crosses it. MetaTrader 5's iSAR(symbol, timeframe, step, maximum) is the same algorithm with one parameter fewer: it uses step both as the starting acceleration and as the increment. With the usual 0.02/0.02/0.2 the arguments map directly; with a start different from the increment you need your own implementation, given below. The two also start the first trend differently and treat the forming bar differently.

What ta.sar computes

The SAR moves each bar by af * (ep - sar), where ep is the extreme point of the trend (highest high in an uptrend, lowest low in a downtrend) and af is the acceleration factor. af starts at start and grows by inc each time a new extreme is made, up to max. If the new SAR crosses the current bar's range, the trend reverses: the SAR jumps to the old extreme point, the extreme point resets to the current bar, and af goes back to start. Finally the SAR is clamped so it never sits inside the previous one or two bars' range. Pine seeds on bar 1 from the first two closes: if the second close is higher the first trend is up, with the SAR at bar 0's low. Bar 0 is na. Because the reversal test uses the current bar's high and low, on the realtime bar the SAR can flip sides intrabar and flip back before the close.

The MQL5 equivalent

//@version=6
indicator("SAR ref", overlay=true)
s = ta.sar(0.02, 0.02, 0.2)
plot(s, "SAR", style=plot.style_cross)

The MQL5 indicator keeps the extreme point, acceleration and direction in calculation buffers, so recalculating the newest bar on each tick reads only the previous bar's state. The steps follow the order above: advance, test for reversal, accelerate on a new extreme, clamp.

//+------------------------------------------------------------------+
//| Parabolic SAR matching ta.sar(start, increment, maximum)          |
//+------------------------------------------------------------------+
#property indicator_chart_window
#property indicator_buffers 4
#property indicator_plots   1
#property indicator_label1  "SAR"
#property indicator_type1   DRAW_ARROW
#property indicator_color1  clrDodgerBlue

input double InpStart     = 0.02;   // Start
input double InpIncrement = 0.02;   // Increment
input double InpMaximum   = 0.2;    // Maximum

double SarBuf[], EpBuf[], AfBuf[], DirBuf[];   // extreme point, acceleration, +1 up / -1 down

int OnInit()
{
   SetIndexBuffer(0, SarBuf, INDICATOR_DATA);
   SetIndexBuffer(1, EpBuf,  INDICATOR_CALCULATIONS);
   SetIndexBuffer(2, AfBuf,  INDICATOR_CALCULATIONS);
   SetIndexBuffer(3, DirBuf, INDICATOR_CALCULATIONS);
   PlotIndexSetInteger(0, PLOT_ARROW, 159);   // a dot
   PlotIndexSetDouble(0, PLOT_EMPTY_VALUE, EMPTY_VALUE);
   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[])
{
   int start = prev_calculated > 1 ? prev_calculated - 1 : 0;
   for(int i = start; i < rates_total; i++)
   {
      if(i == 0) { SarBuf[0] = EMPTY_VALUE; EpBuf[0] = 0; AfBuf[0] = 0; DirBuf[0] = 0; continue; }
      double sar, ep, af;
      bool up, firstTrendBar = false;
      if(i == 1)   // seed from the direction of the first two closes
      {
         up  = close[1] > close[0];
         ep  = up ? high[1] : low[1];
         sar = up ? low[0]  : high[0];
         af  = InpStart;
         firstTrendBar = true;
      }
      else
      {
         sar = SarBuf[i - 1]; ep = EpBuf[i - 1]; af = AfBuf[i - 1]; up = DirBuf[i - 1] > 0;
      }
      sar += af * (ep - sar);                       // advance toward the extreme point
      if(up && sar > low[i])                        // reversal to a downtrend
      {
         firstTrendBar = true; up = false;
         sar = MathMax(high[i], ep); ep = low[i]; af = InpStart;
      }
      else if(!up && sar < high[i])                 // reversal to an uptrend
      {
         firstTrendBar = true; up = true;
         sar = MathMin(low[i], ep); ep = high[i]; af = InpStart;
      }
      if(!firstTrendBar)                            // new extreme: accelerate
      {
         if(up  && high[i] > ep) { ep = high[i]; af = MathMin(af + InpIncrement, InpMaximum); }
         if(!up && low[i]  < ep) { ep = low[i];  af = MathMin(af + InpIncrement, InpMaximum); }
      }
      // never inside the previous one or two bars' range
      if(up) { sar = MathMin(sar, low[i - 1]);  if(i > 1) sar = MathMin(sar, low[i - 2]); }
      else   { sar = MathMax(sar, high[i - 1]); if(i > 1) sar = MathMax(sar, high[i - 2]); }
      SarBuf[i] = sar; EpBuf[i] = ep; AfBuf[i] = af; DirBuf[i] = up ? 1.0 : -1.0;
   }
   return rates_total;
}

When start equals increment, the built-in handle is a valid replacement on closed bars:

// ta.sar(start, increment, maximum)  vs  iSAR(symbol, timeframe, step, maximum)
// iSAR has no separate start: its step is both the starting and the added
// acceleration. ta.sar(0.02, 0.02, 0.2) maps exactly; ta.sar(0.01, 0.02, 0.2) cannot.
int sarHandle = iSAR(_Symbol, _Period, 0.02, 0.2);

Where the two differ

AspectPine ta.sarMQL5 iSAR
Parametersstart, increment, maximumstep, maximum (step = start = increment)
First trendFrom the first two closesAlways starts as a downtrend
Forming barRecomputed each tick, can flip intrabarThe standard indicator computes the next bar's SAR from closed bars; a reversal shows once the bar has closed
Bar 0naThe first bar's high
ClampPrevious one or two bars' rangePrevious two bars' range
PlotUsually plot.style_crossDRAW_ARROW with a dot glyph

The seeding difference means the two can disagree about the trend for the first stretch of the chart; after reversals both follow the same rules on the same bars, so compare well inside the history. The forming-bar difference matters for Expert Advisors: a Pine strategy that reacts to a SAR flip on the realtime bar sees it earlier than an EA reading iSAR on the current bar. Read bar 1 (the last closed bar) in both if you want them to agree.

What the Stratlate converter emits

On the chart timeframe the converter computes the SAR inline with its runtime helper pine_sar(high, low, close, result, extreme, af, dir, bar, start, inc, max), a transcription of Pine's reference algorithm with four per-bar state arrays, so the three arguments, the seeding from the first two closes and the intrabar flip are Pine's. No handle is used. Inside request.security(...) on another timeframe it creates iSAR(symbol, tf, start, max) and drops the increment, which is exact only when start equals increment; that higher-timeframe read is flagged as an approximation. In the test script above the only note is PM295: plot.style_cross is drawn as a line, so you may want to change the plot to DRAW_ARROW as in the code on this page. Compile and backtest the output.

Pitfalls

  • Passing Pine's three numbers to iSAR in order: iSAR(sym, tf, 0.02, 0.02) sets the maximum to 0.02, and the SAR barely accelerates.
  • Using iSAR for ta.sar(0.01, 0.02, 0.2). Every trend starts with twice the acceleration and reversals come earlier.
  • Drawing the SAR with DRAW_LINE. Each reversal draws a vertical segment across the candles; use DRAW_ARROW.
  • Keeping the extreme point and acceleration in static variables. Every tick on the forming bar accelerates again and the SAR races toward price.
  • Expecting identical values on the first trend of the chart. MetaTrader always seeds a downtrend; Pine looks at the first two closes.
  • Trading a SAR flip on the forming bar in an EA. The flip can reverse before the close; Pine strategies without calc_on_every_tick only act on the closed bar.

FAQ

How do the ta.sar arguments map to iSAR?

iSAR(symbol, timeframe, step, maximum) takes the acceleration step and the maximum. Pine's start and increment both correspond to the step, so ta.sar(0.02, 0.02, 0.2) becomes iSAR(_Symbol, _Period, 0.02, 0.2). If start differs from increment there is no exact iSAR setting.

Why does my converted SAR differ at the start of the chart?

The first trend is seeded differently: Pine compares the first two closes, MetaTrader's standard indicator starts every chart in a downtrend. After the first reversals both follow the same rules, so compare values deeper in the history.

Can the Parabolic SAR repaint?

On the forming bar, yes: the reversal test uses the bar's current high and low, so a dot can switch sides during the bar and switch back. Once the bar closes the value is fixed in both platforms.

Convert the whole script

Paste a Pine Script indicator or strategy and get MQL5 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