Data Types#

QuantScript supports the following primitive types:

Number

Integer and floating-point numbers.

QuantScript
42
3.14
-17
2.5e10

Boolean

Logical values true and false.

String

Text values in single or double quotes: "Hello" or 'Hello'.

Null

Represents the absence of a value: null.

Color

Hex color literals: #FF0000, #00FF00FF.

Variables and Constants#

Declaration

Use let for mutable variables and const for constants.

QuantScript
let x = 10;
const PI = 3.14159;

Destructuring

QuantScript
const [a, b, c] = [1, 2, 3];
let [first, second] = myArray;

Compound Assignment

Supported: +=, -=, *=, /=.

Operators#

Arithmetic

OperatorDescriptionExample
+Addition10 + 5 → 15
-Subtraction10 - 5 → 5
*Multiplication10 * 5 → 50
/Division10 / 3 → 3.333
%Modulo10 % 3 → 1
**Exponentiation2 ** 8 → 256

Comparison

==, !=, ===, !==, <, >, <=, >=

Logical

&& (AND), || (OR), ! (NOT) — all short-circuit.

Ternary

QuantScript
let result = condition ? valueIfTrue : valueIfFalse;

Nullish Coalescing & Optional Chaining

QuantScript
let value = maybeNull ?? defaultValue;
let prop = obj?.property;

Member Access & History

QuantScript
let value = object.property;
let first = array[0];
let prev = close[1];  // Previous bar's close

Control Flow#

If Statement

QuantScript
if (condition) {
    // code
} else if (other) {
    // code
} else {
    // code
}

For Loop

QuantScript
for (let i = 0; i < 10; i++) { /* ... */ }

for (const item of myArray) { /* ... */ }

While Loop

QuantScript
while (condition) { /* ... */ }

Use break to exit a loop and continue to skip to the next iteration.

Functions#

Function Declaration

QuantScript
function add(a, b) {
    return a + b;
}

Arrow Functions

QuantScript
const square = (x) => x * x;
const add = (a, b) => { return a + b; };

Default & Named Parameters

QuantScript
function calculate(x, y = 10) { return x + y; }

config(name: "setting", value: 42);

Arrays and Objects#

QuantScript
let numbers = [1, 2, 3, 4, 5];
let config = { period: 14, multiplier: 2.0, enabled: true };

Access elements with numbers[0] and properties with config.period or config["period"].

Built-in Functions#

Global functions available without a namespace prefix.

alert(message, freq?)

Display an alert message.

message
Alert message text
freq
"once" (default) or "all"
alertcondition(condition, title?, message?)

Trigger an alert when a condition is true.

nz(source, replacement?)

Replace null values with a default value (default: 0).

tostring(value)

Convert a value to its string representation.

tonumber(str)

Convert a string to number. Returns null if invalid.

na(x)

Check if a value is null. Returns true if null.

console.log(...args)

Print values to console output.

console.error(...args)

Print error to console output.

Technical Analysis (ta.*)#

Moving Averages

ta.sma(source, length)

Simple Moving Average.

source
Input series (e.g., close prices)
length
Number of periods

Returns: SMA value

ta.ema(source, length)

Exponential Moving Average.

Returns: EMA value

ta.wma(source, length)

Weighted Moving Average.

Returns: WMA value

ta.rma(source, length)

