Mathematical/probuilder · probacktest · proorder · proscreener

MOD

MOD in ProBuilder returns the remainder of dividing one number by another, the modulo operation. Infix syntax, use for cycles and divisibility, examples.

Syntax

probuilder
result = a MOD b

Parameters

NameTypeDescription
anumberThe dividend, the value being divided.
bnumberThe divisor. Must not be zero, since division by zero is undefined.

Formula

code
MOD(a, b) = remainder of a / b

For example 10 MOD 3 is 1, because 10 divided by 3 is 3 with a remainder of 1. When a is an exact multiple of b, the remainder is 0.

How it works

MOD is written between its two operands, like a MOD b, rather than as MOD(a, b). It returns what is left over after integer division. This makes it the go-to tool for two tasks: testing divisibility, where a MOD b = 0 means a divides evenly by b, and cycling through a repeating range, where barCount MOD n counts 0, 1, ... n-1 and wraps back to 0.

The divisor must not be zero. A MOD 0 is undefined and raises an error, so guard b whenever it can reach zero.

Examples

Example 1, Remainder of a division (Indicator)

probuilder
// Remainder when 10 is divided by 3
remainder = 10 MOD 3
RETURN remainder AS "10 MOD 3"

The result is 1, the leftover after dividing 10 by 3. Replacing the constants with variables generalizes the calculation.

Example 2, Every third bar flag (ProScreener)

probuilder
// Flag instruments on a repeating three-bar cycle
cyclePos = BarIndex MOD 3
SCREENER[cyclePos = 0](cyclePos AS "Cycle position")

BarIndex MOD 3 cycles through 0, 1, 2 and back, so the condition fires once every three bars.

Example 3, Trade only on even bars (ProOrder)

probuilder
// Restrict entries to every second bar using MOD
phase = BarIndex MOD 2
IF phase = 0 AND NOT LongOnMarket AND close CROSSES OVER Average[20](close) THEN
  BUY 1 CONTRACT AT MARKET
ENDIF

The MOD 2 test splits bars into even and odd, letting the strategy act on only one of the two.

Common errors and gotchas

  • Divisor cannot be zero. a MOD 0 is undefined and raises an error. Guard the divisor when it can reach zero.
  • Infix operator, not a function. Write a MOD b, not MOD(a, b). The function-call form is a syntax error.
  • Result sign follows the dividend. For negative dividends the remainder is not always what you expect. Wrap with ABS first if you need a non-negative cycle position.
  • FLOOR, rounds down to an integer, related to the quotient behind MOD.
  • CEIL, rounds up to an integer.
  • ROUND, rounds to the nearest integer or decimal.
  • ABS, absolute value, useful to normalize a MOD result to non-negative.
  • SGN, sign of a value.
  • MAX, larger of two values.
  • MIN, smaller of two values.