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
result = a MOD bParameters
| Name | Type | Description |
|---|---|---|
a | number | The dividend, the value being divided. |
b | number | The divisor. Must not be zero, since division by zero is undefined. |
Formula
MOD(a, b) = remainder of a / bFor 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)
// 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)
// 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)
// 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
ENDIFThe 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 0is undefined and raises an error. Guard the divisor when it can reach zero. - Infix operator, not a function. Write
a MOD b, notMOD(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
ABSfirst if you need a non-negative cycle position.