Recursive Moving Average (Wilder's smoothing).

Returns: RMA value

ta.swma(source, length)

Sine-Weighted Moving Average.

Returns: SWMA value

ta.hma(source, length)

Hull Moving Average.

Returns: HMA value

ta.alma(source, length, offset?, sigma?)

Arnaud Legoux Moving Average.

offset
Offset parameter (default: 0.85)
sigma
Sigma parameter (default: 6)

Returns: ALMA value

ta.linreg(source, length)

Linear Regression.

Returns: Linear regression value

Oscillators

ta.rsi(source, length)

Relative Strength Index.

Returns: RSI value (0-100)

ta.macd(source, fastLength, slowLength, signalLength)

Moving Average Convergence Divergence.

Returns: Array of [macdLine, signalLine, histogram]

ta.stoch(source, high, low, length)

Stochastic Oscillator.

Returns: Stochastic value (0-100)

ta.roc(source, length)

Rate of Change.

Returns: ROC percentage

ta.mom(source, length)

Momentum.

Returns: Momentum value

Volatility

ta.stdev(source, length)

Standard Deviation.

ta.variance(source, length)

Variance.

ta.dev(source, length)

Mean Deviation.

ta.bbands(source, length, mult?)

Bollinger Bands. mult defaults to 2.

Returns: Array of [lower, middle, upper]

ta.kc(source, length, mult?)

Keltner Channels. mult defaults to 2.

Returns: Array of [lower, middle, upper]

Utility Functions

ta.crossover(source1, source2)

Check if source1 crosses over source2.

Returns: true if crossover occurred

ta.crossunder(source1, source2)

Check if source1 crosses under source2.

Returns: true if crossunder occurred

ta.highest(source, length?)

Highest value over a period.

ta.lowest(source, length?)

Lowest value over a period.

ta.highestbars(source, length)

Bar index of highest value. Returns negative bar offset.

ta.lowestbars(source, length)

Bar index of lowest value. Returns negative bar offset.

ta.change(source, length?)

Change in value over a period.

ta.falling(source, length?)

Check if series is falling.

ta.rising(source, length?)

Check if series is rising.

ta.barssince(condition)

Number of bars since condition was true.

ta.valuewhen(condition, source, occurrence?)

Value of source when condition was last true.

ta.cum(source)

Cumulative sum of a series.

ta.median(source, length)

Median value over a period.

ta.percentrank(source, length)

Percentile rank (0-100).

ta.pivothigh(source, leftBars, rightBars)

Pivot high point. Returns value or null.

ta.pivotlow(source, leftBars, rightBars)

Pivot low point. Returns value or null.

ta.correlation(source1, source2, length)

Correlation between two series (-1 to 1).

Math Functions (math.*)#

Basic Operations

math.abs(x)

Absolute value.

math.max(a, b, ...)

Maximum of multiple values.

math.min(a, b, ...)

Minimum of multiple values.

math.pow(base, exp)

Power function.

math.sqrt(x)

Square root.

math.sign(x)

Sign of a number (1, -1, or 0).

Rounding

math.round(x, precision?)

Round to nearest integer or specified precision.

math.ceil(x)

Round up to nearest integer.

math.floor(x)

Round down to nearest integer.

Logarithmic & Exponential

math.log(x, base?)

Natural logarithm or with specified base.

math.log10(x)

Base-10 logarithm.

math.log2(x)

Base-2 logarithm.

math.exp(x)

Exponential function (e^x).

Trigonometric

math.sin(x), math.cos(x), math.tan(x)

Sine, cosine, tangent. Input in radians.

math.asin(x), math.acos(x), math.atan(x)

Inverse trig functions. Returns radians.

math.atan2(y, x)

Arc tangent of y/x using signs for quadrant.

math.todegrees(x), math.toradians(x)

Angle conversion.

Statistical & Constants

math.avg(values...)

Average of multiple values.

math.sum(source, length)

Sum of series over a period.

math.random()

Random number in [0, 1).

math.pi, math.e, math.phi

Mathematical constants: π, e, φ.

String Functions (str.*)#

Query

str.length(source)

Get string length.

str.contains(source, substring)

Check if string contains substring.

str.startswith(source, prefix)

Check if string starts with prefix.

str.endswith(source, suffix)

Check if string ends with suffix.

str.pos(source, substring, from?)

Find position of substring. Returns index or null.

str.matches(source, regex)

Check if string matches regex.

Transform

str.lower(source), str.upper(source)

Convert to lowercase / uppercase.

str.trim(source)

Remove leading/trailing whitespace.

str.reverse(source)

Reverse the string.

str.replace_all(source, old, newStr)

Replace all occurrences of a substring.

str.substring(source, beginIndex, endIndex?)

Extract a substring.

str.repeat(source, times)

Repeat string multiple times.

str.pad(source, length, padding?, padLeft?)

Pad string to specified length.

Split, Join & Format

str.split(source, separator)

Split string into array.

str.join(source, separator)

Join array into string.

str.tostring(source), str.tonumber(source)

Type conversion.

str.format(format, args...)

Format string with {0}, %s, %d, %f placeholders.

Array Functions (array.*)#

Constructors

array.new_int(size, initialValue?)

Create array of integers.

array.new_float(size, initialValue?)

Create array of floats.

array.new_bool(size, initialValue?)

Create array of booleans.

array.new_string(size, initialValue?)

Create array of strings.

array.new_color(size, initialValue?)

Create array of colors.

array.from(source)

Create array from a value or copy an array.

Mutation

array.push(id, value)

Add element to end.

array.unshift(id, value)

Add element to beginning.

array.pop(id)

Remove and return last element.

array.shift(id)

Remove and return first element.

array.insert(id, index, value)

Insert element at index.

array.remove(id, index)

Remove element at index.

array.clear(id)

Remove all elements.

array.fill(id, value, from?, to?)

Fill array with a value.

Access & Search

array.get(id, index), array.set(id, index, value)

Get/set element at index.

array.first(id), array.last(id)

Get first/last element.

array.size(id), array.isempty(id)

Get size or check if empty.

array.includes(id, value), array.indexof(id, value)

Search for value.

Slice, Sort & Aggregate

array.slice(id, from?, to?)

Extract a portion of array.

array.concat(id, other), array.copy(id)

Concatenate or copy arrays.

array.sort(id, order?)

Sort array. 0 = ascending (default), 1 = descending.

array.avg(id), array.sum(id), array.min(id), array.max(id)

Aggregate functions.

array.range(id), array.median(id), array.stdev(id)

Statistical functions.

array.join(id, separator?)

Join elements into string.

Chart Functions (chart.*)#

chart.plot(source, title?, color?, style?)

Plot a data series on the chart.

source
Data series to plot
title
Plot title/label
color
Color (hex format)
style
Plot style
chart.plotshape(series, title?, style?, color?, size?, text?)

Plot a shape marker on the chart.

chart.hline(price, title?, color?, style?)

Draw a horizontal line at a price level.

chart.bgcolor(color, title?)

Set background color.

chart.pane(name?)

Create or switch to a named pane.

Strategy Functions (strategy.*)#

Order Management

strategy.entry(id, direction, qty?, qty_type?, limit?, stop?, ...)

Enter a position.

id
Order identifier
direction
"long" or "short"
qty
Quantity (default: from config)
qty_type
"fixed", "cash", or "percent_of_equity"
strategy.close(id, qty?, qty_percent?, comment?)

Close a position.

strategy.close_all(comment?)

Close all open positions.

strategy.exit(id, from_entry?, profit?, loss?, trail_points?, ...)

Set exit conditions for a position.

strategy.order(id, direction, ...)

Place an order. Same parameters as strategy.entry.

strategy.cancel(id), strategy.cancel_all()

Cancel pending orders.

Properties

PropertyDescription
strategy.position_sizeCurrent position size
strategy.position_avg_priceAverage entry price
strategy.equityCurrent equity
strategy.cashAvailable cash
strategy.openprofitOpen position profit
strategy.netprofitNet profit
strategy.opentradesNumber of open trades
strategy.closedtradesNumber of closed trades
strategy.wintradesWinning trades count
strategy.losstradesLosing trades count

Constants

ConstantDescription
strategy.longLong direction
strategy.shortShort direction
strategy.fixedFixed quantity type
strategy.cashCash quantity type
strategy.percent_of_equityPercent of equity type

DataFrame Operations#

df.forEach(callback)

Iterate over each frame (bar) in the DataFrame.

QuantScript
df.forEach((frame) => {
    let closePrice = frame.close;
    let highPrice = frame.high;
});

Frame Properties

PropertyDescription
bar_indexCurrent bar index (0-based)
last_bar_indexIndex of the last bar
barstate.isfirsttrue if first bar
barstate.islasttrue if last bar
barstate.isnewtrue if new bar
barstate.isconfirmedtrue if bar is confirmed
frame.hl2(high + low) / 2
frame.hlc3(high + low + close) / 3
frame.hlcc4(high + low + close + close) / 4
frame.ohlc4(open + high + low + close) / 4

Historical Reference

QuantScript
let prevClose = close[1];  // Previous bar's close
let twoAgo = high[2];     // High from 2 bars ago

Script Declaration#

QuantScript
// Indicator script
indicator("My Indicator");

// Strategy script
strategy("My Strategy");

Comments & Semicolons#

QuantScript
// Single-line comment

/*
  Multi-line comment
*/

// Semicolons are optional
let x = 10
let y = 20;