cond
Conditional/ternary operator (if-then-else)
cond(condition, if_true, if_false)
Evaluates a condition and returns one of two values based on the result. This is the ternary operator for StonQL, enabling if-then-else logic within expressions. Use it to create conditional calculations, classify price action, and build complex decision logic.
Parameters
- condition (expression): Boolean expression to evaluate
- if_true (expression): Value returned when condition is true
- if_false (expression): Value returned when condition is false
Formula
cond(A, B, C) → B when A is true, otherwise C
Examples
Bullish/Bearish Bar Indicator
Convert price action into numeric values for analysis:
// 1 for up days, 0 for down days
cond(close > open, 1, 0);
Conditional Distance Calculation
Calculate distance from moving average only when price is above it:
// distance above MA (zero when below)
cond(close > sma(close, 20), close - sma(close, 20), 0);
Multi-Level Classification with Nesting
Classify RSI into zones by nesting multiple cond() calls:
// -1 = overbought, 1 = oversold, 0 = neutral
cond(rsi(close, 14) > 70, -1,
cond(rsi(close, 14) < 30, 1, 0));
Safe Division
Protect against divide-by-zero errors in ratio calculations:
// body-to-range ratio, safe when range is zero
cond(bar_range != 0, bar_change / bar_range, 0);
Returns
Value of if_true or if_false depending on condition evaluation
Notes
- Can be nested for multi-level classification (if-else-if chains)
- Arguments can be any expression: fields, functions, or constants
- Both branches are evaluated, so use for calculations not side effects