Skip to content

Pine Script

Pine Script math.clamp: Bound Values With min and max

Pine Script's v5 and v6 reference manuals list no built-in math.clamp(). To clamp a number between a lower and an upper bound, use math.min(math.max(value, lower), upper), with lower no greater than upper. Values inside the interval stay unchanged; values outside it become the nearest boundary. Clamping limits a number, but does not check missing data, broker volume steps or whether the chosen bounds make sense.

Illustrative Pine Script clamp cover showing a changing input clipped between two horizontal bounds.
Clamping keeps a value within an interval; it does not validate the meaning of those bounds.

Part of the Pine Script function reference. As of 25 September 2026, the documented building blocks are math.min() and math.max(); a function called clamp() in another script may be a custom helper.[1][5]

Clamping in Pine Script at a glance

Scroll horizontally to read every column.

Item Meaning
Expression math.min(math.max(value, lower), upper)
Inputs A numeric value and two numeric bounds in the same units
Required relationship lower <= upper; handle missing values explicitly
Result Lower bound, original value or upper bound, depending on the input
Typical coding use Bounding a score or a calculated input before another operation
Not established by clamping Valid broker lot increments, a complete message or an accepted order

What is the correct clamp formula?

Clamped value = min(max(value, lower), upper), provided lower ≤ upper

math.max(value, lower) selects the larger argument, lifting anything below the lower bound up to that bound. math.min(..., upper) then selects the smaller argument, bringing anything above the upper bound down to it.[1]

  • Below the interval: return the lower bound.
  • Inside the interval, including either boundary: keep the value.
  • Above the interval: return the upper bound.

The built-ins accept numeric arguments; they do not assign units. A result measured in lots needs bounds measured in lots. A score needs score bounds. The custom helper below uses float arguments, so its output is a float value or na, not a true-or-false test.

Bounds with equal values are valid mathematically: clamping any available number between 20 and 20 returns 20. Reversed bounds are a different case. With lower 80 and upper 20, the expression returns 20 for any finite input, silently hiding the incorrect interval.

Worked example: clamp a score between 20 and 80

Illustrative values, not recommended settings. Let the lower bound be 20 and the upper bound be 80. Each row represents a separate input, not a trading result.

Input value After max(value, 20) After min(result, 80)
10 20 20
20 20 20
50 50 50
80 80 80
90 90 80

For 10, the calculation is min(max(10, 20), 80) = min(20, 80) = 20. For 90, it is min(max(90, 20), 80) = min(90, 80) = 80. The middle value, 50, passes through unchanged.

Illustrative Pine Script clamp diagram: inputs 10, 50 and 90 become 20, 50 and 80 when bounded between 20 and 80.
Illustrative arithmetic. Clamping changes values outside the bounds and leaves values inside them unchanged.

How do you write a clamp helper in Pine Script v6?

Illustrative sketch; not compiled or tested. Paste into TradingView's Pine Editor. The helper checks for missing arguments and reversed bounds before applying the formula. The default input of 50 and bounds of 20 and 80 only reproduce the example.[1]

//@version=6
indicator("Clamp arithmetic sketch")
clampValue(float value, float lower, float upper) =>
    valid = not na(value) and not na(lower) and not na(upper) and lower <= upper
    valid ? math.min(math.max(value, lower), upper) : na
raw = input.float(50.0, "Illustrative value")
bounded = clampValue(raw, 20.0, 80.0)
plot(bounded, "Bounded value")

clampValue() is defined by this example; it is not a TradingView built-in. With the default input, the plot is 50. Changing the input to 10 gives 20; changing it to 90 gives 80. The sketch creates no alerts or orders.

The guard is a deliberate policy: invalid inputs return na. Another application might report an error instead. Blindly applying nz() before the clamp introduces a replacement value and can turn missing information into an apparently valid boundary result. See nz() and missing-value handling.

Is clamping the same as normalising?

No. Clamping clips values at two boundaries; rescaling changes their scale. TradingView's techniques FAQ distinguishes rescaling a known range from normalising an unbounded series using its historical extremes.[2]

Rescaled value in 0–1 = (value − lower) ÷ (upper − lower), provided upper > lower

Illustrative: 50 in the range 20–80 maps to (50 − 20) ÷ (80 − 20) = 30 ÷ 60 = 0.5. Clamping that same 50 to 20–80 simply returns 50. Equal bounds permit a clamp but make this rescaling formula divide by zero.

