math.* in MQL5: MathAbs, MathRound, math.sum and math.sign

Short answer

Most math.* functions have a Math-prefixed MQL5 equivalent: math.abs is MathAbs, math.pow is MathPow, math.log is MathLog. Write math.sign, math.round with precision and math.sum yourself; math.sum is a sliding window over a series, and MathMax takes only two arguments.

Most of Pine's math.* namespace has a one-to-one MQL5 function with a Math prefix: math.abs is MathAbs, math.pow is MathPow, math.log is MathLog. The differences are in the details: Pine's math.max takes any number of arguments while MathMax takes two, math.round has a precision argument MathRound lacks, math.sign has no MQL5 function, and math.sum is not a plain sum at all but a sliding window over a series.

What math.* computes

  • math.abs, math.sqrt, math.log (natural), math.log10, math.exp, math.pow, trigonometric functions: the usual scalar functions; an na argument gives na.
  • math.max(a, b, …) and math.min(a, b, …): any number of arguments.
  • math.round(x): nearest integer, ties rounded up; math.round(x, precision) rounds to that many decimals. math.floor and math.ceil round down and up.
  • math.sign(x): -1, 0 or 1.
  • math.avg(a, b, …): the mean of its arguments on the current bar, not over time.
  • math.sum(source, length): the sum of the last length values of a series; na until length bars exist.
  • math.round_to_mintick(x): rounded to the symbol's tick size.

The MQL5 equivalent

The example plots a 10-bar sliding volume sum and the sign of each candle, and prints the scalar cases once so both platforms can be compared side by side.

//@version=6
indicator("math demo")
int length = input.int(10, "Length")
plot(math.sum(volume, length), "math.sum(volume, 10)")
plot(math.sign(close - open), "math.sign(close - open)", color=color.orange)
if barstate.isfirst
    log.info("avg=" + str.tostring(math.avg(1, 2, 4)) + " round(2.5)=" + str.tostring(math.round(2.5)) + " round(-2.5)=" + str.tostring(math.round(-2.5)) + " round(1.2345, 2)=" + str.tostring(math.round(1.2345, 2)) + " max=" + str.tostring(math.max(3, 7, 5)))
#property indicator_separate_window
#property indicator_buffers 3
#property indicator_plots   2
#property indicator_type1   DRAW_LINE
#property indicator_color1  clrDodgerBlue
#property indicator_label1  "math.sum(volume, 10)"
#property indicator_type2   DRAW_LINE
#property indicator_color2  clrOrangeRed
#property indicator_label2  "math.sign(close - open)"

input int Length = 10;

double SumBuf[];
double SignBuf[];
double VolBuf[];   // volume as double, one slot per bar

// Pine: math.round(x, precision) -- half away from zero, like MathRound
double RoundTo(const double x, const int precision)
{
   double p = MathPow(10.0, precision);
   return MathRound(x * p) / p;
}

// Pine: math.sign(x) -- MQL5 has no sign function
double Sign(const double x) { return x > 0 ? 1.0 : (x < 0 ? -1.0 : 0.0); }

// Pine: math.sum(src, len) -- a sliding window, NaN until it is full
double WindowSum(const double &src[], const int i, const int len)
{
   if(i < len - 1) return MathLog(-1.0);
   double s = 0.0;
   for(int k = i - len + 1; k <= i; k++) s += src[k];
   return s;
}

int OnInit()
{
   SetIndexBuffer(0, SumBuf, INDICATOR_DATA);
   SetIndexBuffer(1, SignBuf, INDICATOR_DATA);
   SetIndexBuffer(2, VolBuf, INDICATOR_CALCULATIONS);
   PlotIndexSetDouble(0, PLOT_EMPTY_VALUE, EMPTY_VALUE);
   // Pine: math.avg(1, 2, 4) = 2.3333, math.round(2.5) = 3, math.round(-2.5) = -3
   Print("avg=", (1.0 + 2.0 + 4.0) / 3.0, " round(2.5)=", MathRound(2.5), " round(-2.5)=", MathRound(-2.5),
         " round(1.2345, 2)=", RoundTo(1.2345, 2), " max(3,7,5)=", MathMax(3.0, MathMax(7.0, 5.0)));
   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 > 0 ? prev_calculated - 1 : 0;
   for(int i = start; i < rates_total; i++)
   {
      VolBuf[i] = (double)tick_volume[i];   // Pine volume; use volume[] where the broker has real volume
      double s = WindowSum(VolBuf, i, Length);
      SumBuf[i]  = MathIsValidNumber(s) ? s : EMPTY_VALUE;
      SignBuf[i] = Sign(close[i] - open[i]);
   }
   return rates_total;
}

The window sum loops over length values per bar, which is fine for short windows. For long windows keep a running total in a calculation buffer: add the new value, subtract the one that left the window, and resynchronise after a full recalculation.

Where the two differ

PineMQL5Note
math.abs, floor, ceil, sqrt, exp, log, log10, powMathAbs, MathFloor, MathCeil, MathSqrt, MathExp, MathLog, MathLog10, MathPowdirect
math.max(a, b, c)MathMax(a, MathMax(b, c))two arguments only
math.round(x)MathRound(x)agree on positive halves (2.5 → 3); MathRound rounds negative halves away from zero, so check -2.5 if it matters
math.round(x, 2)MathRound(x * 100) / 100 or NormalizeDouble(x, 2)no precision argument
math.sign(x)x > 0 ? 1 : x < 0 ? -1 : 0no built-in
math.avg(a, b, c)(a + b + c) / 3.0beware integer division
math.sum(x, n)loop over x[i-n+1..i]sliding window, not a total; for a running total see ta.cum
na inputNaN in, NaN outsame, if na is represented as NaN

What the Stratlate converter emits

The scalar functions map to their Math* twins; math.max and math.min with more than two arguments are folded into nested MathMax/MathMin calls; math.sign becomes an inline ternary; math.avg is the inline mean; math.sum uses the runtime's pine_sum window helper, which returns na until the window is full or when any value in it is na; math.round_to_mintick becomes NormalizeDouble(x, _Digits). One gap: math.round(x, precision) is currently emitted as MathRound(x) and the precision is dropped without a note in the report (the example converted CLEAN and printed 1 for math.round(1.2345, 2)). Replace such calls with NormalizeDouble(x, precision) in the output.

Pitfalls

  • Integer division: (a + b) / 2 with int operands truncates in MQL5. Write 2.0. Symptom: averages that move in whole steps.
  • Reading math.sum as a cumulative sum: it is a window. Translating it to a running total makes the line grow without bound.
  • Passing three arguments to MathMax: MetaEditor reports "wrong parameters count".
  • Using MathRound for price rounding: it gives whole numbers. Round prices with NormalizeDouble(x, _Digits) or to the tick size.
  • MathLog of zero or a negative number gives -inf or NaN, the same as Pine's na for the negative case but not for zero. Guard divisions and logs of volume on bars with zero volume.

FAQ

Is there math.sign in MQL5?

No. Write it as a ternary: x > 0 ? 1 : (x < 0 ? -1 : 0). MathAbs(x) / x is shorter but divides by zero when x is 0.

How do I round to two decimals in MQL5?

NormalizeDouble(x, 2) returns the value rounded to two decimals, which is what Pine's math.round(x, 2) does. For text, DoubleToString(x, 2) formats with exactly two decimals.

Is Pine math.sum the same as a for-loop sum in MQL5?

It is a for-loop over the last length bars of the series, recomputed on every bar, and na until length bars exist. A loop over the whole array from bar 0 is ta.cum, not math.sum.

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