Rescaling also does not necessarily bound the result. An input of 90 maps to 70 ÷ 60 = 1.1667, rounded to four decimal places. Clamping that rescaled result to 0–1 would return 1, discarding how far the input exceeded the original range.

A percent rank answers another question: how many comparison values are at or below the current value. None of these transformations supplies a trading recommendation.

What does clamping a position-size input actually check?

A clamp can bound a number calculated in Pine Script, but a broker order has more constraints. PineConnector's syntax reference requires checking the receiving symbol's minimum volume, maximum volume and volume step.[3]

Illustrative broker specification: minimum 0.10 lots, maximum 1.00 lot, step 0.10 lots. A value of 0.26 is between the bounds, so the clamp leaves it unchanged. It still falls between the permitted 0.20 and 0.30 increments.

A lower bound can also increase an intended size. Clamping 0.05 lots to that interval produces 0.10 lots, twice the original value. The code must explicitly distinguish accepting a resized value from rejecting a request outside its permitted range. Clamping alone makes no such decision.

vol_lots= carries a volume in lots in PineConnector Syntax; it is not a clamp command. The syntax reference does not establish the EA's rounding direction. For that behaviour: not documented; test on demo, and compare requested and accepted volume.[3]

A bounded input remains upstream of the alert condition, alert trigger, webhook delivery, PineConnector processing and EA order request. Broker acceptance, the deal and the resulting position require separate evidence. The demo verification guide follows those checkpoints.[4]

What are the common clamp mistakes?

  • Calling a nonexistent built-in: importing the name from another programming language does not make math.clamp() available in Pine Script.
  • Reversing the bounds: check their relationship before applying the expression.
  • Replacing missing values without a rule: a substituted zero may become the lower bound, hiding the original missing input.
  • Discarding the raw value: keeping both raw and bounded values during inspection reveals how often the boundaries change the calculation.
  • Confusing a number with permission: being inside a range does not establish valid increments, sufficient margin or a broker fill.
  • Assuming the transformation adds information: once several inputs become the same boundary value, the bounded output no longer distinguishes them.

Frequently asked questions

Does math.clamp() exist in Pine Script v5?

math.clamp() is not a built-in listed in the Pine Script v5 reference. Use math.min(math.max(value, lower), upper) with correctly ordered numeric bounds, or define a custom helper around that expression. A similarly named function in a published script may belong to its author or an imported library.

How do I clamp a value in Pine Script v6?

Use math.min(math.max(value, lower), upper) after checking that the inputs are available and lower is no greater than upper. The inner maximum enforces the lower bound; the outer minimum enforces the upper bound. Values already inside the interval, including the boundary values, remain unchanged.

Does clamping normalise an indicator?

Clamping clips values at selected boundaries; it does not rescale the interval. Illustratively, clamping 50 between 20 and 80 returns 50. Rescaling that same interval to 0–1 returns 0.5. A separate clamp can bound a rescaled output, but doing so discards information about values outside the original range.

Can a clamp make a lot size valid for MT5?

A clamp can place a numeric lot size between minimum and maximum values, but it does not enforce the broker's volume step. It can also increase a below-minimum request. Check the receiving symbol's specification and verify the requested and accepted volume separately; an in-range number is not evidence of an accepted order.

Reviewed 25 September 2026. Facts were checked against the linked sources on that date. Nothing in this article was tested on a trading account and no code was compiled.

Related reading

Sources

  1. TradingView – Pine Script v6 Reference Manual, accessed 25 September 2026.
  2. TradingView – Pine Script FAQ: Techniques, accessed 25 September 2026.
  3. PineConnector – PineConnector Syntax: broker values and volume handling, accessed 25 September 2026.
  4. PineConnector – Test your setup, accessed 25 September 2026.
  5. TradingView – Pine Script v5 Reference Manual, accessed 25 September 2026.

PineConnector executes the instructions you send it. It does not select trades, manage money, or hold funds. Trading carries risk, and past performance of any strategy does not indicate future results.


Leave a comment

Back To PiCo Blog

Ready when your strategy is

You bring the strategy.We bring the infrastructure.

Connect TradingView to MetaTrader, choose where MT5 runs and put the full PineConnector workflow through its paces from your first month.

Strategy and trading decisions remain yours. The MT5 environment can be ours.

PineConnector Edge

Run the full PineConnector workflow.

$59/mo at launch

Core plan · 1 connection · 1 hosted MT5 environment

Try Core for $7

7 days of Core for $7, then $59/month at the launch price unless you cancel.