# Cuprel language reference (edition 1)

One file with the syntax, what is not available and every function of Cuprel, the script language of MillionChart (https://millionchart.com).
For an AI assistant that writes or rewrites a script: use only what is written here; a script starts with its header and `edition = 1`;
if something is listed as not available, say so instead of inventing it. The script editor on the chart checks the result.

Source pages: https://millionchart.com/wiki/scripting

## Already write scripts elsewhere?

If you have written indicators or strategies in other chart scripting languages, most of the ideas carry over: a script runs once for each bar, reads price series, keeps some values from bar to bar and draws what it works out. This page names each idea, shows how Cuprel writes it and links to the page that teaches it. It does not compare products; it only helps you find the words. If you have never written a script, start with [Lesson 1: Your first script](https://millionchart.com/wiki/scripting/tutorial/first-script) instead.

### Idea by idea

| The idea | How it is written here | Read |
|---|---|---|
| A header that says what kind of script it is | `indicator "Name"`, `strategy "Name"` or `module Name`, with its settings indented under it | [Syntax and layout](https://millionchart.com/wiki/scripting/language/syntax) |
| A setting the user can change | `input length: int = 20, name = "Length", min = 1` | [Inputs](https://millionchart.com/wiki/scripting/language/inputs) |
| Price series and earlier bars | `open`, `high`, `low`, `close`, `volume`; `close[1]` is one bar back | [Values and types](https://millionchart.com/wiki/scripting/language/values) |
| Bar-by-bar execution and repaint | the script runs once per bar, oldest to newest; a forming bar changes until it closes | [Lesson 16: Results that look too good](https://millionchart.com/wiki/scripting/tutorial/repaint-and-leaks) |
| Lines and colours | `plot(x, name = …, color = …, width = …, style = …)`, `level`, `shade`, `chart.background` | [Plots and drawings](https://millionchart.com/wiki/scripting/chart/plots-and-drawings) |
| Labels, lines, boxes and tables | `label.new`, `line.new`, `box.new`, `table.new` | [Lesson 8: Labels, lines and boxes](https://millionchart.com/wiki/scripting/tutorial/drawings) |
| Conditions and missing values | `if`, `if … then … else`, `match`; `na`, `is_na(x)`, `x ?? 0` | [na, errors and arithmetic](https://millionchart.com/wiki/scripting/language/na-and-numbers) |
| Functions and loops | `fn name(…): type`, `for … in`, `while` | [Functions, types and enums](https://millionchart.com/wiki/scripting/language/functions) |
| A value kept from bar to bar | `state` (and `state day`, which starts again each trading day); `mut` is recomputed each bar | [let, mut and state](https://millionchart.com/wiki/scripting/language/variables) |
| Another timeframe | `data.series("240", expression, symbol = symbol.id)`, the last closed bar by default | [Lesson 10: Other timeframes and symbols](https://millionchart.com/wiki/scripting/tutorial/other-data) |
| Another symbol | not available in this release: the script is refused (`E-REQ-UNDECLARED`) or stops (`E4001`) | [Lesson 10: Other timeframes and symbols](https://millionchart.com/wiki/scripting/tutorial/other-data) |
| Alerts from a script | `alert.when` and `alert.send`; alerts on your own scripts come with MillionChart Pro and higher plans | [Lesson 11: Alerts that say something](https://millionchart.com/wiki/scripting/tutorial/alerts) |
| Strategies and testing them | `strategy "Name"`, `orders.enter` / `orders.close` / `orders.exit`, costs in `setup:` and `execution:`; tested in the Strategy Lab | [Lesson 15: Testing in the Strategy Lab](https://millionchart.com/wiki/scripting/tutorial/strategy-lab) |

### The real differences

These are the points to read twice, because habits from other languages may lead you astray here.

- **Editions.** Write `edition = 1` in the header. The edition says which reading of the language the script was written for, so a script keeps its meaning when a later edition exists.
- **Blocks by indentation.** A block is the lines indented under it, four spaces a level. There are no braces and no end words, and each statement has a line of its own.
- **The same numbers on every device.** The engine computes the mathematical functions with one fixed implementation, so a script on the same bars gives the same result on every supported device. [Determinism and limits](https://millionchart.com/wiki/scripting/reference/determinism) says exactly what this covers.
- **Budgets.** Each bar may spend at most 500,000 operations and a run 600,000,000; history, drawings, requests and memory have limits too. A script that spends more than its budget is stopped with a message that names the bar. See [Limits and budgets](https://millionchart.com/wiki/scripting/reference/limits).
- **na rules.** Comparing a value with `na` is never true, not even `na == na`; the checker warns (`W-NA-COMPARE`). Ask `is_na(x)`, or replace a missing value with `x ?? 0`.
- **Lazy operators.** The right side of `and`, `or` and `??`, and the branches of a one-line `if … then … else`, run only when they are needed. If you are used to a language where both sides always run, note that a call that remembers earlier bars (such as `tech.sma`) runs there only where it is reached, and the checker warns with `W3303`. To run it on every bar, write it on a line of its own first:

```script-warn W3303
indicator "A call that remembers, in an operand"
    edition = 1
    display = price

let strong = close > open and close > tech.sma(close, 20)
plot(if strong then close else na, name = "Strong bars", style = circles)
```

```script
indicator "Bound on its own line first"
    edition = 1
    display = price

let average = tech.sma(close, 20)
let strong = close > open and close > average
plot(if strong then close else na, name = "Strong bars", style = circles)
```

- **Private scripts.** Every script belongs to your account. There is no way to share or publish one in this release.
- **One layout.** The editor's **Format** button (and **Format when saving**) rewrites a script in the one standard layout this guide uses, so you do not need to learn a style guide.

[Lazy operators, W3303 and W3302](https://millionchart.com/wiki/scripting/language/lazy-operators) and [Calls that keep a state](https://millionchart.com/wiki/scripting/language/temporal-calls) explain the last rule in full.

### The same idea, written in Cuprel

Each program is complete: paste it into a new script, press **Save** and **Add to chart**.

A moving average with two settings:

```script
indicator "Average with a setting"
    edition = 1
    display = price

input length: int = 20, name = "Length", min = 1
input src: source = close, name = "Source"
plot(tech.sma(src, length), name = "Average", color = color.orange, width = 2)
```

Marks where a fast average crosses a slow one. The crossing tests are worked out on lines of their own:

```script
indicator "Crossing marks"
    edition = 1
    display = price

let fast = tech.ema(close, 10)
let slow = tech.ema(close, 30)
let up = tech.crosses_above(fast, slow)
let down = tech.crosses_below(fast, slow)
plot(fast, name = "Fast", color = color.green)
plot(slow, name = "Slow", color = color.red)
mark.shape(up, name = "Up", shape = triangle_up, place = below, color = color.green)
mark.shape(down, name = "Down", shape = triangle_down, place = above, color = color.red)
```

A value kept from bar to bar with `state`:

```script
indicator "Bars since a new high"
    edition = 1
    display = pane

state count = 0
if close >= tech.highest(close, 20)
    count = 0
else
    count += 1
plot(count, name = "Bars since", style = histogram, color = color.teal)
```

A value from the four-hour chart. By default it is the value of the last four-hour bar that has closed, so it does not change while that bar is still forming:

```script
indicator "Four-hour average"
    edition = 1
    display = price

let h4 = data.series("240", tech.ema(close, 20), symbol = symbol.id)
plot(h4, name = "4h EMA (last closed bar)", color = color.orange, width = 2)
```

Missing values: `??` gives a replacement, `is_na` asks whether a value is missing:

```script
indicator "Missing values"
    edition = 1
    display = pane

let change = close - close[1]
let average = tech.sma(change, 50)
plot(average ?? 0, name = "Average change, 0 while unknown", color = color.blue)
plot(if is_na(average) then 1 else 0, name = "Still unknown", style = columns, color = color.gray)
```

A function that gives back two results at once:

```script
indicator "Range of the last bars"
    edition = 1
    display = price

fn range_of(length: int): (float, float)
    return (tech.highest(high, length), tech.lowest(low, length))
let (top, bottom) = range_of(20)
plot(top, name = "Top", color = color.green)
plot(bottom, name = "Bottom", color = color.red)
```

A small strategy with a size and a commission. The chart marks its trades; the Strategy Lab tests it over a longer history:

```script
strategy "Crossing strategy"
    edition = 1
    display = price

setup:
    size = sizing.lots(0.1)
    fees = fee.per_lot(3.5)

let fast = tech.ema(close, 10)
let slow = tech.ema(close, 30)
if tech.crosses_above(fast, slow)
    orders.enter("Long", side.long)
if tech.crosses_below(fast, slow)
    orders.close("Long")
plot(fast, name = "Fast", color = color.green)
plot(slow, name = "Slow", color = color.red)
```

> **Note:** If a program you bring from elsewhere does not compile, read the first message in the **Problems** list: [Lesson 18: Reading the editor's messages](https://millionchart.com/wiki/scripting/tutorial/common-mistakes) explains the ones you will meet first, and [Diagnostics](https://millionchart.com/wiki/scripting/reference/diagnostics) explains every code.

Next: [Lesson 1: Your first script](https://millionchart.com/wiki/scripting/tutorial/first-script)

## Cheat sheet

The whole language at a glance. Every form here compiles on the chart; follow the links for the rules.

### A whole indicator

```script
// One program that uses most of the syntax on one page.
indicator "Cheat sheet"
    edition = 1
    display = price

enum Kind
    sma = "SMA"
    ema = "EMA"

type Band
    upper: float
    lower: float

group "Average"
    /// How many bars the average reads
    input length: int = 20, name = "Length", min = 2, max = 500
    input kind: Kind = Kind.ema, name = "Kind"
    input src: source = close, name = "Source"
input width: float = 2.0, name = "Width", min = 0.1, step = 0.1
input band_color: color = #2962ff, name = "Band colour"

session london = 08:00 .. 16:30 @ "Europe/London"

fn band_of(middle: float, size: float): Band = Band(upper = middle + size, lower = middle - size)

let sma = tech.sma(src, length)
let ema = tech.ema(src, length)
let middle = match kind
    Kind.sma => sma
    Kind.ema => ema
let b = band_of(middle, width * tech.atr(length))
state above_count = 0
mut last_three = 0.0
for i in 0 until 3
    last_three += close[i]
if close > b.upper
    above_count += 1
let crossed = tech.crosses_above(close, middle)
let top = plot(b.upper, name = "Upper", color = band_color)
let bottom = plot(b.lower, name = "Lower", color = band_color)
shade(top, bottom, color = color.fade(band_color, 90), name = "Band")
plot(middle, name = "Middle", color = color.gray, width = 2)
plot(last_three / 3, name = "Mean of 3 closes", display = none)
mark.shape(crossed, name = "Cross up", shape = triangle_up, place = below, color = color.green)
chart.background(if london.active then color.fade(color.blue, 94) else na, name = "London")
let yesterday_high = prior(day).high
plot(yesterday_high, name = "Yesterday's high", style = step_break, color = color.orange)
if bar.is_last
    label.new(
        bar.index,
        b.upper,
        f"{above_count} closes above, last {close:price}",
        style = label_down,
    )
```

### The shape of a script

> **Warning:** The lines under the header (`edition = 1`, `display = price`, …) are indented by four spaces. Typed by hand, the line after `indicator "..."` is not indented for you; without the indentation the editor reports `E3102` on `edition` or `display`. Indent them; do not take the **Fix** that offers `let`.

| Write | Means |
|---|---|
| `indicator "Name"` | the header of an indicator; its settings are indented under it |
| `strategy "Name"` | the header of a strategy (simulated orders) |
| `module Name` | the header of a module that other scripts import |
| `    edition = 1` | the edition of the language the script is written for |
| `    display = price` | draw on the price chart; without it the script gets its own pane |
| `// text` | a comment, to the end of the line |
| `/// text` | above an `input`: its tooltip |
| four spaces | one level of a block (`if`, `for`, `fn`, `group` …); a tab is an error |

One statement a line. A long statement goes on when a line ends with an operator or a comma, or inside brackets. See [Syntax and layout](https://millionchart.com/wiki/scripting/language/syntax).

### Names and values

| Write | Means |
|---|---|
| `let x = close - open` | a name set once on each bar, never changed |
| `mut n = 0` | a value that starts again on each bar and may change: `n += 1`, `-=`, `*=`, `/=` |
| `state count = 0` | a value kept from bar to bar; `state day` starts again each trading day |
| `close[1]` | the value one bar back (history) |
| `na`, `is_na(x)`, `x ?? 0` | no value; the test for it; a fallback |
| `20`, `2.5`, `"text"`, `true` | a whole number, a number, a text, a truth value |
| `#2962ff`, `color.red`, `color.fade(c, 80)` | colours: a code, a name, more transparent |
| `08:30`, `@2026-01-01T00:00Z`, `15m`, `0.5%` | a time of day, a moment, a duration, a percentage |
| `[1, 2, 3]`, `[0.0; 4]` | an array; four copies of 0.0 |
| `map<int, float>()` | an empty map from whole numbers to numbers |

See [let, mut and state](https://millionchart.com/wiki/scripting/language/variables), [Values and types](https://millionchart.com/wiki/scripting/language/values), [Units and literals](https://millionchart.com/wiki/scripting/language/units-and-literals).

### Inputs

| Write | Shows |
|---|---|
| `input length: int = 20, name = "Length", min = 1, max = 500` | a whole number with limits |
| `input mult: float = 2.0, name = "Width", step = 0.1` | a number; `step` moves the field |
| `input on: bool = true, name = "Show"` | a switch |
| `input src: source = close, name = "Source"` | the price the script reads |
| `input c: color = color.blue, name = "Colour"` | a colour picker |
| `input tf: tf = "60", name = "Timeframe"` | a timeframe |
| `input kind: text = "EMA", name = "Kind", options = ["EMA", "SMA"]` | a dropdown |
| `input mode: Mode = Mode.fast, name = "Mode"` | a dropdown of an `enum` |
| `group "Name"` | the inputs indented under it share a heading |

See [Inputs](https://millionchart.com/wiki/scripting/language/inputs).

### Operators, loose to tight

| Operators | Note |
|---|---|
| `if c then a else b` | a value chosen by a condition; the `else` is required |
| `or` | the right side runs only when the left is false |
| `and` | the right side runs only when the left is true |
| `not` | looser than a comparison: `not a == b` is `not (a == b)` |
| `==` `!=` `<` `<=` `>` `>=` | not chained: `a < b < c` is an error |
| `??` | the right side when the left is `na` |
| `+` `-` | add, subtract (`+` also joins texts) |
| `*` `/` `%` | multiply, divide, remainder |
| `-x` | minus |
| `x[1]`, `f(x)`, `a.b` | history, a call, a member |

There is no power operator: write `math.pow(x, 2)`. A call that remembers earlier bars (`tech.*`, `data.series`) on the right of `and`, `or`, `??` or in a branch of `if ... then ... else` runs only where it is reached, and the checker warns (`W3303`): give it a line of its own to run it on every bar. See [Lazy operators](https://millionchart.com/wiki/scripting/language/lazy-operators).

### Choices and loops

| Write | Does |
|---|---|
| `if cond` with an indented block, `else` | runs the block when the condition is true |
| `let v = if cond then a else b` | chooses a value |
| `match x` then `"a" => 1` lines and `_ => 0` | chooses by value; `match` with no subject chooses by condition |
| `for i in 0 to 3` | 0, 1, 2, 3 (`until 3` leaves 3 out; `by 2` sets the step) |
| `for x in items`, `for (i, x) in items` | each item of an array, with its position |
| `while cond` | repeats while the condition holds |
| `break`, `continue` | leave the loop; go to its next pass |

A loop keeps one state per pass of the bar for a call that remembers earlier bars; only a read of another timeframe may not stand in a loop (`E3301`). See [Choices and loops](https://millionchart.com/wiki/scripting/language/control-flow).

### Functions, types and enums

| Write | Means |
|---|---|
| `fn mid(a: float, b: float): float = (a + b) / 2` | a one-line function |
| `fn f(x: float)` with an indented block and `return` | a function with a block |
| `fn scaled(x: float, k: float = 2.0): float` | a parameter with a default; call with `scaled(close, k = 0.5)` |
| `let (a, b) = pair()` | take a tuple apart (`_` skips a value) |
| `type Band` with indented fields `upper: float` | a record; build it with `Band(upper = 1.0, lower = 0.0)` |
| `fn Band.width(self): float = self.upper - self.lower` | a method, called as `b.width()` |
| `enum Mode` with indented `fast = "Fast"` | a closed list of names |
| `import Me/Name@1 as alias` | one of your own modules |

A function may call itself (a chain deeper than the limit is `E-LIMIT-DEPTH`). See [Functions, types and enums](https://millionchart.com/wiki/scripting/language/functions), [Modules and libraries](https://millionchart.com/wiki/scripting/chart/libraries).

### Text and formats

| Write | Gives |
|---|---|
| `f"Close {close:price}"` | the close with the symbol's own decimals |
| `{x:.2f}`, `{x:,.2f}`, `{x:+.1f}` | two decimals; with thousands; with a sign |
| `{x:.1%}`, `{x:03}` | a percentage; padded with zeros |
| `{x:.1f?'n/a'}` | `n/a` while `x` is `na` |
| `text.fmt(x, ".2f")`, `text.length(s)`, `text.split(s, ",")` | text functions |

See [Text and number formatting](https://millionchart.com/wiki/scripting/language/text).

### Drawing on the chart

| Write | Draws |
|---|---|
| `plot(x, name = "A", color = color.blue, width = 2, style = histogram)` | a series on every bar |
| `level(70, name = "Top", style = dashed)` | a horizontal line |
| `shade(top, bottom, color = color.fade(color.purple, 90))` | the space between two plots or levels kept in names |
| `mark.shape(cond, shape = triangle_up, place = below)` | a shape where a condition is true |
| `mark.char(cond, char = "x", place = above)`, `mark.arrow(x)` | a character; an arrow up or down by the sign |
| `chart.background(if cond then color.fade(color.green, 90) else na)` | the background of a bar |
| `chart.candles(color)` | recolours the chart's candles |
| `label.new(bar.index, high, "text")`, `line.new(x1, y1, x2, y2)`, `box.new(left, top, right, bottom)` | drawings placed by bar and price |
| `table.new(top_right, 2, 2)`, `table.cell(t, 0, 0, "A")` | a table in a corner |
| `log.info("close {0}", close)` | a line in the script's log |

Plot styles: `line`, `line_break`, `step`, `step_break`, `step_diamond`, `histogram`, `columns`, `area`, `area_break`, `circles`, `cross`. See [Plots and drawings](https://millionchart.com/wiki/scripting/chart/plots-and-drawings), [Tables](https://millionchart.com/wiki/scripting/chart/tables).

### Time and other timeframes

| Write | Gives |
|---|---|
| `bar.index`, `bar.time`, `bar.is_last` | the bar's number, its time, true on the newest bar |
| `data.series("240", tech.ema(close, 20), symbol = symbol.id)` | an expression on another timeframe, last closed bar |
| `prior(day).high`, `current(week).open` | yesterday's high; this week's open (intraday charts) |
| `session london = 08:00 .. 16:30 @ "Europe/London"` | a named session: `london.active`, `.start`, `.end`, `.high`, `.low` |
| `clock.hour_of(bar.time, zone = "UTC")` | the hour of a time in a zone |

See [Other timeframes and symbols](https://millionchart.com/wiki/scripting/chart/other-timeframes), [Trading day and sessions](https://millionchart.com/wiki/scripting/chart/time-and-sessions).

### Common built-ins

| Group | Some of its names |
|---|---|
| prices | `open` `high` `low` `close` `volume` `hl2` `hlc3` `ohlc4` |
| `tech` | `tech.sma` `tech.ema` `tech.rma` `tech.rsi` `tech.atr` `tech.stdev` `tech.highest` `tech.lowest` `tech.crosses_above` `tech.crosses_below` `tech.pivot_high` `tech.macd` |
| `math` | `math.abs` `math.max` `math.min` `math.round` `math.floor` `math.sqrt` `math.pow` `math.sign` |
| `symbol` | `symbol.id` `symbol.tick` `symbol.pip` |
| `color` | `color.rgb` `color.fade` `color.gradient` and the named colours |

The [Function index](https://millionchart.com/wiki/scripting/reference/function-index) lists every name with its parameters, and the [Function reference](https://millionchart.com/wiki/scripting/reference/api) explains each one.

### Strategies

| Write | Does |
|---|---|
| `orders.enter("Long", side.long)` | opens a simulated long trade with the key "Long" (`side.short` for a short) |
| `orders.close("Long")` | closes it |
| `orders.exit("Exit", "Long", stop = s, limit = t)` | a stop and a target for the trade "Long" |
| `orders.cancel("Key")`, `orders.close_all()` | cancels an order; closes everything |
| `position.size`, `position.avg_price` | the open size (positive for a long); its price |
| `setup:` with `capital`, `size = sizing.lots(0.1)`, `fees = fee.per_lot(3.5)` | money, size and commission |
| `execution:` with `spread = 20 ticks`, `slippage = 2 ticks` | the costs of a fill |

```script
// A strategy: orders with a key, a stop and a target, size and costs in the header.
strategy "Cheat sheet strategy"
    edition = 1
    display = price

setup:
    capital = 10000
    size = sizing.lots(0.1)
    fees = fee.per_lot(3.5)

execution:
    spread = 20 ticks
    slippage = 2 ticks

let fast = tech.ema(close, 10)
let slow = tech.ema(close, 30)
if tech.crosses_above(fast, slow)
    orders.enter("Long", side.long)
if position.size > 0
    orders.exit("Exit", "Long", stop = position.avg_price * 0.99, limit = position.avg_price * 1.02)
if tech.crosses_below(fast, slow)
    orders.close("Long")
plot(fast, name = "Fast", color = color.green)
plot(slow, name = "Slow", color = color.red)
```

See [Your first strategy](https://millionchart.com/wiki/scripting/tutorial/first-strategy), [Strategies and the header](https://millionchart.com/wiki/scripting/chart/strategies).

## What is not available yet

This page collects in one place what members cannot do with scripts in this release. Where a script tries, the engine refuses it with an error, so a script never runs with a meaning it was not written for. Every item below was checked against the engine that runs on the chart.

### Things the platform does not offer yet

| What | What happens | What to do instead |
|---|---|---|
| Sharing a script with another member | There is no way to share; every script is private to your account | Copy the text yourself if you want to keep it elsewhere |
| Libraries supplied by the platform | Only modules you saved yourself can be imported | Write the module yourself ([Lesson 12](https://millionchart.com/wiki/scripting/tutorial/modules)) |
| Data of another symbol | Refused: `E-REQ-UNDECLARED` without a `uses` line, `E4001` with one | Read your chart's own symbol (`symbol = symbol.id`) |
| A panel or a scan of several symbols | Not available | One symbol per chart; use the chart grid to watch several |
| Showing the log in the editor | `log.info`, `log.warning` and `log.error` are accepted and kept by the engine, but no panel lists them | Draw the value: [Lesson 13](https://millionchart.com/wiki/scripting/tutorial/debugging) |

### Words of the language reserved for a later edition

These are written into the language now and refused, so that a script written for them cannot run with the wrong meaning. The message says the word is reserved (`E9002`):

- the inputs `preset`, `bind` and `secret`;
- the blocks `on close` and `on tick`;
- the `report` statement and the `bracket` order statement.

```script-error E9002
indicator "A reserved input"
    edition = 1

preset p
plot(close)
```

The names `account.*` and `contract.*` are reserved in the same way (`E9001`):

```script-error E9001
indicator "Account values"
    edition = 1

plot(account.equity)
```

`funding` and `hedge` are not settings of a strategy's header; writing them is `E3130`.

### Forms that are not part of the language

These are simply not known. Write the form on the right:

| Not known | Code | Write instead |
|---|---|---|
| An item of a list as `items[i]` | `E3173` | `items.at(i)` (`items[1]` reads the list as it was one bar back) |
| Selectors on lists such as `.where(...)` and `.count(...)` | `E5140` | a `for` loop over the items |
| `pips(x)`, `to_ticks(d)` | `E3160` | multiply by `symbol.pip`, divide by `symbol.tick` |
| A cooldown or an expiry written `3 bars` | `E2002` | the number: `cooldown = 3` |
| `json(...)` to build an alert message | `E3160` | build the text yourself with `f"..."` |
| A function without a name (`fn(x) => ...` as a value) | `E2006` | declare a named function with `fn` |
| `nz(x)` | `E3160` | `x ?? 0` |

```script-error E3160
indicator "A helper that does not exist"
    edition = 1

plot(pips(10))
```

### What works, with limits

Some things are available but bounded; they are not missing:

- Your plan decides how many scripts you can keep: 2 on the free chart plan, up to 100 on MillionChart Pro.
- Alerts on your own scripts need MillionChart Pro or a higher plan; up to 10 run at a time.
- A script can read other timeframes of its own symbol, up to 40 of them ([Lesson 10](https://millionchart.com/wiki/scripting/tutorial/other-data)).
- The engine bounds work, history, memory and drawings ([Lesson 17](https://millionchart.com/wiki/scripting/tutorial/performance), [Limits and budgets](https://millionchart.com/wiki/scripting/reference/limits)).

See also: [Limits and budgets](https://millionchart.com/wiki/scripting/reference/limits), [Diagnostics](https://millionchart.com/wiki/scripting/reference/diagnostics).

## Alerts reference

Raise an alert at once, or declare a condition the settings panel lists. Alerts are limited per bar and per run. Alerts on your own scripts come with MillionChart Pro and higher plans; on other plans a script with these calls still compiles and runs.

### Functions

#### alert.send

**`alert.send([message], [key], [once], [cooldown])`**

Raises an alert with `message` on the current bar. `once` and `cooldown` limit how often the same alert may fire.

- **Effects:** can raise an alert; builds a new value whose size follows its arguments (counted in the memory ledger).
- **Phase:** every bar.
- **Cost:** allocates: the memory ledger counts what it builds; counts against the alerts allowed per bar and per run.

#### alert.when

**`alert.when([condition], [name], [message], [on], [key], [was])`**

Declares an alert condition: the alert fires on the bars where `condition` is true, and appears in the settings under its `name`.

- **Effects:** can raise an alert.
- **Phase:** every bar.
- **Cost:** counts against the alerts allowed per bar and per run.
- **Examples:** [Cross alert](https://millionchart.com/wiki/scripting/examples/orders-and-alerts#cross-alert).

## Arrays reference

An array is an ordered list of values of one kind. Many functions here are written as methods: `a.push(x)` is `array.push(a, x)`.

### Functions

#### array.abs

**`array.abs([array])`**

A new array with the absolute value of each element.

- **Effects:** builds a new value whose size follows its arguments (counted in the memory ledger).
- **Phase:** every bar.
- **Cost:** allocates: the memory ledger counts what it builds.
- **Returns:** an array.

#### array.all

**`array.all([array])`**

True when the array is not empty and every element is true.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.
- **Returns:** true or false.

#### array.any

**`array.any([array])`**

True when at least one element is true.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.
- **Returns:** true or false.

#### array.at

**`array.at(array, index)`**

The element at an index.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.
- **Examples:** [Guarded read](https://millionchart.com/wiki/scripting/examples/lazy-operators#guarded-read), [Read past the end of an array](https://millionchart.com/wiki/scripting/examples/lazy-operators#read-past-the-end-of-an-array).

#### array.avg

**`array.avg([array])`**

A statistic of the elements.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.

#### array.binary_search

**`array.binary_search([array], [value])`**

The index of a value in a sorted array, or -1 when the value is not there.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.
- **Returns:** a whole number.

#### array.binary_search_leftmost

**`array.binary_search_leftmost([array], [value])`**

The index of the first element equal to the value in a sorted array; when none is equal, the index of the element just below where the value would sit.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.
- **Returns:** a whole number.

#### array.binary_search_rightmost

**`array.binary_search_rightmost([array], [value])`**

The index of the last element equal to the value in a sorted array; when none is equal, the index of the element just above where the value would sit.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.
- **Returns:** a whole number.

#### array.clear

**`array.clear(array)`**

Removes every element.

- **Effects:** changes a collection in place.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.

#### array.concat

**`array.concat([array], [other])`**

Appends the elements of another array to the array and returns it.

- **Effects:** changes a collection in place; builds a new value whose size follows its arguments (counted in the memory ledger).
- **Phase:** every bar.
- **Cost:** allocates: the memory ledger counts what it builds.
- **Returns:** the array.

#### array.contains

**`array.contains([array], [value])`**

True when the array holds the value.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.

#### array.copy

**`array.copy([array])`**

A copy of the array.

- **Effects:** builds a new value whose size follows its arguments (counted in the memory ledger).
- **Phase:** every bar.
- **Cost:** allocates: the memory ledger counts what it builds.

#### array.covariance

**`array.covariance([array], [other], [biased])`**

The covariance of two arrays of the same size; pairs that hold na are skipped, and `biased` divides by the count instead of the count minus one.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.
- **Returns:** a number.

#### array.fill

**`array.fill([array], [value], [from], [to])`**

Sets the elements from index `from` up to, not including, `to` to one value; without a range it fills the whole array.

- **Effects:** changes a collection in place.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.

#### array.first

**`array.first([array])`**

The first or last element.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.

#### array.index_of

**`array.index_of([array], [value])`**

The index of the first or last element equal to the value, or -1.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.

#### array.insert

**`array.insert([array], [index], [value])`**

Inserts a value at an index.

- **Effects:** changes a collection in place; builds a new value whose size follows its arguments (counted in the memory ledger).
- **Phase:** every bar.
- **Cost:** allocates: the memory ledger counts what it builds.

#### array.join

**`array.join([array], [separator])`**

The elements as one text, with `separator` between.

- **Effects:** builds a new value whose size follows its arguments (counted in the memory ledger).
- **Phase:** every bar.
- **Cost:** allocates: the memory ledger counts what it builds.

#### array.last

**`array.last([array])`**

The first or last element.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.
- **Examples:** [Guarded read](https://millionchart.com/wiki/scripting/examples/lazy-operators#guarded-read), [Read past the end of an array](https://millionchart.com/wiki/scripting/examples/lazy-operators#read-past-the-end-of-an-array).

#### array.last_index_of

**`array.last_index_of([array], [value])`**

The index of the first or last element equal to the value, or -1.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.

#### array.max

**`array.max([array], [nth])`**

A statistic of the elements.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.
- **Examples:** [Rolling median band](https://millionchart.com/wiki/scripting/examples/collections#rolling-median-band), [Array read with brackets](https://millionchart.com/wiki/scripting/examples/collections#array-read-with-brackets).

#### array.median

**`array.median([array])`**

A statistic of the elements.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.
- **Examples:** [Rolling median band](https://millionchart.com/wiki/scripting/examples/collections#rolling-median-band).

#### array.min

**`array.min([array], [nth])`**

A statistic of the elements.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.
- **Examples:** [Rolling median band](https://millionchart.com/wiki/scripting/examples/collections#rolling-median-band), [Array read with brackets](https://millionchart.com/wiki/scripting/examples/collections#array-read-with-brackets).

#### array.mode

**`array.mode([array])`**

A statistic of the elements.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.

#### array.new

**`array.new([size], [initial])`**

Makes an array of `size` elements, each `initial`.

- **Effects:** builds a new value whose size follows its arguments (counted in the memory ledger).
- **Phase:** every bar.
- **Cost:** allocates: the memory ledger counts what it builds.

#### array.percent_rank

**`array.percent_rank([array], [index])`**

The percentage of the elements that are less than or equal to the element at `index`.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.
- **Returns:** a number from 0 to 100.

#### array.percentile

**`array.percentile([array], [percent])`**

The value at a percentage of the sorted elements, interpolated between the two closest ranks.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.
- **Returns:** a number.
- **Examples:** [Rolling median band](https://millionchart.com/wiki/scripting/examples/collections#rolling-median-band), [Array read with brackets](https://millionchart.com/wiki/scripting/examples/collections#array-read-with-brackets).

#### array.percentile_nearest

**`array.percentile_nearest([array], [percent])`**

The value at a percentage of the sorted elements, taken at the nearest rank.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.
- **Returns:** a number.

#### array.pop

**`array.pop(array)`**

Removes and gives the last element.

- **Effects:** changes a collection in place.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.

#### array.push

**`array.push(array, value)`**

Adds a value at the end.

- **Effects:** changes a collection in place; builds a new value whose size follows its arguments (counted in the memory ledger).
- **Phase:** every bar.
- **Cost:** allocates: the memory ledger counts what it builds.
- **Examples:** [Rolling median band](https://millionchart.com/wiki/scripting/examples/collections#rolling-median-band), [Swing high path](https://millionchart.com/wiki/scripting/examples/drawing#swing-high-path), [Guarded read](https://millionchart.com/wiki/scripting/examples/lazy-operators#guarded-read), [Array read with brackets](https://millionchart.com/wiki/scripting/examples/collections#array-read-with-brackets).

#### array.range

**`array.range([array])`**

A statistic of the elements.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.

#### array.remove

**`array.remove(array, index)`**

Removes and gives the element at an index.

- **Effects:** changes a collection in place.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.

#### array.reverse

**`array.reverse([array])`**

Reverses the order in place.

- **Effects:** changes a collection in place.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.

#### array.set

**`array.set(array, index, value)`**

Sets the element at an index.

- **Effects:** changes a collection in place.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.

#### array.shift

**`array.shift([array])`**

Removes and gives the first element.

- **Effects:** changes a collection in place.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.
- **Examples:** [Rolling median band](https://millionchart.com/wiki/scripting/examples/collections#rolling-median-band), [Swing high path](https://millionchart.com/wiki/scripting/examples/drawing#swing-high-path), [Array read with brackets](https://millionchart.com/wiki/scripting/examples/collections#array-read-with-brackets).

#### array.size

**`array.size(array)`**

The number of elements.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.
- **Examples:** [Rolling median band](https://millionchart.com/wiki/scripting/examples/collections#rolling-median-band), [Swing high path](https://millionchart.com/wiki/scripting/examples/drawing#swing-high-path), [Guarded read](https://millionchart.com/wiki/scripting/examples/lazy-operators#guarded-read), [Array read with brackets](https://millionchart.com/wiki/scripting/examples/collections#array-read-with-brackets).

#### array.slice

**`array.slice([array], [from], [to])`**

A copy of part of the array.

- **Effects:** builds a new value whose size follows its arguments (counted in the memory ledger).
- **Phase:** every bar.
- **Cost:** allocates: the memory ledger counts what it builds.

#### array.sort

**`array.sort([array], [order])`**

Sorts the array in place, ascending or descending.

- **Effects:** changes a collection in place.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.

#### array.sort_indices

**`array.sort_indices([array], [order])`**

A new array with the indexes that would put the elements in order, ascending or descending.

- **Effects:** builds a new value whose size follows its arguments (counted in the memory ledger).
- **Phase:** every bar.
- **Cost:** allocates: the memory ledger counts what it builds.
- **Returns:** an array of whole numbers.

#### array.standardize

**`array.standardize([array])`**

A new array with each element as a z-score: its distance from the mean in standard deviations.

- **Effects:** builds a new value whose size follows its arguments (counted in the memory ledger).
- **Phase:** every bar.
- **Cost:** allocates: the memory ledger counts what it builds.
- **Returns:** an array of numbers.

#### array.stdev

**`array.stdev([array], [biased])`**

A statistic of the elements.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.

#### array.sum

**`array.sum([array])`**

A statistic of the elements.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.

#### array.unshift

**`array.unshift([array], [value])`**

Adds a value at the start.

- **Effects:** changes a collection in place; builds a new value whose size follows its arguments (counted in the memory ledger).
- **Phase:** every bar.
- **Cost:** allocates: the memory ledger counts what it builds.

#### array.variance

**`array.variance([array], [biased])`**

A statistic of the elements.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.

## Bar reference

Tests on the time of the current bar against a session, and the values of the bar: its number, its times and where it stands in the history.

### Functions

#### bar.close_time_in

**`bar.close_time_in([tf], [session], [zone], [offset])`**

The time at which the bar (or the period of `tf` it belongs to) closes, when the bar lies inside the session text in the zone; `na` outside it.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.
- **Examples:** [Window of the day](https://millionchart.com/wiki/scripting/examples/time-and-sessions#window-of-the-day).

#### bar.time_in

**`bar.time_in([tf], [session], [zone], [offset])`**

The time at which the bar (or the period of `tf` it belongs to) opens, when the bar lies inside the session text in the zone; `na` outside it.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.
- **Examples:** [Window of the day](https://millionchart.com/wiki/scripting/examples/time-and-sessions#window-of-the-day).

### Values

- `bar.close_time` — The time the bar closes.
- `bar.index` — The number of the bar, counting from 0 at the oldest bar.
- `bar.is_closed` — True when the bar has closed.
- `bar.is_first` — True on the oldest bar.
- `bar.is_first_of_day`
- `bar.is_history` — True on bars of the past.
- `bar.is_last` — True on the newest bar.
- `bar.is_last_history`
- `bar.is_last_of_day`
- `bar.is_live` — True while the newest bar is still forming.
- `bar.last_index`
- `bar.last_time`
- `bar.time` — The time the bar opened.

## Boxes reference

Rectangles drawn on the chart. A box is made with `box.new`, and the other functions read or change it.

### Functions

#### box.copy

**`box.copy([box])`**

Makes a copy.

- **Effects:** draws on the chart or writes an output; builds a new value whose size follows its arguments (counted in the memory ledger).
- **Phase:** every bar.
- **Cost:** allocates: the memory ledger counts what it builds; counts against the limits on drawn objects and outputs.

#### box.delete

**`box.delete([box])`**

Removes the object from the chart.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.

#### box.get_bottom

**`box.get_bottom([box])`**

Reads the bottom of the object.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.

#### box.get_left

**`box.get_left([box])`**

Reads the left of the object.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.

#### box.get_right

**`box.get_right([box])`**

Reads the right of the object.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.

#### box.get_top

**`box.get_top([box])`**

Reads the top of the object.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.

#### box.new

**`box.new(left, top, [right], [bottom], [border_color], [border_width], [border_style], [extend], [x_unit], [background], [text], [text_size], [text_color], [h_align], [v_align], [wrap], [pane], [top_left], [bottom_right], [corner_radius])`**

Draws a rectangle between two corners. `corner_radius` rounds the corners (css pixels, 0 = square, at most 40). `wrap = true` breaks the text into lines inside the box; `h_align`, `v_align` and `text_size` place and size it.

- **Effects:** draws on the chart or writes an output; builds a new value whose size follows its arguments (counted in the memory ledger).
- **Phase:** every bar.
- **Cost:** allocates: the memory ledger counts what it builds; counts against the limits on drawn objects and outputs.
- **Returns:** a box.
- **Examples:** [Recent range drawing](https://millionchart.com/wiki/scripting/examples/drawing#recent-range-drawing), [Session range boxes](https://millionchart.com/wiki/scripting/examples/time-and-sessions#session-range-boxes), [A session read by itself](https://millionchart.com/wiki/scripting/examples/time-and-sessions#a-session-read-by-itself).

#### box.set_background

**`box.set_background([box], [color])`**

Changes the background of the object.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.

#### box.set_border_color

**`box.set_border_color([box], [color])`**

Changes the border color of the object.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.

#### box.set_border_style

**`box.set_border_style([box], [style])`**

Changes the border style of the object.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.

#### box.set_border_width

**`box.set_border_width([box], [width])`**

Changes the border width of the object.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.

#### box.set_bottom

**`box.set_bottom([box], [bottom])`**

Changes the bottom of the object.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.

#### box.set_bottom_right

**`box.set_bottom_right([box], [right], [bottom])`**

Changes the bottom right of the object.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.

#### box.set_bottom_right_point

**`box.set_bottom_right_point([box], [point])`**

Changes the bottom right point of the object.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.

#### box.set_extend

**`box.set_extend([box], [extend])`**

Changes the extend of the object.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.

#### box.set_h_align

**`box.set_h_align([box], [h_align])`**

Changes the h align of the object.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.

#### box.set_left

**`box.set_left([box], [left])`**

Changes the left of the object.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.

#### box.set_right

**`box.set_right([box], [right])`**

Changes the right of the object.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.

#### box.set_text

**`box.set_text([box], [text])`**

Changes the text of the object.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.

#### box.set_text_color

**`box.set_text_color([box], [text_color])`**

Changes the text color of the object.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.

#### box.set_text_size

**`box.set_text_size([box], [text_size])`**

Changes the text size of the object.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.

#### box.set_top

**`box.set_top([box], [top])`**

Changes the top of the object.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.

#### box.set_top_left

**`box.set_top_left([box], [left], [top])`**

Changes the top left of the object.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.

#### box.set_top_left_point

**`box.set_top_left_point([box], [point])`**

Changes the top left point of the object.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.

#### box.set_v_align

**`box.set_v_align([box], [v_align])`**

Changes the v align of the object.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.

#### box.set_x_unit

**`box.set_x_unit([box], [left], [right], [x_unit])`**

Changes the x unit of the object.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.

### Values

- `box.all`

## Chart points reference

A point on the chart, made from a time or a bar index and a price, used by lines, labels, boxes and polylines.

### Functions

#### chart.point.at_index

**`chart.point.at_index([index], [price])`**

A point at a bar index and a price, for the drawings that take points.

- **Effects:** builds a new value whose size follows its arguments (counted in the memory ledger).
- **Phase:** every bar.
- **Cost:** allocates: the memory ledger counts what it builds.
- **Returns:** a point.
- **Examples:** [Swing high path](https://millionchart.com/wiki/scripting/examples/drawing#swing-high-path).

#### chart.point.at_time

**`chart.point.at_time([time], [price])`**

A point at a time and a price, for the drawings that take points.

- **Effects:** builds a new value whose size follows its arguments (counted in the memory ledger).
- **Phase:** every bar.
- **Cost:** allocates: the memory ledger counts what it builds.
- **Returns:** a point.

#### chart.point.copy

**`chart.point.copy([point])`**

Makes a copy.

- **Effects:** builds a new value whose size follows its arguments (counted in the memory ledger).
- **Phase:** every bar.
- **Cost:** allocates: the memory ledger counts what it builds.

#### chart.point.new

**`chart.point.new([time], [index], [price])`**

A point on the chart from a time, a bar index and a price.

- **Effects:** builds a new value whose size follows its arguments (counted in the memory ledger).
- **Phase:** every bar.
- **Cost:** allocates: the memory ledger counts what it builds.

#### chart.point.now

**`chart.point.now([price])`**

A point at the current bar with a price.

- **Effects:** builds a new value whose size follows its arguments (counted in the memory ledger).
- **Phase:** every bar.
- **Cost:** allocates: the memory ledger counts what it builds.

## Chart look reference

Functions that colour the chart itself: its background and its candles.

### Functions

#### chart.background

**`chart.background([color], [offset], [last_bars], [name], [display], [pane], [key], [was])`**

Colours the background of the bars where `color` is not na.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.
- **Examples:** [Trend background](https://millionchart.com/wiki/scripting/examples/drawing#trend-background), [Window of the day](https://millionchart.com/wiki/scripting/examples/time-and-sessions#window-of-the-day).

#### chart.candles

**`chart.candles([color], [offset], [last_bars], [name], [display], [body], [wick], [border])`**

Colours the candles of the chart.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.

### Values

- `chart.theme_background`
- `chart.theme_foreground`

## Clock and calendar reference

Read the parts of a time value in a time zone, and ask whether a time of day has been reached.

### Functions

#### clock.day_of

**`clock.day_of([time], [zone])`**

A part of a time value, read in the zone.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.
- **Returns:** a whole number.

#### clock.hour_of

**`clock.hour_of([time], [zone])`**

A part of a time value, read in the zone.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.
- **Returns:** a whole number.
- **Examples:** [Weekday mornings](https://millionchart.com/wiki/scripting/examples/time-and-sessions#weekday-mornings), [A time with no zone](https://millionchart.com/wiki/scripting/examples/time-and-sessions#a-time-with-no-zone).

#### clock.minute_of

**`clock.minute_of([time], [zone])`**

A part of a time value, read in the zone.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.
- **Returns:** a whole number.

#### clock.month_of

**`clock.month_of([time], [zone])`**

A part of a time value, read in the zone.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.
- **Returns:** a whole number.

#### clock.reached

**`clock.reached([time], [zone])`**

True on the first bar of each date whose close is at or after the time of day, in the zone.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.

#### clock.second_of

**`clock.second_of([time], [zone])`**

A part of a time value, read in the zone.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.
- **Returns:** a whole number.

#### clock.timestamp

**`clock.timestamp([year], [month], [day], [hour], [minute], [second], [zone])`**

The time of a calendar moment, in the zone, as a time value.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.
- **Examples:** [Weekday mornings](https://millionchart.com/wiki/scripting/examples/time-and-sessions#weekday-mornings), [A time with no zone](https://millionchart.com/wiki/scripting/examples/time-and-sessions#a-time-with-no-zone).

#### clock.week_of

**`clock.week_of([time], [zone])`**

A part of a time value, read in the zone.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.
- **Returns:** a whole number.

#### clock.weekday_of

**`clock.weekday_of([time], [zone])`**

A part of a time value, read in the zone.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.
- **Returns:** a whole number.
- **Examples:** [Weekday mornings](https://millionchart.com/wiki/scripting/examples/time-and-sessions#weekday-mornings), [Volume by weekday](https://millionchart.com/wiki/scripting/examples/collections#volume-by-weekday), [A time with no zone](https://millionchart.com/wiki/scripting/examples/time-and-sessions#a-time-with-no-zone).

#### clock.year_of

**`clock.year_of([time], [zone])`**

A part of a time value, read in the zone.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.
- **Returns:** a whole number.

### Values

- `clock.day`
- `clock.friday`
- `clock.hour`
- `clock.minute`
- `clock.monday`
- `clock.month`
- `clock.now`
- `clock.saturday`
- `clock.second`
- `clock.sunday`
- `clock.thursday`
- `clock.tuesday`
- `clock.wednesday`
- `clock.week`
- `clock.weekday`
- `clock.year`

## Colours reference

Make a colour from parts, fade it, or take it apart.

### Functions

#### color.blue_of

**`color.blue_of([color])`**

The red, green or blue part of a colour.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.

#### color.fade

**`color.fade(color, [percent])`**

Makes a colour more transparent by `percent`.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.
- **Examples:** [RSI zones](https://millionchart.com/wiki/scripting/examples/drawing#rsi-zones), [Bollinger bands](https://millionchart.com/wiki/scripting/examples/tech-indicators#bollinger-bands), [Status table](https://millionchart.com/wiki/scripting/examples/drawing#status-table), [Recent range drawing](https://millionchart.com/wiki/scripting/examples/drawing#recent-range-drawing).

#### color.fade_of

**`color.fade_of([color])`**

The transparency of a colour, in percent.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.

#### color.gradient

**`color.gradient([value], [min], [max], [min_color], [max_color])`**

A colour between two colours, by where `value` lies between `min` and `max`.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.

#### color.green_of

**`color.green_of([color])`**

The red, green or blue part of a colour.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.

#### color.red_of

**`color.red_of([color])`**

The red, green or blue part of a colour.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.

#### color.rgb

**`color.rgb(red, green, blue, [fade])`**

A colour from its red, green and blue parts.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.

### Values

- `color.aqua`
- `color.black`
- `color.blue`
- `color.fuchsia`
- `color.gray`
- `color.green`
- `color.lime`
- `color.maroon`
- `color.navy`
- `color.olive`
- `color.orange`
- `color.purple`
- `color.red`
- `color.silver`
- `color.teal`
- `color.white`
- `color.yellow`

## Core reference

The functions every script uses without a prefix: drawing a plot or a level, shading, testing for na and converting a value. The prices of the bar (`open`, `high`, `low`, `close`, `volume`) are values of this page.

### Functions

#### bool

**`bool([value])`**

Converts `x` to true or false.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.

#### confirmed

**`confirmed(value)`**

The value on a closed bar, and na on the bar that is still forming.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.
- **Returns:** a number, or na.

#### falls

**`falls(condition)`**

True on the bar where the condition turns false after being true.

- **Effects:** keeps a state for each place it is written (a call site) and advances it when execution reaches the call.
- **Phase:** every bar.
- **Cost:** one state per call site.
- **Returns:** true or false.

#### float

**`float([value])`**

Converts `x` to a number.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.

#### int

**`int([value])`**

Converts `x` to a whole number, dropping the fraction.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.

#### is_na

**`is_na([value])`**

True when `value` is na.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.
- **Returns:** true or false.
- **Examples:** [Swing pivots](https://millionchart.com/wiki/scripting/examples/drawing#swing-pivots), [Trend background](https://millionchart.com/wiki/scripting/examples/drawing#trend-background), [Window of the day](https://millionchart.com/wiki/scripting/examples/time-and-sessions#window-of-the-day), [Levels from text](https://millionchart.com/wiki/scripting/examples/text-and-logs#levels-from-text).

#### level

**`level(price, [name], [color], [style], [width], [display], [key], [was])`**

Draws a horizontal line at a fixed price.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.
- **Returns:** a handle to the level, for `shade`.
- **Examples:** [RSI zones](https://millionchart.com/wiki/scripting/examples/drawing#rsi-zones), [RSI written out](https://millionchart.com/wiki/scripting/examples/series-and-bars#rsi-written-out), [Stochastic oscillator](https://millionchart.com/wiki/scripting/examples/tech-indicators#stochastic-oscillator), [ADX with directional indicators](https://millionchart.com/wiki/scripting/examples/tech-indicators#adx-with-directional-indicators).

#### plot

**`plot(source, [name], [color], [width], [style], [track_price], [base], [offset], [join], [last_bars], [display], [format], [precision], [pane], [key], [was])`**

Draws `source` on every bar as a line, or in the style you choose.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.
- **Returns:** a handle to the plot, for `shade`.
- **Examples:** [Simple moving average](https://millionchart.com/wiki/scripting/examples/start#simple-moving-average), [EMA pair with cross marks](https://millionchart.com/wiki/scripting/examples/series-and-bars#ema-pair-with-cross-marks), [RSI written out](https://millionchart.com/wiki/scripting/examples/series-and-bars#rsi-written-out), [RSI zones](https://millionchart.com/wiki/scripting/examples/drawing#rsi-zones).

#### plot_bars

**`plot_bars([open], [high], [low], [close], [name], [color], [last_bars], [display], [format], [precision], [pane], [key], [was])`**

Draws bars from four series.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.

#### plot_candles

**`plot_candles([open], [high], [low], [close], [name], [color], [wick_color], [last_bars], [border_color], [display], [format], [precision], [pane], [key], [was])`**

Draws candles from four series.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.

#### rises

**`rises(condition)`**

True on the bar where the condition turns true after being false.

- **Effects:** keeps a state for each place it is written (a call site) and advances it when execution reaches the call.
- **Phase:** every bar.
- **Cost:** one state per call site.
- **Returns:** true or false.

#### shade

**`shade(a, b, [color], [name], [last_bars], [fill_gaps], [display], [max], [min], [max_color], [min_color], [key], [was])`**

Colours the space between two plots or levels.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.
- **Examples:** [RSI zones](https://millionchart.com/wiki/scripting/examples/drawing#rsi-zones), [Bollinger bands](https://millionchart.com/wiki/scripting/examples/tech-indicators#bollinger-bands).

### Values

- `ask` — The best asking price of the quote book. A study reads bars, not quotes, so it is na on every bar; a text that branches on it takes the na branch, as it does on history elsewhere.
- `bid` — The best bid of the quote book. na on every bar, like `ask`.
- `close` — The close of the bar.
- `high` — The high of the bar.
- `hl2` — (high + low) / 2
- `hlc3` — (high + low + close) / 3
- `hlcc4` — (high + low + close + close) / 4
- `low` — The low of the bar.
- `ohlc4` — (open + high + low + close) / 4
- `open` — The open of the bar.
- `trading_day`
- `volume` — The volume of the bar.

## Data requests reference

Read another timeframe of the chart's own symbol (reading another symbol is not available in this release). A request keeps a state for each place it is written, so it may not stand in a loop or where it may not run.

### Functions

#### data.intrabars

**`data.intrabars([tf], [expression], [symbol], [allow_missing])`**

Evaluates `expression` on the smaller bars inside each bar of this chart and gives the values as an array (a tuple expression gives a tuple of arrays). The chart loads the newest smaller bars only (about 10000 for a timeframe of 15 minutes or less), so an older chart bar has an empty array; a timeframe in seconds reads the chart's own bar.

- **Effects:** keeps a state for each place it is written (a call site) and advances it when execution reaches the call; reads data the chart did not load for the script; builds a new value whose size follows its arguments (counted in the memory ledger).
- **Phase:** every bar.
- **Cost:** one state per call site; allocates: the memory ledger counts what it builds; one request, counted against the requests a script may make (40).

#### data.series

**`data.series(tf, expression, symbol, [gaps], [future], [allow_missing], [live], [candles])`**

Evaluates `expression` on another timeframe of the chart's own symbol and gives its value on the bars of this chart; naming another symbol stops the script with an error in this release. By default it gives the last closed value, so a bar never shows a value that was not known when it closed.

- **Effects:** keeps a state for each place it is written (a call site) and advances it when execution reaches the call; reads data the chart did not load for the script; builds a new value whose size follows its arguments (counted in the memory ledger).
- **Phase:** every bar.
- **Cost:** one state per call site; allocates: the memory ledger counts what it builds; one request, counted against the requests a script may make (40).
- **Examples:** [Higher timeframe average](https://millionchart.com/wiki/scripting/examples/data-and-requests#higher-timeframe-average).

## Labels reference

Text labels drawn on the chart. A label is made with `label.new`, and the other functions read or change it.

### Functions

#### label.copy

**`label.copy([label])`**

Makes a copy.

- **Effects:** draws on the chart or writes an output; builds a new value whose size follows its arguments (counted in the memory ledger).
- **Phase:** every bar.
- **Cost:** allocates: the memory ledger counts what it builds; counts against the limits on drawn objects and outputs.

#### label.delete

**`label.delete([label])`**

Removes the object from the chart.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.

#### label.get_text

**`label.get_text([label])`**

Reads the text of the object.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.

#### label.get_x

**`label.get_x([label])`**

Reads the x of the object.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.

#### label.get_y

**`label.get_y([label])`**

Reads the y of the object.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.

#### label.new

**`label.new(x, [y], [text], [x_unit], [place], [color], [style], [text_color], [text_size], [text_align], [tooltip], [pane], [point])`**

Draws a text label at a point.

- **Effects:** draws on the chart or writes an output; builds a new value whose size follows its arguments (counted in the memory ledger).
- **Phase:** every bar.
- **Cost:** allocates: the memory ledger counts what it builds; counts against the limits on drawn objects and outputs.
- **Returns:** a label.
- **Examples:** [Swing pivots](https://millionchart.com/wiki/scripting/examples/drawing#swing-pivots), [Recent range drawing](https://millionchart.com/wiki/scripting/examples/drawing#recent-range-drawing), [Window of the day](https://millionchart.com/wiki/scripting/examples/time-and-sessions#window-of-the-day), [Levels from text](https://millionchart.com/wiki/scripting/examples/text-and-logs#levels-from-text).

#### label.set_color

**`label.set_color([label], [color])`**

Changes the color of the object.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.

#### label.set_place

**`label.set_place([label], [place])`**

Changes the place of the object.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.

#### label.set_point

**`label.set_point([label], [point])`**

Changes the point of the object.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.

#### label.set_style

**`label.set_style([label], [style])`**

Changes the style of the object.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.

#### label.set_text

**`label.set_text([label], [text])`**

Changes the text of the object.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.

#### label.set_text_align

**`label.set_text_align([label], [text_align])`**

Changes the text align of the object.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.

#### label.set_text_color

**`label.set_text_color([label], [text_color])`**

Changes the text color of the object.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.

#### label.set_text_size

**`label.set_text_size([label], [size])`**

Changes the text size of the object.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.

#### label.set_tooltip

**`label.set_tooltip([label], [tooltip])`**

Changes the tooltip of the object.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.

#### label.set_x

**`label.set_x([label], [x])`**

Changes the x of the object.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.

#### label.set_x_unit

**`label.set_x_unit([label], [x], [x_unit])`**

Changes the x unit of the object.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.

#### label.set_xy

**`label.set_xy([label], [x], [y])`**

Changes the xy of the object.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.

#### label.set_y

**`label.set_y([label], [y])`**

Changes the y of the object.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.

### Values

- `label.all`

## Lines reference

Lines drawn between two points on the chart. A line is made with `line.new`, and the other functions read or change it.

### Functions

#### line.copy

**`line.copy([line])`**

Makes a copy.

- **Effects:** draws on the chart or writes an output; builds a new value whose size follows its arguments (counted in the memory ledger).
- **Phase:** every bar.
- **Cost:** allocates: the memory ledger counts what it builds; counts against the limits on drawn objects and outputs.

#### line.delete

**`line.delete([line])`**

Removes the object from the chart.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.

#### line.get_price

**`line.get_price([line], [x])`**

Reads the price of the object.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.

#### line.get_x1

**`line.get_x1([line])`**

Reads the x1 of the object.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.

#### line.get_x2

**`line.get_x2([line])`**

Reads the x2 of the object.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.

#### line.get_y1

**`line.get_y1([line])`**

Reads the y1 of the object.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.

#### line.get_y2

**`line.get_y2([line])`**

Reads the y2 of the object.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.

#### line.new

**`line.new(x1, y1, [x2], [y2], [x_unit], [extend], [color], [style], [width], [pane], [first_point], [second_point])`**

Draws a line between two points and gives a handle to change or delete it.

- **Effects:** draws on the chart or writes an output; builds a new value whose size follows its arguments (counted in the memory ledger).
- **Phase:** every bar.
- **Cost:** allocates: the memory ledger counts what it builds; counts against the limits on drawn objects and outputs.
- **Returns:** a line.
- **Examples:** [Recent range drawing](https://millionchart.com/wiki/scripting/examples/drawing#recent-range-drawing), [Levels from text](https://millionchart.com/wiki/scripting/examples/text-and-logs#levels-from-text).

#### line.set_color

**`line.set_color([line], [color])`**

Changes the color of the object.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.

#### line.set_extend

**`line.set_extend([line], [extend])`**

Changes the extend of the object.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.

#### line.set_first_point

**`line.set_first_point([line], [point])`**

Changes the first point of the object.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.

#### line.set_second_point

**`line.set_second_point([line], [point])`**

Changes the second point of the object.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.

#### line.set_style

**`line.set_style([line], [style])`**

Changes the style of the object.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.

#### line.set_width

**`line.set_width([line], [width])`**

Changes the width of the object.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.

#### line.set_x1

**`line.set_x1([line], [x])`**

Changes the x1 of the object.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.

#### line.set_x2

**`line.set_x2([line], [x])`**

Changes the x2 of the object.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.

#### line.set_x_unit

**`line.set_x_unit([line], [x1], [x2], [x_unit])`**

Changes the x unit of the object.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.

#### line.set_xy1

**`line.set_xy1([line], [x], [y])`**

Changes the xy1 of the object.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.

#### line.set_xy2

**`line.set_xy2([line], [x], [y])`**

Changes the xy2 of the object.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.

#### line.set_y1

**`line.set_y1([line], [y])`**

Changes the y1 of the object.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.

#### line.set_y2

**`line.set_y2([line], [y])`**

Changes the y2 of the object.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.

### Values

- `line.all`

## Log reference

Write lines to the script's log, or stop the run with a message.

### Functions

#### log.abort

**`log.abort([message])`**

Stops the run with this message.

- **Effects:** can raise an alert.
- **Phase:** every bar.
- **Cost:** counts against the alerts allowed per bar and per run.
- **Examples:** [Logged crossings](https://millionchart.com/wiki/scripting/examples/text-and-logs#logged-crossings), [Stopped on purpose](https://millionchart.com/wiki/scripting/examples/text-and-logs#stopped-on-purpose).

#### log.error

**`log.error([message], ...values)`**

Writes an error line to the script's log.

- **Effects:** draws on the chart or writes an output; builds a new value whose size follows its arguments (counted in the memory ledger).
- **Phase:** every bar.
- **Cost:** allocates: the memory ledger counts what it builds; counts against the limits on drawn objects and outputs.
- **Examples:** [Logged crossings](https://millionchart.com/wiki/scripting/examples/text-and-logs#logged-crossings), [Stopped on purpose](https://millionchart.com/wiki/scripting/examples/text-and-logs#stopped-on-purpose).

#### log.info

**`log.info([message], ...values)`**

Writes a line to the script's log. The text may hold `{0}`, `{1}` for the values after it.

- **Effects:** draws on the chart or writes an output; builds a new value whose size follows its arguments (counted in the memory ledger).
- **Phase:** every bar.
- **Cost:** allocates: the memory ledger counts what it builds; counts against the limits on drawn objects and outputs.
- **Examples:** [Logged crossings](https://millionchart.com/wiki/scripting/examples/text-and-logs#logged-crossings), [Stopped on purpose](https://millionchart.com/wiki/scripting/examples/text-and-logs#stopped-on-purpose).

#### log.warning

**`log.warning([message], ...values)`**

Writes a warning line to the script's log.

- **Effects:** draws on the chart or writes an output; builds a new value whose size follows its arguments (counted in the memory ledger).
- **Phase:** every bar.
- **Cost:** allocates: the memory ledger counts what it builds; counts against the limits on drawn objects and outputs.
- **Examples:** [Logged crossings](https://millionchart.com/wiki/scripting/examples/text-and-logs#logged-crossings), [Stopped on purpose](https://millionchart.com/wiki/scripting/examples/text-and-logs#stopped-on-purpose).

## Maps reference

A map holds values under keys. Many functions here are written as methods: `m.set(k, v)` is `map.set(m, k, v)`.

### Functions

#### map.at

**`map.at([map], [key])`**

The value under a key.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.
- **Examples:** [Volume by weekday](https://millionchart.com/wiki/scripting/examples/collections#volume-by-weekday).

#### map.clear

**`map.clear([map])`**

Removes every entry.

- **Effects:** changes a collection in place.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.

#### map.contains

**`map.contains([map], [key])`**

True when the key is in the map.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.

#### map.copy

**`map.copy([map])`**

A copy of the map.

- **Effects:** builds a new value whose size follows its arguments (counted in the memory ledger).
- **Phase:** every bar.
- **Cost:** allocates: the memory ledger counts what it builds.

#### map.keys

**`map.keys([map])`**

The keys or the values as an array.

- **Effects:** builds a new value whose size follows its arguments (counted in the memory ledger).
- **Phase:** every bar.
- **Cost:** allocates: the memory ledger counts what it builds.
- **Examples:** [Volume by weekday](https://millionchart.com/wiki/scripting/examples/collections#volume-by-weekday).

#### map.new

**`map.new()`**

Makes an empty map.

- **Effects:** builds a new value whose size follows its arguments (counted in the memory ledger).
- **Phase:** every bar.
- **Cost:** allocates: the memory ledger counts what it builds.

#### map.remove

**`map.remove([map], [key])`**

Removes the key.

- **Effects:** changes a collection in place.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.

#### map.set

**`map.set([map], [key], [value])`**

Sets the value under a key.

- **Effects:** changes a collection in place; builds a new value whose size follows its arguments (counted in the memory ledger).
- **Phase:** every bar.
- **Cost:** allocates: the memory ledger counts what it builds.
- **Examples:** [Volume by weekday](https://millionchart.com/wiki/scripting/examples/collections#volume-by-weekday).

#### map.set_all

**`map.set_all([map], [other])`**

Copies every entry of another map into the map.

- **Effects:** changes a collection in place; builds a new value whose size follows its arguments (counted in the memory ledger).
- **Phase:** every bar.
- **Cost:** allocates: the memory ledger counts what it builds.

#### map.size

**`map.size([map])`**

The number of entries.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.
- **Examples:** [Volume by weekday](https://millionchart.com/wiki/scripting/examples/collections#volume-by-weekday).

#### map.values

**`map.values([map])`**

The keys or the values as an array.

- **Effects:** builds a new value whose size follows its arguments (counted in the memory ledger).
- **Phase:** every bar.
- **Cost:** allocates: the memory ledger counts what it builds.

## Marks reference

Marks drawn on the bars where a condition holds: a shape, a character or an arrow.

### Functions

#### mark.arrow

**`mark.arrow([source], [name], [up_color], [down_color], [offset], [min_height], [max_height], [last_bars], [display], [format], [precision], [pane], [key], [was])`**

Draws an arrow on each bar whose direction and length follow the sign and size of `source`.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.

#### mark.char

**`mark.char([condition], [name], [char], [place], [color], [offset], [text], [text_color], [size], [last_bars], [display], [format], [precision], [pane], [key], [was])`**

Draws a character on each bar where `condition` is true.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.
- **Examples:** [Inside bars](https://millionchart.com/wiki/scripting/examples/series-and-bars#inside-bars).

#### mark.shape

**`mark.shape([condition], [name], [shape], [place], [color], [offset], [text], [text_color], [size], [last_bars], [display], [format], [precision], [pane], [key], [was])`**

Draws a shape on each bar where `condition` is true.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.
- **Examples:** [EMA pair with cross marks](https://millionchart.com/wiki/scripting/examples/series-and-bars#ema-pair-with-cross-marks), [RSI zones](https://millionchart.com/wiki/scripting/examples/drawing#rsi-zones), [Inside bars](https://millionchart.com/wiki/scripting/examples/series-and-bars#inside-bars), [Window of the day](https://millionchart.com/wiki/scripting/examples/time-and-sessions#window-of-the-day).

## Math reference

Arithmetic and elementary functions. The functions that need a transcendental calculation (`math.log`, `math.exp`, `math.pow` and the trigonometric functions) use the deterministic math kernel, so they give the same numbers on every machine.

### Functions

#### math.abs

**`math.abs(value)`**

The absolute value.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.
- **Returns:** a number.
- **Examples:** [User functions](https://millionchart.com/wiki/scripting/examples/language#user-functions), [Lazy operators](https://millionchart.com/wiki/scripting/examples/lazy-operators#lazy-operators).

#### math.acos

**`math.acos([value])`**

A trigonometric function, in radians.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.
- **Returns:** a number.

#### math.asin

**`math.asin([value])`**

A trigonometric function, in radians.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.
- **Returns:** a number.

#### math.atan

**`math.atan([value])`**

A trigonometric function, in radians.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.
- **Returns:** a number.

#### math.avg

**`math.avg(...values)`**

The mean of its arguments.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.
- **Returns:** a number.

#### math.ceil

**`math.ceil(value)`**

The smallest whole number that is not less than the value.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.
- **Returns:** a number.

#### math.cos

**`math.cos(value)`**

A trigonometric function, in radians.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.
- **Returns:** a number.

#### math.exp

**`math.exp(value)`**

e raised to the value.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.
- **Returns:** a number.

#### math.floor

**`math.floor(value)`**

The largest whole number that is not more than the value.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.
- **Returns:** a number.

#### math.log

**`math.log(value)`**

The natural or base-10 logarithm.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.
- **Returns:** a number.

#### math.log10

**`math.log10(value)`**

The natural or base-10 logarithm.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.
- **Returns:** a number.

#### math.max

**`math.max(...values)`**

The smallest or largest of its arguments.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.
- **Returns:** a number.
- **Examples:** [RSI written out](https://millionchart.com/wiki/scripting/examples/series-and-bars#rsi-written-out), [Session highs](https://millionchart.com/wiki/scripting/examples/temporal-calls#session-highs), [Trade tally](https://millionchart.com/wiki/scripting/examples/sizing-and-trades#trade-tally).

#### math.min

**`math.min(...values)`**

The smallest or largest of its arguments.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.
- **Returns:** a number.
- **Examples:** [RSI written out](https://millionchart.com/wiki/scripting/examples/series-and-bars#rsi-written-out).

#### math.pow

**`math.pow(base, exponent)`**

`base` raised to `exponent`.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.
- **Returns:** a number.

#### math.random

**`math.random([min], [max], [seed])`**

A pseudo-random number from `min` to `max`. The same seed and the same call site give the same numbers on every run and every machine.

- **Effects:** keeps a state for each place it is written (a call site) and advances it when execution reaches the call.
- **Phase:** every bar.
- **Cost:** one state per call site.
- **Returns:** a number.
- **Examples:** [Seeded random numbers](https://millionchart.com/wiki/scripting/examples/determinism#seeded-random-numbers).

#### math.rem

**`math.rem(a, b)`**

The remainder of `a` divided by `b`, with the sign of `a`.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.
- **Returns:** a number.

#### math.round

**`math.round(value, [precision])`**

Rounds to the nearest whole number, or to `precision` decimals.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.
- **Returns:** a number.

#### math.sign

**`math.sign(value)`**

-1, 0 or 1 by the sign of the number.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.
- **Returns:** a number.
- **Examples:** [On-balance volume](https://millionchart.com/wiki/scripting/examples/tech-indicators#on-balance-volume).

#### math.sin

**`math.sin(value)`**

A trigonometric function, in radians.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.
- **Returns:** a number.

#### math.sqrt

**`math.sqrt(value)`**

The square root.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.
- **Returns:** a number.

#### math.tan

**`math.tan(value)`**

A trigonometric function, in radians.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.
- **Returns:** a number.

#### math.to_degrees

**`math.to_degrees([value])`**

Converts between radians and degrees.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.
- **Returns:** a number.

#### math.to_radians

**`math.to_radians([value])`**

Converts between radians and degrees.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.
- **Returns:** a number.

### Values

- `math.e`
- `math.phi`
- `math.pi`

## Matrices reference

A matrix is a table of numbers with rows and columns, with the usual linear algebra.

### Functions

#### matrix.add

**`matrix.add([matrix], [other])`**

A new matrix where another matrix of the same size, or a number, is added to every element.

- **Effects:** builds a new value whose size follows its arguments (counted in the memory ledger).
- **Phase:** every bar.
- **Cost:** allocates: the memory ledger counts what it builds.
- **Returns:** a matrix.

#### matrix.add_column

**`matrix.add_column([matrix], [column], [array_id])`**

Inserts a column at an index (at the end without one), filled from an array or with na.

- **Effects:** changes a collection in place; builds a new value whose size follows its arguments (counted in the memory ledger).
- **Phase:** every bar.
- **Cost:** allocates: the memory ledger counts what it builds.

#### matrix.add_row

**`matrix.add_row([matrix], [row], [array_id])`**

Inserts a row at an index (at the end without one), filled from an array or with na.

- **Effects:** changes a collection in place; builds a new value whose size follows its arguments (counted in the memory ledger).
- **Phase:** every bar.
- **Cost:** allocates: the memory ledger counts what it builds.

#### matrix.at

**`matrix.at([matrix], [row], [column])`**

The element at a row and a column.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.
- **Examples:** [Up and down transitions](https://millionchart.com/wiki/scripting/examples/collections#up-and-down-transitions), [Determinant of a matrix that is not square](https://millionchart.com/wiki/scripting/examples/collections#determinant-of-a-matrix-that-is-not-square).

#### matrix.avg

**`matrix.avg([matrix])`**

The average of all elements of the matrix.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.
- **Returns:** a number.

#### matrix.column

**`matrix.column([matrix], [column])`**

A copy of one column as an array.

- **Effects:** builds a new value whose size follows its arguments (counted in the memory ledger).
- **Phase:** every bar.
- **Cost:** allocates: the memory ledger counts what it builds.
- **Returns:** an array.

#### matrix.columns

**`matrix.columns([matrix])`**

The number of rows or columns.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.

#### matrix.concat

**`matrix.concat([matrix], [other])`**

Appends the rows of another matrix below the matrix; both need the same number of columns.

- **Effects:** changes a collection in place; builds a new value whose size follows its arguments (counted in the memory ledger).
- **Phase:** every bar.
- **Cost:** allocates: the memory ledger counts what it builds.
- **Returns:** the matrix.

#### matrix.copy

**`matrix.copy([matrix])`**

Makes a copy.

- **Effects:** builds a new value whose size follows its arguments (counted in the memory ledger).
- **Phase:** every bar.
- **Cost:** allocates: the memory ledger counts what it builds.

#### matrix.count

**`matrix.count([matrix])`**

The number of elements of the matrix: rows times columns.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.
- **Returns:** a whole number.

#### matrix.det

**`matrix.det([matrix])`**

The determinant of a square matrix.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.
- **Examples:** [Determinant of a matrix that is not square](https://millionchart.com/wiki/scripting/examples/collections#determinant-of-a-matrix-that-is-not-square).

#### matrix.eigenvalues

**`matrix.eigenvalues([matrix])`**

The eigenvalues of a square matrix.

- **Effects:** builds a new value whose size follows its arguments (counted in the memory ledger).
- **Phase:** every bar.
- **Cost:** allocates: the memory ledger counts what it builds.
- **Returns:** an array of numbers.

#### matrix.eigenvectors

**`matrix.eigenvectors([matrix])`**

The eigenvectors of a square matrix, one in each column.

- **Effects:** builds a new value whose size follows its arguments (counted in the memory ledger).
- **Phase:** every bar.
- **Cost:** allocates: the memory ledger counts what it builds.
- **Returns:** a matrix.

#### matrix.fill

**`matrix.fill([matrix], [value], [from_row], [to_row], [from_column], [to_column])`**

Sets a block of the matrix to one value; without a block it fills the whole matrix.

- **Effects:** changes a collection in place.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.

#### matrix.inv

**`matrix.inv([matrix])`**

The inverse of a square matrix.

- **Effects:** builds a new value whose size follows its arguments (counted in the memory ledger).
- **Phase:** every bar.
- **Cost:** allocates: the memory ledger counts what it builds.

#### matrix.is_antidiagonal

**`matrix.is_antidiagonal([matrix])`**

True when the matrix is antidiagonal.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.

#### matrix.is_antisymmetric

**`matrix.is_antisymmetric([matrix])`**

True when the matrix is antisymmetric.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.

#### matrix.is_binary

**`matrix.is_binary([matrix])`**

True when the matrix is binary.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.

#### matrix.is_diagonal

**`matrix.is_diagonal([matrix])`**

True when the matrix is diagonal.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.

#### matrix.is_identity

**`matrix.is_identity([matrix])`**

True when the matrix is identity.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.

#### matrix.is_square

**`matrix.is_square([matrix])`**

True when the matrix is square.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.

#### matrix.is_stochastic

**`matrix.is_stochastic([matrix])`**

True when the matrix is stochastic.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.

#### matrix.is_symmetric

**`matrix.is_symmetric([matrix])`**

True when the matrix is symmetric.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.

#### matrix.is_triangular

**`matrix.is_triangular([matrix])`**

True when the matrix is triangular.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.

#### matrix.is_zero

**`matrix.is_zero([matrix])`**

True when the matrix is zero.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.

#### matrix.kron

**`matrix.kron([matrix], [other])`**

The Kronecker product of two matrices.

- **Effects:** builds a new value whose size follows its arguments (counted in the memory ledger).
- **Phase:** every bar.
- **Cost:** allocates: the memory ledger counts what it builds.
- **Returns:** a matrix.

#### matrix.max

**`matrix.max([matrix])`**

The greatest element of the matrix.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.
- **Returns:** a number.

#### matrix.median

**`matrix.median([matrix])`**

The median of all elements of the matrix.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.
- **Returns:** a number.

#### matrix.min

**`matrix.min([matrix])`**

The smallest element of the matrix.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.
- **Returns:** a number.

#### matrix.mode

**`matrix.mode([matrix])`**

The most frequent element of the matrix.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.
- **Returns:** a number.

#### matrix.multiply

**`matrix.multiply([matrix], [other])`**

The product of two matrices, or of a matrix and a number.

- **Effects:** builds a new value whose size follows its arguments (counted in the memory ledger).
- **Phase:** every bar.
- **Cost:** allocates: the memory ledger counts what it builds.

#### matrix.new

**`matrix.new([rows], [columns], [initial])`**

Makes a matrix of `rows` by `columns`, each element `initial`.

- **Effects:** builds a new value whose size follows its arguments (counted in the memory ledger).
- **Phase:** every bar.
- **Cost:** allocates: the memory ledger counts what it builds.

#### matrix.pinv

**`matrix.pinv([matrix])`**

The pseudo-inverse of a matrix.

- **Effects:** builds a new value whose size follows its arguments (counted in the memory ledger).
- **Phase:** every bar.
- **Cost:** allocates: the memory ledger counts what it builds.
- **Returns:** a matrix.

#### matrix.pow

**`matrix.pow([matrix], [exponent])`**

The matrix multiplied by itself `exponent` times; the exponent is a whole number from 0 and the matrix is square.

- **Effects:** builds a new value whose size follows its arguments (counted in the memory ledger).
- **Phase:** every bar.
- **Cost:** allocates: the memory ledger counts what it builds.
- **Returns:** a matrix.

#### matrix.rank

**`matrix.rank([matrix])`**

The rank of the matrix: how many rows are independent of the others.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.
- **Returns:** a whole number.

#### matrix.remove_column

**`matrix.remove_column([matrix], [column])`**

Removes one column.

- **Effects:** changes a collection in place; builds a new value whose size follows its arguments (counted in the memory ledger).
- **Phase:** every bar.
- **Cost:** allocates: the memory ledger counts what it builds.

#### matrix.remove_row

**`matrix.remove_row([matrix], [row])`**

Removes one row.

- **Effects:** changes a collection in place; builds a new value whose size follows its arguments (counted in the memory ledger).
- **Phase:** every bar.
- **Cost:** allocates: the memory ledger counts what it builds.

#### matrix.reshape

**`matrix.reshape([matrix], [rows], [columns])`**

Gives the same elements a new number of rows and columns; the count of elements must not change.

- **Effects:** changes a collection in place.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.

#### matrix.reverse

**`matrix.reverse([matrix])`**

Reverses the order of the elements in the same place.

- **Effects:** changes a collection in place.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.

#### matrix.row

**`matrix.row([matrix], [row])`**

A copy of one row as an array.

- **Effects:** builds a new value whose size follows its arguments (counted in the memory ledger).
- **Phase:** every bar.
- **Cost:** allocates: the memory ledger counts what it builds.
- **Returns:** an array.
- **Examples:** [Up and down transitions](https://millionchart.com/wiki/scripting/examples/collections#up-and-down-transitions), [Determinant of a matrix that is not square](https://millionchart.com/wiki/scripting/examples/collections#determinant-of-a-matrix-that-is-not-square).

#### matrix.rows

**`matrix.rows([matrix])`**

The number of rows or columns.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.

#### matrix.set

**`matrix.set([matrix], [row], [column], [value])`**

Sets the element at a row and a column.

- **Effects:** changes a collection in place.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.
- **Examples:** [Up and down transitions](https://millionchart.com/wiki/scripting/examples/collections#up-and-down-transitions), [Determinant of a matrix that is not square](https://millionchart.com/wiki/scripting/examples/collections#determinant-of-a-matrix-that-is-not-square).

#### matrix.slice

**`matrix.slice([matrix], [from_row], [to_row], [from_column], [to_column])`**

A new matrix with the rows from `from_row` up to, not including, `to_row` and the columns from `from_column` up to, not including, `to_column`.

- **Effects:** builds a new value whose size follows its arguments (counted in the memory ledger).
- **Phase:** every bar.
- **Cost:** allocates: the memory ledger counts what it builds.
- **Returns:** a matrix.

#### matrix.sort

**`matrix.sort([matrix], [column], [order])`**

Sorts the rows by the values of one column, ascending or descending.

- **Effects:** changes a collection in place.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.

#### matrix.subtract

**`matrix.subtract([matrix], [other])`**

A new matrix where another matrix of the same size, or a number, is subtracted from every element.

- **Effects:** builds a new value whose size follows its arguments (counted in the memory ledger).
- **Phase:** every bar.
- **Cost:** allocates: the memory ledger counts what it builds.
- **Returns:** a matrix.

#### matrix.swap_columns

**`matrix.swap_columns([matrix], [column1], [column2])`**

Swaps two columns.

- **Effects:** changes a collection in place.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.

#### matrix.swap_rows

**`matrix.swap_rows([matrix], [row1], [row2])`**

Swaps two rows.

- **Effects:** changes a collection in place.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.

#### matrix.trace

**`matrix.trace([matrix])`**

The sum of the elements on the main diagonal of a square matrix.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.
- **Returns:** a number.
- **Examples:** [Up and down transitions](https://millionchart.com/wiki/scripting/examples/collections#up-and-down-transitions), [Determinant of a matrix that is not square](https://millionchart.com/wiki/scripting/examples/collections#determinant-of-a-matrix-that-is-not-square).

#### matrix.transpose

**`matrix.transpose([matrix])`**

The transposed matrix.

- **Effects:** builds a new value whose size follows its arguments (counted in the memory ledger).
- **Phase:** every bar.
- **Cost:** allocates: the memory ledger counts what it builds.

## Orders reference

Place, change and cancel the orders of a strategy. The tester fills them on the bars of the chart under the rules of the setup and execution blocks.

### Functions

#### orders.cancel

**`orders.cancel([key])`**

Cancels the pending order with this key.

- **Effects:** places, changes or cancels an order.
- **Phase:** every bar.
- **Cost:** one order record per call.

#### orders.cancel_all

**`orders.cancel_all()`**

Cancels every pending order.

- **Effects:** places, changes or cancels an order.
- **Phase:** every bar.
- **Cost:** one order record per call.

#### orders.close

**`orders.close(key, [comment], [qty], [qty_percent], [message], [immediately], [silent])`**

Closes the position that the entry with this key opened.

- **Effects:** places, changes or cancels an order.
- **Phase:** every bar.
- **Cost:** one order record per call.
- **Examples:** [Moving average crossover strategy](https://millionchart.com/wiki/scripting/examples/orders-and-alerts#moving-average-crossover-strategy), [RSI reversion strategy](https://millionchart.com/wiki/scripting/examples/orders-and-alerts#rsi-reversion-strategy), [Risk guards](https://millionchart.com/wiki/scripting/examples/orders-and-alerts#risk-guards), [Trade tally](https://millionchart.com/wiki/scripting/examples/sizing-and-trades#trade-tally).

#### orders.close_all

**`orders.close_all([comment], [message], [immediately], [silent])`**

Closes every open position.

- **Effects:** places, changes or cancels an order.
- **Phase:** every bar.
- **Cost:** one order record per call.

#### orders.enter

**`orders.enter(key, side, [qty], [limit], [stop], [oca], [oca_type], [comment], [message], [silent], [expires])`**

Places an order in the direction `side` under the name `key`. Without `limit` or `stop` it is a market order; with one it waits until the price is reached, and `expires` limits how long it waits.

- **Effects:** places, changes or cancels an order.
- **Phase:** every bar.
- **Cost:** one order record per call.
- **Examples:** [Moving average crossover strategy](https://millionchart.com/wiki/scripting/examples/orders-and-alerts#moving-average-crossover-strategy), [Donchian breakout strategy](https://millionchart.com/wiki/scripting/examples/orders-and-alerts#donchian-breakout-strategy), [RSI reversion strategy](https://millionchart.com/wiki/scripting/examples/orders-and-alerts#rsi-reversion-strategy), [ATR stop and target](https://millionchart.com/wiki/scripting/examples/orders-and-alerts#atr-stop-and-target).

#### orders.exit

**`orders.exit(key, [entry], [qty], [qty_percent], [profit_ticks], [limit], [loss_ticks], [stop], [trail_price], [trail_ticks], [trail_offset_ticks], [oca], [comment], [profit_comment], [loss_comment], [trail_comment], [message], [profit_message], [loss_message], [trail_message], [silent])`**

Places the exit of the entry named `entry`: a stop, a limit, or a trailing stop, given as prices or as distances in ticks.

- **Effects:** places, changes or cancels an order.
- **Phase:** every bar.
- **Cost:** one order record per call.
- **Examples:** [ATR stop and target](https://millionchart.com/wiki/scripting/examples/orders-and-alerts#atr-stop-and-target), [Donchian breakout strategy](https://millionchart.com/wiki/scripting/examples/orders-and-alerts#donchian-breakout-strategy), [Stops on the price grid](https://millionchart.com/wiki/scripting/examples/determinism#stops-on-the-price-grid), [Loss limit before entry](https://millionchart.com/wiki/scripting/examples/sizing-and-trades#loss-limit-before-entry).

#### orders.exit_r

**`orders.exit_r(key, entry, risk_ticks, [target_r], [qty], [qty_percent], [comment], [profit_comment], [loss_comment])`**

Places the exit of the entry named `entry` as a bracket measured in the trade's own risk: the stop is `risk_ticks` ticks from the entry price and the limit is `target_r` times that distance on the other side (2 when left out). It is `orders.exit` with `loss_ticks = risk_ticks` and `profit_ticks = risk_ticks * target_r`, so it fills by the same rules and the closed trade's risk figure is the stop distance. A risk or a target that is not above zero places no exit and is noted in the journal. R is only a unit: one R is the distance from the entry to the stop, so a limit at `target_r = 2` sits two R from the entry. The default of 2 is a starting value, not a recommendation, and a bracket in R says nothing about how often either side is reached.

- **Effects:** places, changes or cancels an order.
- **Phase:** every bar.
- **Cost:** one order record per call.

#### orders.place

**`orders.place(key, side, [qty], [limit], [stop], [oca], [oca_type], [comment], [message], [silent], [expires])`**

Places an order of `qty` in the direction `side` under the name `key`, with the same price and expiry options as `orders.enter`.

- **Effects:** places, changes or cancels an order.
- **Phase:** every bar.
- **Cost:** one order record per call.

## Periods reference

Read a field of the current or of an earlier day, week or month, written `current(week).open` or `prior(day, 1).high`.

### Functions

#### current

**`current(period).field`**

A field of the current period so far.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.
- **Examples:** [Earlier days and weeks](https://millionchart.com/wiki/scripting/examples/time-and-sessions#earlier-days-and-weeks).

#### prior

**`prior(period [, n]).field`**

A field of the n-th finished period (day, week or month) before the current one.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.
- **Examples:** [Daily pivot levels](https://millionchart.com/wiki/scripting/examples/data-and-requests#daily-pivot-levels), [Earlier days and weeks](https://millionchart.com/wiki/scripting/examples/time-and-sessions#earlier-days-and-weeks).

## Polylines reference

A line drawn through a list of chart points.

### Functions

#### polyline.delete

**`polyline.delete([polyline])`**

Removes the object from the chart.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.

#### polyline.new

**`polyline.new([points], [curved], [closed], [x_unit], [color], [fill], [style], [width], [pane])`**

Draws a line through a list of points. `fill` paints the area the points enclose.

- **Effects:** draws on the chart or writes an output; builds a new value whose size follows its arguments (counted in the memory ledger).
- **Phase:** every bar.
- **Cost:** allocates: the memory ledger counts what it builds; counts against the limits on drawn objects and outputs.
- **Returns:** a polyline.
- **Examples:** [Swing high path](https://millionchart.com/wiki/scripting/examples/drawing#swing-high-path).

### Values

- `polyline.all`

## Position values reference

The position the simulated account holds now: its size, its average price, the key of the order that opened it and its liquidation price.

### Values

- `position.avg_price`
- `position.entry_key`
- `position.liquidation_price`
- `position.size`

## Risk rules reference

Rules that stop a strategy from trading when a limit is reached.

### Functions

#### risk.allow_entries

**`risk.allow_entries([value], [unit], [message])`**

Restricts the directions in which entries are allowed.

- **Effects:** places, changes or cancels an order.
- **Phase:** every bar.
- **Cost:** one order record per call.

#### risk.max_daily_loss

**`risk.max_daily_loss([value], [unit], [message])`**

Stops trading for the rest of the day once the loss of the day reaches `value`.

- **Effects:** places, changes or cancels an order.
- **Phase:** every bar.
- **Cost:** one order record per call.

#### risk.max_daily_orders

**`risk.max_daily_orders([value], [unit], [message])`**

Stops placing orders for the rest of the day once `value` orders have been filled.

- **Effects:** places, changes or cancels an order.
- **Phase:** every bar.
- **Cost:** one order record per call.
- **Examples:** [Risk guards](https://millionchart.com/wiki/scripting/examples/orders-and-alerts#risk-guards).

#### risk.max_drawdown

**`risk.max_drawdown([value], [unit], [message])`**

Stops trading once the drawdown reaches `value`.

- **Effects:** places, changes or cancels an order.
- **Phase:** every bar.
- **Cost:** one order record per call.

#### risk.max_losing_days

**`risk.max_losing_days([value], [unit], [message])`**

Stops trading after `value` losing days in a row.

- **Effects:** places, changes or cancels an order.
- **Phase:** every bar.
- **Cost:** one order record per call.
- **Examples:** [Risk guards](https://millionchart.com/wiki/scripting/examples/orders-and-alerts#risk-guards).

#### risk.max_position

**`risk.max_position([value], [unit], [message])`**

Limits the size of the position to `value`.

- **Effects:** places, changes or cancels an order.
- **Phase:** every bar.
- **Cost:** one order record per call.

## Sessions reference

A session is two times of day and a zone, declared with `session NAME = 08:00 .. 16:30 @ "Zone"`. Its members, written `NAME.active`, `NAME.start` and so on, tell where the bar stands in it.

### Functions

#### NAME.active

**`NAME.active`**

True while the bar is inside the session.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.
- **Examples:** [Session highs](https://millionchart.com/wiki/scripting/examples/temporal-calls#session-highs), [Session range boxes](https://millionchart.com/wiki/scripting/examples/time-and-sessions#session-range-boxes), [A session read by itself](https://millionchart.com/wiki/scripting/examples/time-and-sessions#a-session-read-by-itself).

#### NAME.end

**`NAME.end`**

True on the first bar after the session.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.
- **Examples:** [Session range boxes](https://millionchart.com/wiki/scripting/examples/time-and-sessions#session-range-boxes), [A session read by itself](https://millionchart.com/wiki/scripting/examples/time-and-sessions#a-session-read-by-itself).

#### NAME.high

**`NAME.high`**

The highest price of the current session so far.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.
- **Examples:** [Session range boxes](https://millionchart.com/wiki/scripting/examples/time-and-sessions#session-range-boxes), [A session read by itself](https://millionchart.com/wiki/scripting/examples/time-and-sessions#a-session-read-by-itself).

#### NAME.index

**`NAME.index`**

The number of the current session.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.
- **Examples:** [Session range boxes](https://millionchart.com/wiki/scripting/examples/time-and-sessions#session-range-boxes).

#### NAME.low

**`NAME.low`**

The lowest price of the current session so far.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.
- **Examples:** [Session range boxes](https://millionchart.com/wiki/scripting/examples/time-and-sessions#session-range-boxes), [A session read by itself](https://millionchart.com/wiki/scripting/examples/time-and-sessions#a-session-read-by-itself).

#### NAME.start

**`NAME.start`**

True on the first bar of the session.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.
- **Examples:** [Session range boxes](https://millionchart.com/wiki/scripting/examples/time-and-sessions#session-range-boxes), [A session read by itself](https://millionchart.com/wiki/scripting/examples/time-and-sessions#a-session-read-by-itself).

## Trade setups reference

Declare a trade idea an indicator has: a side, an entry, a stop and a target. The chart draws each one as a Long or Short position, with the zone the price has reached shown stronger. Nothing here places an order.

### Functions

#### setup.close

**`setup.close([setup], [state])`**

Closes a running setup at the current bar with a result: `hit_target`, `hit_stop`, `expired` or `cancelled`. A setup that is never closed is read from the bars by the chart.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.

#### setup.delete

**`setup.delete([setup])`**

Removes the setup from the chart.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.

#### setup.new

**`setup.new([side], [entry], [stop], [target], [start], [text])`**

Declares a trade setup: `side` is `long` or `short`, then the `entry`; `stop` and `target` are named. The levels must make a trade (a long needs stop < entry < target, a short the reverse), otherwise the call gives na and a warning. `start` is the bar it begins on (the current bar when left out); `text` is a short note shown on it.

- **Effects:** draws on the chart or writes an output; builds a new value whose size follows its arguments (counted in the memory ledger).
- **Phase:** every bar.
- **Cost:** allocates: the memory ledger counts what it builds; counts against the limits on drawn objects and outputs.
- **Returns:** a setup.

#### setup.set_stop

**`setup.set_stop([setup], [stop])`**

Moves the stop of a setup that is still running, not past the entry.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.

#### setup.set_target

**`setup.set_target([setup], [target])`**

Moves the target of a setup that is still running, not past the entry.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.

## Order direction reference

The directions of an order.

### Values

- `side.both` — Both directions.
- `side.long` — The long direction of an order.
- `side.short` — The short direction of an order.

## Sizing reference

Quantities and conversions of amounts between the currency of the account and that of the symbol.

### Functions

#### sizing.default_qty

**`sizing.default_qty([price])`**

The quantity the setup's size rule gives for an entry at `price`.

- **Effects:** reads the simulated account, so it is not moved across an order call.
- **Phase:** every bar.
- **Cost:** reads the account figure of the bar.
- **Examples:** [Loss limit before entry](https://millionchart.com/wiki/scripting/examples/sizing-and-trades#loss-limit-before-entry).

#### sizing.to_account

**`sizing.to_account([value])`**

Converts an amount from the currency of the symbol to the currency of the account.

- **Effects:** reads the simulated account, so it is not moved across an order call.
- **Phase:** every bar.
- **Cost:** reads the account figure of the bar.
- **Examples:** [Loss limit before entry](https://millionchart.com/wiki/scripting/examples/sizing-and-trades#loss-limit-before-entry).

#### sizing.to_symbol

**`sizing.to_symbol([value])`**

Converts an amount from the currency of the account to the currency of the symbol.

- **Effects:** reads the simulated account, so it is not moved across an order call.
- **Phase:** every bar.
- **Cost:** reads the account figure of the bar.
- **Examples:** [Loss limit before entry](https://millionchart.com/wiki/scripting/examples/sizing-and-trades#loss-limit-before-entry).

## Strategy statistics reference

Figures of the simulated account: equity, profit, drawdown and averages of the trades.

### Values

- `stats.account_currency`
- `stats.avg_loss`
- `stats.avg_loss_percent`
- `stats.avg_trade`
- `stats.avg_trade_percent`
- `stats.avg_win`
- `stats.avg_win_percent`
- `stats.capital`
- `stats.day_low_equity`
- `stats.day_start_equity`
- `stats.equity`
- `stats.equity_low`
- `stats.gross_loss`
- `stats.gross_loss_percent`
- `stats.gross_profit`
- `stats.gross_profit_percent`
- `stats.max_drawdown`
- `stats.max_drawdown_percent`
- `stats.max_runup`
- `stats.max_runup_percent`
- `stats.max_size`
- `stats.max_size_long`
- `stats.max_size_short`
- `stats.net_profit`
- `stats.net_profit_percent`
- `stats.open_profit`
- `stats.open_profit_percent`

## Symbol and price grid reference

Facts about the symbol, and the functions that put a price on its tick grid.

### Functions

#### symbol.price_of

**`symbol.price_of([ticks])`**

The price amount of a number of ticks.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.

#### symbol.snap

**`symbol.snap([price])`**

Rounds a price to the nearest tick of the symbol's price grid.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.
- **Examples:** [Stops on the price grid](https://millionchart.com/wiki/scripting/examples/determinism#stops-on-the-price-grid), [Loss limit before entry](https://millionchart.com/wiki/scripting/examples/sizing-and-trades#loss-limit-before-entry).

#### symbol.snap_down

**`symbol.snap_down([price])`**

Rounds a price down to the price grid.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.

#### symbol.snap_up

**`symbol.snap_up([price])`**

Rounds a price up to the price grid.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.

#### symbol.ticks

**`symbol.ticks([price])`**

The number of ticks in a price amount.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.
- **Examples:** [Loss limit before entry](https://millionchart.com/wiki/scripting/examples/sizing-and-trades#loss-limit-before-entry).

#### symbol.ticks_down

**`symbol.ticks_down([price])`**

The number of whole ticks in a price amount, rounded down.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.

#### symbol.ticks_up

**`symbol.ticks_up([price])`**

The number of whole ticks in a price amount, rounded up.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.

### Values

- `symbol.base_currency`
- `symbol.category`
- `symbol.contract_size`
- `symbol.currency`
- `symbol.id` — The identifier of the symbol of the chart.
- `symbol.lot_step`
- `symbol.margin_rate`
- `symbol.max_lot`
- `symbol.min_lot`
- `symbol.name`
- `symbol.pip`
- `symbol.point_value` — The money a price move of 1.0 makes for one unit of a strategy's quantity, in the quote currency: 1 on every instrument, futures included (a futures contract multiplier is not modelled). For lots use `symbol.contract_size`.
- `symbol.price_scale`
- `symbol.spec_date`
- `symbol.spec_source`
- `symbol.swap_long`
- `symbol.swap_mode`
- `symbol.swap_short`
- `symbol.swap_triple_day`
- `symbol.tick` — The size of one tick.
- `symbol.tick_value`
- `symbol.ticker`
- `symbol.venue`
- `symbol.volume_type`
- `symbol.zone`

## Tables reference

Tables drawn in a corner of the chart. A table is made with `table.new`, and `table.cell` writes its cells.

### Functions

#### table.cell

**`table.cell(table, column, row, [text], [width], [height], [text_color], [h_align], [v_align], [text_size], [background])`**

Writes a cell of a table: its text and look.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.
- **Examples:** [Status table](https://millionchart.com/wiki/scripting/examples/drawing#status-table), [Trade tally](https://millionchart.com/wiki/scripting/examples/sizing-and-trades#trade-tally), [Bars in a day](https://millionchart.com/wiki/scripting/examples/time-and-sessions#bars-in-a-day), [A timeframe text the chart does not know](https://millionchart.com/wiki/scripting/examples/time-and-sessions#a-timeframe-text-the-chart-does-not-know).

#### table.clear

**`table.clear([table], [from_column], [from_row], [to_column], [to_row])`**

Clears the cells of a block of the table.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.

#### table.delete

**`table.delete([table])`**

Removes the object from the chart.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.

#### table.merge_cells

**`table.merge_cells([table], [from_column], [from_row], [to_column], [to_row])`**

Merges a block of cells of the table into one.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.

#### table.new

**`table.new(position, columns, rows, [background], [frame_color], [frame_width], [border_color], [border_width], [pane], [corner_radius])`**

Makes a table of `columns` by `rows` in a corner of the chart. Border width (`border_width`), like the other border and frame arguments (`border_color`, `frame_color`, `frame_width`), is accepted but has no visual effect in E1. `corner_radius` rounds the corners of the whole table (css pixels, 0 = square, at most 40).

- **Effects:** draws on the chart or writes an output; builds a new value whose size follows its arguments (counted in the memory ledger).
- **Phase:** every bar.
- **Cost:** allocates: the memory ledger counts what it builds; counts against the limits on drawn objects and outputs.
- **Returns:** a table.
- **Examples:** [Status table](https://millionchart.com/wiki/scripting/examples/drawing#status-table), [Trade tally](https://millionchart.com/wiki/scripting/examples/sizing-and-trades#trade-tally), [Bars in a day](https://millionchart.com/wiki/scripting/examples/time-and-sessions#bars-in-a-day), [A timeframe text the chart does not know](https://millionchart.com/wiki/scripting/examples/time-and-sessions#a-timeframe-text-the-chart-does-not-know).

#### table.set_background

**`table.set_background([table], [background])`**

Changes the background of the table.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.

#### table.set_border_color

**`table.set_border_color([table], [border_color])`**

Changes the border color of the table.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.

#### table.set_border_width

**`table.set_border_width([table], [border_width])`**

Changes the border width of the table.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.

#### table.set_cell_background

**`table.set_cell_background([table], [column], [row], [background])`**

Changes the background of one cell.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.

#### table.set_cell_h_align

**`table.set_cell_h_align([table], [column], [row], [h_align])`**

Changes the h align of one cell.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.

#### table.set_cell_height

**`table.set_cell_height([table], [column], [row], [height])`**

Changes the height of one cell.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.

#### table.set_cell_text

**`table.set_cell_text([table], [column], [row], [text])`**

Changes the text of one cell.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.

#### table.set_cell_text_color

**`table.set_cell_text_color([table], [column], [row], [text_color])`**

Changes the text color of one cell.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.

#### table.set_cell_text_size

**`table.set_cell_text_size([table], [column], [row], [text_size])`**

Changes the text size of one cell.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.

#### table.set_cell_v_align

**`table.set_cell_v_align([table], [column], [row], [v_align])`**

Changes the v align of one cell.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.

#### table.set_cell_width

**`table.set_cell_width([table], [column], [row], [width])`**

Changes the width of one cell.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.

#### table.set_frame_color

**`table.set_frame_color([table], [frame_color])`**

Changes the frame color of the table.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.

#### table.set_frame_width

**`table.set_frame_width([table], [frame_width])`**

Changes the frame width of the table.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.

#### table.set_position

**`table.set_position([table], [position])`**

Changes the position of the table.

- **Effects:** draws on the chart or writes an output.
- **Phase:** every bar.
- **Cost:** counts against the limits on drawn objects and outputs.

### Values

- `table.all`

## Technical analysis reference

Moving averages, oscillators, channels and statistics over series. Every function here keeps a state for each place it is written, so it advances only when execution reaches it: see W3303 and W3302 in the diagnostics.

### Functions

#### tech.alma

**`tech.alma([source], [length], [bias], [sigma], [floor])`**

A moving average with Gaussian weights. `bias` moves the centre of the weights toward the newest bar and `sigma` sets how wide they are.

- **Effects:** keeps a state for each place it is written (a call site) and advances it when execution reaches the call.
- **Phase:** every bar.
- **Cost:** one state per call site; it reads back the number of bars in `length` (at most 8,192), so its memory follows that number and never the length of the chart.
- **Returns:** a series of numbers.

#### tech.aroon

**`tech.aroon(length)`**

The Aroon indicator over `length` bars. Returns `up` and `down`: each is 100 when the highest high (for `up`) or the lowest low (for `down`) of the last `length + 1` bars is the current bar, and falls by `100 / length` for every bar since. na until `length + 1` bars exist.

- **Effects:** keeps a state for each place it is written (a call site) and advances it when execution reaches the call.
- **Phase:** every bar.
- **Cost:** one state per call site; it reads back the number of bars in `length` (at most 8,192), so its memory follows that number and never the length of the chart.
- **Returns:** a tuple of two series.

#### tech.atr

**`tech.atr(length)`**

The average true range: the Wilder average of the true range (`tech.tr`) over `length` bars.

- **Effects:** keeps a state for each place it is written (a call site) and advances it when execution reaches the call.
- **Phase:** every bar.
- **Cost:** one state per call site; it reads back the number of bars in `length` (at most 8,192), so its memory follows that number and never the length of the chart.
- **Returns:** a series of numbers.
- **Examples:** [ATR channel](https://millionchart.com/wiki/scripting/examples/tech-indicators#atr-channel), [Status table](https://millionchart.com/wiki/scripting/examples/drawing#status-table), [ATR stop and target](https://millionchart.com/wiki/scripting/examples/orders-and-alerts#atr-stop-and-target), [Lazy operators](https://millionchart.com/wiki/scripting/examples/lazy-operators#lazy-operators).

#### tech.avg_dev

**`tech.avg_dev([source], [length])`**

The mean absolute deviation of `source` from its simple average over the window.

- **Effects:** keeps a state for each place it is written (a call site) and advances it when execution reaches the call.
- **Phase:** every bar.
- **Cost:** one state per call site; it reads back the number of bars in `length` (at most 8,192), so its memory follows that number and never the length of the chart.
- **Returns:** a series of numbers.

#### tech.bars_since

**`tech.bars_since(condition)`**

The number of bars since `condition` was last true; na until it has been true once.

- **Effects:** keeps a state for each place it is written (a call site) and advances it when execution reaches the call.
- **Phase:** every bar.
- **Cost:** one state per call site.
- **Returns:** a series of numbers.

#### tech.bb

**`tech.bb(source, length, mult)`**

Bollinger Bands. Returns the middle line (a simple moving average) and the upper and lower bands, `mult` standard deviations above and below it.

- **Effects:** keeps a state for each place it is written (a call site) and advances it when execution reaches the call.
- **Phase:** every bar.
- **Cost:** one state per call site; it reads back the number of bars in `length` (at most 8,192), so its memory follows that number and never the length of the chart.
- **Returns:** a tuple of three series.

#### tech.bbw

**`tech.bbw(source, length, mult)`**

The Bollinger Band width: upper band minus lower band, divided by the middle line.

- **Effects:** keeps a state for each place it is written (a call site) and advances it when execution reaches the call.
- **Phase:** every bar.
- **Cost:** one state per call site; it reads back the number of bars in `length` (at most 8,192), so its memory follows that number and never the length of the chart.
- **Returns:** a series of numbers.

#### tech.carry

**`tech.carry([source])`**

The last value of `source` that was not na: it carries a value forward over gaps.

- **Effects:** keeps a state for each place it is written (a call site) and advances it when execution reaches the call.
- **Phase:** every bar.
- **Cost:** one state per call site.
- **Returns:** a series of numbers.

#### tech.cci

**`tech.cci(source, length)`**

The commodity channel index: how far `source` is from its average, in units of the mean absolute deviation.

- **Effects:** keeps a state for each place it is written (a call site) and advances it when execution reaches the call.
- **Phase:** every bar.
- **Cost:** one state per call site; it reads back the number of bars in `length` (at most 8,192), so its memory follows that number and never the length of the chart.
- **Returns:** a series of numbers.

#### tech.change

**`tech.change(source, [length])`**

The difference between `source` and its value `length` bars ago (one bar by default).

- **Effects:** keeps a state for each place it is written (a call site) and advances it when execution reaches the call.
- **Phase:** every bar.
- **Cost:** one state per call site; it reads back the number of bars in `length` (at most 8,192), so its memory follows that number and never the length of the chart.
- **Returns:** a series of numbers.

#### tech.cmo

**`tech.cmo(source, length)`**

The Chande momentum oscillator: the difference between the sum of gains and the sum of losses, divided by their total, times 100.

- **Effects:** keeps a state for each place it is written (a call site) and advances it when execution reaches the call.
- **Phase:** every bar.
- **Cost:** one state per call site; it reads back the number of bars in `length` (at most 8,192), so its memory follows that number and never the length of the chart.
- **Returns:** a series of numbers.

#### tech.cog

**`tech.cog([source], [length])`**

The center of gravity oscillator of the window.

- **Effects:** keeps a state for each place it is written (a call site) and advances it when execution reaches the call.
- **Phase:** every bar.
- **Cost:** one state per call site; it reads back the number of bars in `length` (at most 8,192), so its memory follows that number and never the length of the chart.
- **Returns:** a series of numbers.

#### tech.correlation

**`tech.correlation(source, other, length)`**

The Pearson correlation of two series over the window.

- **Effects:** keeps a state for each place it is written (a call site) and advances it when execution reaches the call.
- **Phase:** every bar.
- **Cost:** one state per call site; it reads back the number of bars in `length` (at most 8,192), so its memory follows that number and never the length of the chart.
- **Returns:** a series of numbers.

#### tech.crosses

**`tech.crosses(source, other)`**

True on the bar where `source` crosses `other`, in either direction.

- **Effects:** keeps a state for each place it is written (a call site) and advances it when execution reaches the call.
- **Phase:** every bar.
- **Cost:** one state per call site.
- **Returns:** a series of true and false.

#### tech.crosses_above

**`tech.crosses_above(source, other)`**

True on the bar where `source` crosses above `other`.

- **Effects:** keeps a state for each place it is written (a call site) and advances it when execution reaches the call.
- **Phase:** every bar.
- **Cost:** one state per call site.
- **Returns:** a series of true and false.
- **Examples:** [EMA pair with cross marks](https://millionchart.com/wiki/scripting/examples/series-and-bars#ema-pair-with-cross-marks), [RSI zones](https://millionchart.com/wiki/scripting/examples/drawing#rsi-zones), [Cross alert](https://millionchart.com/wiki/scripting/examples/orders-and-alerts#cross-alert), [Moving average crossover strategy](https://millionchart.com/wiki/scripting/examples/orders-and-alerts#moving-average-crossover-strategy).

#### tech.crosses_below

**`tech.crosses_below(source, other)`**

True on the bar where `source` crosses below `other`.

- **Effects:** keeps a state for each place it is written (a call site) and advances it when execution reaches the call.
- **Phase:** every bar.
- **Cost:** one state per call site.
- **Returns:** a series of true and false.
- **Examples:** [EMA pair with cross marks](https://millionchart.com/wiki/scripting/examples/series-and-bars#ema-pair-with-cross-marks), [RSI zones](https://millionchart.com/wiki/scripting/examples/drawing#rsi-zones), [Moving average crossover strategy](https://millionchart.com/wiki/scripting/examples/orders-and-alerts#moving-average-crossover-strategy), [RSI reversion strategy](https://millionchart.com/wiki/scripting/examples/orders-and-alerts#rsi-reversion-strategy).

#### tech.cum_sum

**`tech.cum_sum(source)`**

The running total of `source` since the first bar.

- **Effects:** keeps a state for each place it is written (a call site) and advances it when execution reaches the call.
- **Phase:** every bar.
- **Cost:** one state per call site.
- **Returns:** a series of numbers.
- **Examples:** [On-balance volume](https://millionchart.com/wiki/scripting/examples/tech-indicators#on-balance-volume).

#### tech.dema

**`tech.dema(source, length)`**

The double exponential moving average: `2 * ema(source, length) - ema(ema(source, length), length)`. It follows price with less lag than a single exponential average.

- **Effects:** keeps a state for each place it is written (a call site) and advances it when execution reaches the call.
- **Phase:** every bar.
- **Cost:** one state per call site; it reads back the number of bars in `length` (at most 8,192), so its memory follows that number and never the length of the chart.
- **Returns:** a series of numbers.

#### tech.dmi

**`tech.dmi([di_length], [adx_length])`**

The directional movement index. Returns +DI, -DI and the ADX, the average directional index that measures trend strength.

- **Effects:** keeps a state for each place it is written (a call site) and advances it when execution reaches the call.
- **Phase:** every bar.
- **Cost:** one state per call site; it reads back the number of bars in `di_length`, `adx_length` (at most 8,192), so its memory follows that number and never the length of the chart.
- **Returns:** a tuple of three series.
- **Examples:** [ADX with directional indicators](https://millionchart.com/wiki/scripting/examples/tech-indicators#adx-with-directional-indicators).

#### tech.ema

**`tech.ema(source, length)`**

The exponential moving average. Each value is `alpha * source + (1 - alpha) * previous`, with `alpha = 2 / (length + 1)`.

- **Effects:** keeps a state for each place it is written (a call site) and advances it when execution reaches the call.
- **Phase:** every bar.
- **Cost:** one state per call site; it reads back the number of bars in `length` (at most 8,192), so its memory follows that number and never the length of the chart.
- **Returns:** a series of numbers.
- **Examples:** [EMA pair with cross marks](https://millionchart.com/wiki/scripting/examples/series-and-bars#ema-pair-with-cross-marks), [ATR channel](https://millionchart.com/wiki/scripting/examples/tech-indicators#atr-channel), [Higher timeframe average](https://millionchart.com/wiki/scripting/examples/data-and-requests#higher-timeframe-average), [On-balance volume](https://millionchart.com/wiki/scripting/examples/tech-indicators#on-balance-volume).

#### tech.highest

**`tech.highest(source, [length])`**

The highest value of `source` over the last `length` bars.

- **Effects:** keeps a state for each place it is written (a call site) and advances it when execution reaches the call.
- **Phase:** every bar.
- **Cost:** one state per call site; it reads back the number of bars in `length` (at most 8,192), so its memory follows that number and never the length of the chart.
- **Returns:** a series of numbers.
- **Examples:** [Donchian channel](https://millionchart.com/wiki/scripting/examples/tech-indicators#donchian-channel), [Stochastic oscillator](https://millionchart.com/wiki/scripting/examples/tech-indicators#stochastic-oscillator), [Recent range drawing](https://millionchart.com/wiki/scripting/examples/drawing#recent-range-drawing), [Bars since a high](https://millionchart.com/wiki/scripting/examples/series-and-bars#bars-since-a-high).

#### tech.highest_offset

**`tech.highest_offset(source, [length])`**

How many bars back the highest value of the window is.

- **Effects:** keeps a state for each place it is written (a call site) and advances it when execution reaches the call.
- **Phase:** every bar.
- **Cost:** one state per call site; it reads back the number of bars in `length` (at most 8,192), so its memory follows that number and never the length of the chart.
- **Returns:** a series of numbers.

#### tech.hma

**`tech.hma(source, length)`**

The Hull moving average: a weighted average built to follow price closely with little lag.

- **Effects:** keeps a state for each place it is written (a call site) and advances it when execution reaches the call.
- **Phase:** every bar.
- **Cost:** one state per call site; it reads back the number of bars in `length` (at most 8,192), so its memory follows that number and never the length of the chart.
- **Returns:** a series of numbers.

#### tech.is_falling

**`tech.is_falling(source, length)`**

True when `source` has fallen on each of the last `length` bars.

- **Effects:** keeps a state for each place it is written (a call site) and advances it when execution reaches the call.
- **Phase:** every bar.
- **Cost:** one state per call site; it reads back the number of bars in `length` (at most 8,192), so its memory follows that number and never the length of the chart.
- **Returns:** a series of true and false.

#### tech.is_rising

**`tech.is_rising(source, length)`**

True when `source` has risen on each of the last `length` bars.

- **Effects:** keeps a state for each place it is written (a call site) and advances it when execution reaches the call.
- **Phase:** every bar.
- **Cost:** one state per call site; it reads back the number of bars in `length` (at most 8,192), so its memory follows that number and never the length of the chart.
- **Returns:** a series of true and false.

#### tech.kc

**`tech.kc(source, length, mult, [use_true_range])`**

Keltner Channels. Returns the middle line (an exponential average) and the upper and lower lines, `mult` times a measure of range above and below it.

- **Effects:** keeps a state for each place it is written (a call site) and advances it when execution reaches the call.
- **Phase:** every bar.
- **Cost:** one state per call site; it reads back the number of bars in `length` (at most 8,192), so its memory follows that number and never the length of the chart.
- **Returns:** a tuple of three series.

#### tech.kcw

**`tech.kcw([source], [length], [mult], [use_true_range])`**

The Keltner Channel width: upper line minus lower line, divided by the middle line.

- **Effects:** keeps a state for each place it is written (a call site) and advances it when execution reaches the call.
- **Phase:** every bar.
- **Cost:** one state per call site; it reads back the number of bars in `length` (at most 8,192), so its memory follows that number and never the length of the chart.
- **Returns:** a series of numbers.

#### tech.linreg

**`tech.linreg([source], [length], [offset])`**

The value of the least-squares line fitted to the window, at the newest bar shifted by `offset`.

- **Effects:** keeps a state for each place it is written (a call site) and advances it when execution reaches the call.
- **Phase:** every bar.
- **Cost:** one state per call site; it reads back the number of bars in `length` (at most 8,192), so its memory follows that number and never the length of the chart.
- **Returns:** a series of numbers.

#### tech.lowest

**`tech.lowest(source, [length])`**

The lowest value of `source` over the last `length` bars.

- **Effects:** keeps a state for each place it is written (a call site) and advances it when execution reaches the call.
- **Phase:** every bar.
- **Cost:** one state per call site; it reads back the number of bars in `length` (at most 8,192), so its memory follows that number and never the length of the chart.
- **Returns:** a series of numbers.
- **Examples:** [Donchian channel](https://millionchart.com/wiki/scripting/examples/tech-indicators#donchian-channel), [Stochastic oscillator](https://millionchart.com/wiki/scripting/examples/tech-indicators#stochastic-oscillator), [Recent range drawing](https://millionchart.com/wiki/scripting/examples/drawing#recent-range-drawing), [Donchian breakout strategy](https://millionchart.com/wiki/scripting/examples/orders-and-alerts#donchian-breakout-strategy).

#### tech.lowest_offset

**`tech.lowest_offset(source, [length])`**

How many bars back the lowest value of the window is.

- **Effects:** keeps a state for each place it is written (a call site) and advances it when execution reaches the call.
- **Phase:** every bar.
- **Cost:** one state per call site; it reads back the number of bars in `length` (at most 8,192), so its memory follows that number and never the length of the chart.
- **Returns:** a series of numbers.

#### tech.macd

**`tech.macd(source, fast_length, slow_length, signal_length)`**

Moving Average Convergence Divergence. Returns the MACD line (fast EMA minus slow EMA), the signal line (an EMA of the MACD line) and the histogram (their difference).

- **Effects:** keeps a state for each place it is written (a call site) and advances it when execution reaches the call.
- **Phase:** every bar.
- **Cost:** one state per call site; it reads back the number of bars in `fast_length`, `slow_length`, `signal_length` (at most 8,192), so its memory follows that number and never the length of the chart.
- **Returns:** a tuple of three series.
- **Examples:** [MACD](https://millionchart.com/wiki/scripting/examples/tech-indicators#macd).

#### tech.median

**`tech.median([source], [length])`**

The median of `source` over the window.

- **Effects:** keeps a state for each place it is written (a call site) and advances it when execution reaches the call.
- **Phase:** every bar.
- **Cost:** one state per call site; it reads back the number of bars in `length` (at most 8,192), so its memory follows that number and never the length of the chart.
- **Returns:** a series of numbers.

#### tech.mfi

**`tech.mfi(source, length)`**

The money flow index: a volume-weighted relative strength index of the typical price.

- **Effects:** keeps a state for each place it is written (a call site) and advances it when execution reaches the call.
- **Phase:** every bar.
- **Cost:** one state per call site; it reads back the number of bars in `length` (at most 8,192), so its memory follows that number and never the length of the chart.
- **Returns:** a series of numbers.

#### tech.mode

**`tech.mode([source], [length])`**

The most frequent value of `source` over the window.

- **Effects:** keeps a state for each place it is written (a call site) and advances it when execution reaches the call.
- **Phase:** every bar.
- **Cost:** one state per call site; it reads back the number of bars in `length` (at most 8,192), so its memory follows that number and never the length of the chart.
- **Returns:** a series of numbers.

#### tech.mom

**`tech.mom(source, length)`**

Momentum: `source` minus `source` `length` bars ago.

- **Effects:** keeps a state for each place it is written (a call site) and advances it when execution reaches the call.
- **Phase:** every bar.
- **Cost:** one state per call site; it reads back the number of bars in `length` (at most 8,192), so its memory follows that number and never the length of the chart.
- **Returns:** a series of numbers.

#### tech.percent_rank

**`tech.percent_rank(source, length)`**

The percent of the previous `length` values that are less than or equal to the current one.

- **Effects:** keeps a state for each place it is written (a call site) and advances it when execution reaches the call.
- **Phase:** every bar.
- **Cost:** one state per call site; it reads back the number of bars in `length` (at most 8,192), so its memory follows that number and never the length of the chart.
- **Returns:** a series of numbers.

#### tech.percentile

**`tech.percentile([source], [length], [percent])`**

The value at the given percent of the window, interpolating between neighbours.

- **Effects:** keeps a state for each place it is written (a call site) and advances it when execution reaches the call.
- **Phase:** every bar.
- **Cost:** one state per call site; it reads back the number of bars in `length` (at most 8,192), so its memory follows that number and never the length of the chart.
- **Returns:** a series of numbers.

#### tech.percentile_nearest

**`tech.percentile_nearest([source], [length], [percent])`**

The value at the given percent of the window, taking the nearest rank.

- **Effects:** keeps a state for each place it is written (a call site) and advances it when execution reaches the call.
- **Phase:** every bar.
- **Cost:** one state per call site; it reads back the number of bars in `length` (at most 8,192), so its memory follows that number and never the length of the chart.
- **Returns:** a series of numbers.

#### tech.pivot_high

**`tech.pivot_high(source, left_bars, [right_bars])`**

The price of a swing high: a bar whose value is the highest of `left_bars` bars before it and `right_bars` after it. It is known `right_bars` bars late, and na on every other bar.

- **Effects:** keeps a state for each place it is written (a call site) and advances it when execution reaches the call.
- **Phase:** every bar.
- **Cost:** one state per call site; it reads back the number of bars in `left_bars`, `right_bars` (at most 8,192), so its memory follows that number and never the length of the chart.
- **Returns:** a series of numbers.
- **Examples:** [Swing pivots](https://millionchart.com/wiki/scripting/examples/drawing#swing-pivots), [Swing high path](https://millionchart.com/wiki/scripting/examples/drawing#swing-high-path).

#### tech.pivot_levels

**`tech.pivot_levels([kind], [anchor], [developing])`**

Pivot point levels computed from the previous period of `anchor` by the formula `kind`.

- **Effects:** keeps a state for each place it is written (a call site) and advances it when execution reaches the call; builds a new value whose size follows its arguments (counted in the memory ledger).
- **Phase:** every bar.
- **Cost:** one state per call site; allocates: the memory ledger counts what it builds.

#### tech.pivot_low

**`tech.pivot_low(source, left_bars, [right_bars])`**

The price of a swing low, found the same way as `tech.pivot_high`.

- **Effects:** keeps a state for each place it is written (a call site) and advances it when execution reaches the call.
- **Phase:** every bar.
- **Cost:** one state per call site; it reads back the number of bars in `left_bars`, `right_bars` (at most 8,192), so its memory follows that number and never the length of the chart.
- **Returns:** a series of numbers.
- **Examples:** [Swing pivots](https://millionchart.com/wiki/scripting/examples/drawing#swing-pivots).

#### tech.range

**`tech.range([source], [length])`**

The highest value minus the lowest value of `source` over the window.

- **Effects:** keeps a state for each place it is written (a call site) and advances it when execution reaches the call.
- **Phase:** every bar.
- **Cost:** one state per call site; it reads back the number of bars in `length` (at most 8,192), so its memory follows that number and never the length of the chart.
- **Returns:** a series of numbers.

#### tech.rci

**`tech.rci([source], [length])`**

The rank correlation index of the window: how closely the price ranks follow the time order.

- **Effects:** keeps a state for each place it is written (a call site) and advances it when execution reaches the call.
- **Phase:** every bar.
- **Cost:** one state per call site; it reads back the number of bars in `length` (at most 8,192), so its memory follows that number and never the length of the chart.
- **Returns:** a series of numbers.

#### tech.rma

**`tech.rma(source, length)`**

Wilder's running moving average, an exponential average with `alpha = 1 / length`. It is the smoothing behind `tech.rsi` and `tech.atr`.

- **Effects:** keeps a state for each place it is written (a call site) and advances it when execution reaches the call.
- **Phase:** every bar.
- **Cost:** one state per call site; it reads back the number of bars in `length` (at most 8,192), so its memory follows that number and never the length of the chart.
- **Returns:** a series of numbers.
- **Examples:** [RSI written out](https://millionchart.com/wiki/scripting/examples/series-and-bars#rsi-written-out).

#### tech.roc

**`tech.roc(source, length)`**

Rate of change: the percent change of `source` over `length` bars.

- **Effects:** keeps a state for each place it is written (a call site) and advances it when execution reaches the call.
- **Phase:** every bar.
- **Cost:** one state per call site; it reads back the number of bars in `length` (at most 8,192), so its memory follows that number and never the length of the chart.
- **Returns:** a series of numbers.

#### tech.rsi

**`tech.rsi(source, length)`**

The relative strength index: 100 minus 100 divided by one plus the ratio of the Wilder average gain to the Wilder average loss. It lies between 0 and 100.

- **Effects:** keeps a state for each place it is written (a call site) and advances it when execution reaches the call.
- **Phase:** every bar.
- **Cost:** one state per call site; it reads back the number of bars in `length` (at most 8,192), so its memory follows that number and never the length of the chart.
- **Returns:** a series of numbers.
- **Examples:** [RSI zones](https://millionchart.com/wiki/scripting/examples/drawing#rsi-zones), [RSI written out](https://millionchart.com/wiki/scripting/examples/series-and-bars#rsi-written-out), [Status table](https://millionchart.com/wiki/scripting/examples/drawing#status-table), [RSI reversion strategy](https://millionchart.com/wiki/scripting/examples/orders-and-alerts#rsi-reversion-strategy).

#### tech.running_max

**`tech.running_max([source])`**

The highest value of `source` since the first bar.

- **Effects:** keeps a state for each place it is written (a call site) and advances it when execution reaches the call.
- **Phase:** every bar.
- **Cost:** one state per call site.
- **Returns:** a series of numbers.

#### tech.running_min

**`tech.running_min([source])`**

The lowest value of `source` since the first bar.

- **Effects:** keeps a state for each place it is written (a call site) and advances it when execution reaches the call.
- **Phase:** every bar.
- **Cost:** one state per call site.
- **Returns:** a series of numbers.

#### tech.sample_when

**`tech.sample_when(source, condition, occurrence)`**

The value of `source` on the bar where `condition` was true, looking back `occurrence` such bars (0 is the latest).

- **Effects:** keeps a state for each place it is written (a call site) and advances it when execution reaches the call; builds a new value whose size follows its arguments (counted in the memory ledger).
- **Phase:** every bar.
- **Cost:** one state per call site; it reads back the number of bars in `occurrence` (at most 8,192), so its memory follows that number and never the length of the chart; allocates: the memory ledger counts what it builds.
- **Returns:** a series of numbers.

#### tech.sar

**`tech.sar([start], [step], [max])`**

The parabolic stop and reverse: a trailing point that accelerates by `step` up to `max` in the direction of the trend.

- **Effects:** keeps a state for each place it is written (a call site) and advances it when execution reaches the call.
- **Phase:** every bar.
- **Cost:** one state per call site.
- **Returns:** a series of numbers.

#### tech.sma

**`tech.sma(source, length)`**

The simple moving average: the mean of the last `length` values of `source`.

- **Effects:** keeps a state for each place it is written (a call site) and advances it when execution reaches the call.
- **Phase:** every bar.
- **Cost:** one state per call site; it reads back the number of bars in `length` (at most 8,192), so its memory follows that number and never the length of the chart.
- **Returns:** a series of numbers.
- **Examples:** [Simple moving average](https://millionchart.com/wiki/scripting/examples/start#simple-moving-average), [Bollinger bands](https://millionchart.com/wiki/scripting/examples/tech-indicators#bollinger-bands), [Stochastic oscillator](https://millionchart.com/wiki/scripting/examples/tech-indicators#stochastic-oscillator), [Trend background](https://millionchart.com/wiki/scripting/examples/drawing#trend-background).

#### tech.stdev

**`tech.stdev(source, length, [biased])`**

The standard deviation of `source` over the window.

- **Effects:** keeps a state for each place it is written (a call site) and advances it when execution reaches the call.
- **Phase:** every bar.
- **Cost:** one state per call site; it reads back the number of bars in `length` (at most 8,192), so its memory follows that number and never the length of the chart.
- **Returns:** a series of numbers.
- **Examples:** [Bollinger bands](https://millionchart.com/wiki/scripting/examples/tech-indicators#bollinger-bands).

#### tech.stoch

**`tech.stoch(source, length, high, low)`**

The raw stochastic: 100 times the close's distance above the lowest low of the window, divided by the range between the highest high and the lowest low.

- **Effects:** keeps a state for each place it is written (a call site) and advances it when execution reaches the call.
- **Phase:** every bar.
- **Cost:** one state per call site; it reads back the number of bars in `length` (at most 8,192), so its memory follows that number and never the length of the chart.
- **Returns:** a series of numbers.
- **Examples:** [Stochastic oscillator](https://millionchart.com/wiki/scripting/examples/tech-indicators#stochastic-oscillator).

#### tech.sum

**`tech.sum(source, length)`**

The sum of `source` over the last `length` bars.

- **Effects:** keeps a state for each place it is written (a call site) and advances it when execution reaches the call.
- **Phase:** every bar.
- **Cost:** one state per call site; it reads back the number of bars in `length` (at most 8,192), so its memory follows that number and never the length of the chart.
- **Returns:** a series of numbers.

#### tech.supertrend

**`tech.supertrend([factor], [atr_length])`**

The supertrend: a line built from the average true range that flips side when the price crosses it. Returns the line and the direction.

- **Effects:** keeps a state for each place it is written (a call site) and advances it when execution reaches the call.
- **Phase:** every bar.
- **Cost:** one state per call site; it reads back the number of bars in `atr_length` (at most 8,192), so its memory follows that number and never the length of the chart.
- **Returns:** a tuple of two series.

#### tech.swma

**`tech.swma([source])`**

A moving average of the last four values with the weights 1, 2, 2, 1.

- **Effects:** keeps a state for each place it is written (a call site) and advances it when execution reaches the call.
- **Phase:** every bar.
- **Cost:** one state per call site; a fixed window of 4 bars.
- **Returns:** a series of numbers.

#### tech.tr

**`tech.tr([handle_na])`**

The true range of the bar: the largest of the high minus the low, the high minus the previous close and the previous close minus the low (absolute values).

A function and also a value of the same name: `tech.tr` is the true range of the current bar.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.
- **Returns:** a series of numbers.

#### tech.tsi

**`tech.tsi([source], [short_length], [long_length])`**

The true strength index: a double-smoothed momentum divided by the double-smoothed absolute momentum.

- **Effects:** keeps a state for each place it is written (a call site) and advances it when execution reaches the call.
- **Phase:** every bar.
- **Cost:** one state per call site; it reads back the number of bars in `short_length`, `long_length` (at most 8,192), so its memory follows that number and never the length of the chart.
- **Returns:** a series of numbers.

#### tech.variance

**`tech.variance(source, length, [biased])`**

The variance of `source` over the window.

- **Effects:** keeps a state for each place it is written (a call site) and advances it when execution reaches the call.
- **Phase:** every bar.
- **Cost:** one state per call site; it reads back the number of bars in `length` (at most 8,192), so its memory follows that number and never the length of the chart.
- **Returns:** a series of numbers.

#### tech.vwap

**`tech.vwap([source], [anchor], [mult])`**

The volume-weighted average price, restarting at each `anchor` period.

- **Effects:** keeps a state for each place it is written (a call site) and advances it when execution reaches the call.
- **Phase:** every bar.
- **Cost:** one state per call site.
- **Returns:** a series of numbers.

#### tech.vwma

**`tech.vwma(source, length)`**

The volume-weighted moving average: the mean of `source * volume` over the window divided by the mean of `volume`.

- **Effects:** keeps a state for each place it is written (a call site) and advances it when execution reaches the call.
- **Phase:** every bar.
- **Cost:** one state per call site; it reads back the number of bars in `length` (at most 8,192), so its memory follows that number and never the length of the chart.
- **Returns:** a series of numbers.

#### tech.wma

**`tech.wma(source, length)`**

The weighted moving average: the newest value of the window has the largest weight, falling linearly to the oldest.

- **Effects:** keeps a state for each place it is written (a call site) and advances it when execution reaches the call.
- **Phase:** every bar.
- **Cost:** one state per call site; it reads back the number of bars in `length` (at most 8,192), so its memory follows that number and never the length of the chart.
- **Returns:** a series of numbers.

#### tech.wpr

**`tech.wpr([length])`**

Williams %R: where the close sits in the range of the last `length` bars, on a scale from -100 to 0.

- **Effects:** keeps a state for each place it is written (a call site) and advances it when execution reaches the call.
- **Phase:** every bar.
- **Cost:** one state per call site; it reads back the number of bars in `length` (at most 8,192), so its memory follows that number and never the length of the chart.
- **Returns:** a series of numbers.

### Values

- `tech.accdist`
- `tech.iii`
- `tech.nvi`
- `tech.obv`
- `tech.pvi`
- `tech.pvt`
- `tech.tr`
- `tech.vwap`
- `tech.wad`
- `tech.wvad`

## Text reference

Build, search and change text.

### Functions

#### text.contains

**`text.contains(text, part)`**

True when `text` holds `part`.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.

#### text.ends_with

**`text.ends_with(text, part)`**

True when `text` ends with `part`.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.

#### text.fmt

**`text.fmt([value], [spec], [fallback], [zone])`**

A value written as text by a format `spec`, with a fallback for na.

- **Effects:** builds a new value whose size follows its arguments (counted in the memory ledger).
- **Phase:** every bar.
- **Cost:** allocates: the memory ledger counts what it builds.

#### text.format

**`text.format([pattern], ...values)`**

Fills `{0}`, `{1}` in `pattern` with the values after it.

- **Effects:** builds a new value whose size follows its arguments (counted in the memory ledger).
- **Phase:** every bar.
- **Cost:** allocates: the memory ledger counts what it builds.
- **Examples:** [Levels from text](https://millionchart.com/wiki/scripting/examples/text-and-logs#levels-from-text).

#### text.format_time

**`text.format_time([time], [pattern], [zone])`**

A time value written by a pattern, in a zone.

- **Effects:** builds a new value whose size follows its arguments (counted in the memory ledger).
- **Phase:** every bar.
- **Cost:** allocates: the memory ledger counts what it builds.

#### text.index_of

**`text.index_of(text, part)`**

The position of the first `part` in `text`, or -1.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.

#### text.length

**`text.length(text)`**

The number of characters of `text`.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.

#### text.lower

**`text.lower(text)`**

The text in lower or upper case.

- **Effects:** builds a new value whose size follows its arguments (counted in the memory ledger).
- **Phase:** every bar.
- **Cost:** allocates: the memory ledger counts what it builds.

#### text.match

**`text.match([text], [pattern])`**

Matches `text` against a pattern.

- **Effects:** builds a new value whose size follows its arguments (counted in the memory ledger).
- **Phase:** every bar.
- **Cost:** allocates: the memory ledger counts what it builds.

#### text.of

**`text.of(value, [format])`**

A value written as text, in a given format.

- **Effects:** builds a new value whose size follows its arguments (counted in the memory ledger).
- **Phase:** every bar.
- **Cost:** allocates: the memory ledger counts what it builds.

#### text.repeat

**`text.repeat(text, count, [separator])`**

The text repeated `count` times, with `separator` between.

- **Effects:** builds a new value whose size follows its arguments (counted in the memory ledger).
- **Phase:** every bar.
- **Cost:** allocates: the memory ledger counts what it builds.

#### text.replace

**`text.replace(text, target, replacement, [occurrence])`**

Replaces one occurrence of `target`.

- **Effects:** builds a new value whose size follows its arguments (counted in the memory ledger).
- **Phase:** every bar.
- **Cost:** allocates: the memory ledger counts what it builds.

#### text.replace_all

**`text.replace_all(text, target, replacement)`**

Replaces every occurrence of `target`.

- **Effects:** builds a new value whose size follows its arguments (counted in the memory ledger).
- **Phase:** every bar.
- **Cost:** allocates: the memory ledger counts what it builds.
- **Examples:** [Levels from text](https://millionchart.com/wiki/scripting/examples/text-and-logs#levels-from-text).

#### text.slice

**`text.slice(text, from, [to])`**

The part of `text` from `from` to `to`.

- **Effects:** builds a new value whose size follows its arguments (counted in the memory ledger).
- **Phase:** every bar.
- **Cost:** allocates: the memory ledger counts what it builds.

#### text.split

**`text.split(text, separator)`**

Splits `text` at `separator` into an array.

- **Effects:** builds a new value whose size follows its arguments (counted in the memory ledger).
- **Phase:** every bar.
- **Cost:** allocates: the memory ledger counts what it builds.
- **Examples:** [Levels from text](https://millionchart.com/wiki/scripting/examples/text-and-logs#levels-from-text).

#### text.starts_with

**`text.starts_with(text, part)`**

True when `text` begins with `part`.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.

#### text.to_number

**`text.to_number(text)`**

The number written in `text`, or na.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.
- **Examples:** [Levels from text](https://millionchart.com/wiki/scripting/examples/text-and-logs#levels-from-text).

#### text.trim

**`text.trim(text)`**

The text without spaces at either end.

- **Effects:** builds a new value whose size follows its arguments (counted in the memory ledger).
- **Phase:** every bar.
- **Cost:** allocates: the memory ledger counts what it builds.
- **Examples:** [Levels from text](https://millionchart.com/wiki/scripting/examples/text-and-logs#levels-from-text).

#### text.upper

**`text.upper(text)`**

The text in lower or upper case.

- **Effects:** builds a new value whose size follows its arguments (counted in the memory ledger).
- **Phase:** every bar.
- **Cost:** allocates: the memory ledger counts what it builds.

## Timeframes reference

Convert timeframe texts and detect the start of a new period of a timeframe.

### Functions

#### tf.changed

**`tf.changed([tf])`**

True on the first bar of each new period of the timeframe `tf`, never on the very first bar of the chart (there is no earlier period to change from).

- **Effects:** keeps a state for each place it is written (a call site) and advances it when execution reaches the call.
- **Phase:** every bar.
- **Cost:** one state per call site.
- **Examples:** [Bars in a day](https://millionchart.com/wiki/scripting/examples/time-and-sessions#bars-in-a-day), [A timeframe text the chart does not know](https://millionchart.com/wiki/scripting/examples/time-and-sessions#a-timeframe-text-the-chart-does-not-know).

#### tf.from_seconds

**`tf.from_seconds([seconds])`**

The timeframe text of a length in seconds.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.
- **Examples:** [Bars in a day](https://millionchart.com/wiki/scripting/examples/time-and-sessions#bars-in-a-day), [A timeframe text the chart does not know](https://millionchart.com/wiki/scripting/examples/time-and-sessions#a-timeframe-text-the-chart-does-not-know).

#### tf.to_seconds

**`tf.to_seconds([tf])`**

The length of a timeframe in seconds.

- **Effects:** none: the result depends on the arguments only.
- **Phase:** every bar.
- **Cost:** a fixed number of operations.
- **Examples:** [Bars in a day](https://millionchart.com/wiki/scripting/examples/time-and-sessions#bars-in-a-day), [A timeframe text the chart does not know](https://millionchart.com/wiki/scripting/examples/time-and-sessions#a-timeframe-text-the-chart-does-not-know).

### Values

- `tf.id` — The timeframe of the chart as text.
- `tf.is_daily` — True when the chart is daily.
- `tf.is_daily_or_longer`
- `tf.is_intraday` — True when the chart is made of intraday bars.
- `tf.is_minutes`
- `tf.is_monthly`
- `tf.is_seconds`
- `tf.is_weekly`
- `tf.multiplier`

## Closed trades reference

Facts about each closed trade of the simulated account, by index.

### Functions

#### trades.closed.capital_held

**`trades.closed.capital_held()`**

The capital held by closed trades: always 0, because a closed trade holds none.

- **Effects:** reads the simulated account, so it is not moved across an order call.
- **Phase:** every bar.
- **Cost:** reads the account figure of the bar.
- **Returns:** a number.

#### trades.closed.entry_comment

**`trades.closed.entry_comment([index])`**

The comment of the order that opened closed trade number `index`.

- **Effects:** reads the simulated account, so it is not moved across an order call.
- **Phase:** every bar.
- **Cost:** reads the account figure of the bar.
- **Returns:** a text.

#### trades.closed.entry_index

**`trades.closed.entry_index([index])`**

The bar index at which closed trade number `index` was entered.

- **Effects:** reads the simulated account, so it is not moved across an order call.
- **Phase:** every bar.
- **Cost:** reads the account figure of the bar.
- **Returns:** a whole number.

#### trades.closed.entry_key

**`trades.closed.entry_key([index])`**

The key of the order that opened closed trade number `index`.

- **Effects:** reads the simulated account, so it is not moved across an order call.
- **Phase:** every bar.
- **Cost:** reads the account figure of the bar.
- **Returns:** a text.

#### trades.closed.entry_price

**`trades.closed.entry_price([index])`**

The price at which closed trade number `index` was entered.

- **Effects:** reads the simulated account, so it is not moved across an order call.
- **Phase:** every bar.
- **Cost:** reads the account figure of the bar.
- **Returns:** a number.

#### trades.closed.entry_time

**`trades.closed.entry_time([index])`**

The time at which closed trade number `index` was entered.

- **Effects:** reads the simulated account, so it is not moved across an order call.
- **Phase:** every bar.
- **Cost:** reads the account figure of the bar.
- **Returns:** a time.

#### trades.closed.exit_comment

**`trades.closed.exit_comment([index])`**

The comment of the order that closed trade number `index`.

- **Effects:** reads the simulated account, so it is not moved across an order call.
- **Phase:** every bar.
- **Cost:** reads the account figure of the bar.
- **Returns:** a text.

#### trades.closed.exit_index

**`trades.closed.exit_index([index])`**

The bar index at which closed trade number `index` was exited.

- **Effects:** reads the simulated account, so it is not moved across an order call.
- **Phase:** every bar.
- **Cost:** reads the account figure of the bar.
- **Returns:** a whole number.

#### trades.closed.exit_key

**`trades.closed.exit_key([index])`**

The key of the order that closed trade number `index`.

- **Effects:** reads the simulated account, so it is not moved across an order call.
- **Phase:** every bar.
- **Cost:** reads the account figure of the bar.
- **Returns:** a text.

#### trades.closed.exit_price

**`trades.closed.exit_price([index])`**

The price at which closed trade number `index` was exited.

- **Effects:** reads the simulated account, so it is not moved across an order call.
- **Phase:** every bar.
- **Cost:** reads the account figure of the bar.
- **Returns:** a number.

#### trades.closed.exit_time

**`trades.closed.exit_time([index])`**

The time at which closed trade number `index` was exited.

- **Effects:** reads the simulated account, so it is not moved across an order call.
- **Phase:** every bar.
- **Cost:** reads the account figure of the bar.
- **Returns:** a time.

#### trades.closed.fees

**`trades.closed.fees([index])`**

The fees charged to closed trade number `index`.

- **Effects:** reads the simulated account, so it is not moved across an order call.
- **Phase:** every bar.
- **Cost:** reads the account figure of the bar.
- **Returns:** a number.

#### trades.closed.max_drawdown

**`trades.closed.max_drawdown([index])`**

The largest fall of closed trade number `index` below its entry price, in account money; shown as a positive number.

- **Effects:** reads the simulated account, so it is not moved across an order call.
- **Phase:** every bar.
- **Cost:** reads the account figure of the bar.
- **Returns:** a number.

#### trades.closed.max_drawdown_percent

**`trades.closed.max_drawdown_percent([index])`**

The largest fall of closed trade number `index` below its entry price, as a percentage of the value at entry.

- **Effects:** reads the simulated account, so it is not moved across an order call.
- **Phase:** every bar.
- **Cost:** reads the account figure of the bar.
- **Returns:** a number.

#### trades.closed.max_runup

**`trades.closed.max_runup([index])`**

The largest rise of closed trade number `index` above its entry price, in account money.

- **Effects:** reads the simulated account, so it is not moved across an order call.
- **Phase:** every bar.
- **Cost:** reads the account figure of the bar.
- **Returns:** a number.

#### trades.closed.max_runup_percent

**`trades.closed.max_runup_percent([index])`**

The largest rise of closed trade number `index` above its entry price, as a percentage of the value at entry.

- **Effects:** reads the simulated account, so it is not moved across an order call.
- **Phase:** every bar.
- **Cost:** reads the account figure of the bar.
- **Returns:** a number.

#### trades.closed.profit

**`trades.closed.profit([index])`**

The profit of closed trade number `index`, in account money.

- **Effects:** reads the simulated account, so it is not moved across an order call.
- **Phase:** every bar.
- **Cost:** reads the account figure of the bar.
- **Returns:** a number.
- **Examples:** [Trade tally](https://millionchart.com/wiki/scripting/examples/sizing-and-trades#trade-tally).

#### trades.closed.profit_percent

**`trades.closed.profit_percent([index])`**

The profit of closed trade number `index` as a percentage of its value at entry.

- **Effects:** reads the simulated account, so it is not moved across an order call.
- **Phase:** every bar.
- **Cost:** reads the account figure of the bar.
- **Returns:** a number.

#### trades.closed.size

**`trades.closed.size([index])`**

The size of closed trade number `index`: positive for a long trade, negative for a short one.

- **Effects:** reads the simulated account, so it is not moved across an order call.
- **Phase:** every bar.
- **Cost:** reads the account figure of the bar.
- **Returns:** a number.

### Values

- `trades.closed.first_index`

## Open trades reference

Facts about each open trade of the simulated account, by index.

### Functions

#### trades.open.capital_held

**`trades.open.capital_held()`**

The capital (margin) held by the open trades together.

- **Effects:** reads the simulated account, so it is not moved across an order call.
- **Phase:** every bar.
- **Cost:** reads the account figure of the bar.
- **Returns:** a number.

#### trades.open.entry_comment

**`trades.open.entry_comment([index])`**

The comment of the order that opened open trade number `index`.

- **Effects:** reads the simulated account, so it is not moved across an order call.
- **Phase:** every bar.
- **Cost:** reads the account figure of the bar.
- **Returns:** a text.

#### trades.open.entry_index

**`trades.open.entry_index([index])`**

The bar index at which open trade number `index` was entered.

- **Effects:** reads the simulated account, so it is not moved across an order call.
- **Phase:** every bar.
- **Cost:** reads the account figure of the bar.
- **Returns:** a whole number.

#### trades.open.entry_key

**`trades.open.entry_key([index])`**

The key of the order that opened open trade number `index`.

- **Effects:** reads the simulated account, so it is not moved across an order call.
- **Phase:** every bar.
- **Cost:** reads the account figure of the bar.
- **Returns:** a text.

#### trades.open.entry_price

**`trades.open.entry_price([index])`**

The price at which open trade number `index` was entered.

- **Effects:** reads the simulated account, so it is not moved across an order call.
- **Phase:** every bar.
- **Cost:** reads the account figure of the bar.
- **Returns:** a number.

#### trades.open.entry_time

**`trades.open.entry_time([index])`**

The time at which open trade number `index` was entered.

- **Effects:** reads the simulated account, so it is not moved across an order call.
- **Phase:** every bar.
- **Cost:** reads the account figure of the bar.
- **Returns:** a time.

#### trades.open.exit_comment

**`trades.open.exit_comment([index])`**

The comment of the exit of an open trade: always empty, because an open trade has not exited.

- **Effects:** reads the simulated account, so it is not moved across an order call.
- **Phase:** every bar.
- **Cost:** reads the account figure of the bar.
- **Returns:** a text.

#### trades.open.exit_index

**`trades.open.exit_index([index])`**

The exit bar index of an open trade: always na, because an open trade has not exited.

- **Effects:** reads the simulated account, so it is not moved across an order call.
- **Phase:** every bar.
- **Cost:** reads the account figure of the bar.
- **Returns:** na.

#### trades.open.exit_key

**`trades.open.exit_key([index])`**

The key of the exit of an open trade: always empty, because an open trade has not exited.

- **Effects:** reads the simulated account, so it is not moved across an order call.
- **Phase:** every bar.
- **Cost:** reads the account figure of the bar.
- **Returns:** a text.

#### trades.open.exit_price

**`trades.open.exit_price([index])`**

The exit price of an open trade: always na, because an open trade has not exited.

- **Effects:** reads the simulated account, so it is not moved across an order call.
- **Phase:** every bar.
- **Cost:** reads the account figure of the bar.
- **Returns:** na.

#### trades.open.exit_time

**`trades.open.exit_time([index])`**

The exit time of an open trade: always na, because an open trade has not exited.

- **Effects:** reads the simulated account, so it is not moved across an order call.
- **Phase:** every bar.
- **Cost:** reads the account figure of the bar.
- **Returns:** na.

#### trades.open.fees

**`trades.open.fees([index])`**

The fees charged to open trade number `index` so far.

- **Effects:** reads the simulated account, so it is not moved across an order call.
- **Phase:** every bar.
- **Cost:** reads the account figure of the bar.
- **Returns:** a number.

#### trades.open.max_drawdown

**`trades.open.max_drawdown([index])`**

The largest fall of open trade number `index` below its entry price, in account money; shown as a positive number.

- **Effects:** reads the simulated account, so it is not moved across an order call.
- **Phase:** every bar.
- **Cost:** reads the account figure of the bar.
- **Returns:** a number.

#### trades.open.max_drawdown_percent

**`trades.open.max_drawdown_percent([index])`**

The largest fall of open trade number `index` below its entry price, as a percentage of the value at entry.

- **Effects:** reads the simulated account, so it is not moved across an order call.
- **Phase:** every bar.
- **Cost:** reads the account figure of the bar.
- **Returns:** a number.

#### trades.open.max_runup

**`trades.open.max_runup([index])`**

The largest rise of open trade number `index` above its entry price, in account money.

- **Effects:** reads the simulated account, so it is not moved across an order call.
- **Phase:** every bar.
- **Cost:** reads the account figure of the bar.
- **Returns:** a number.

#### trades.open.max_runup_percent

**`trades.open.max_runup_percent([index])`**

The largest rise of open trade number `index` above its entry price, as a percentage of the value at entry.

- **Effects:** reads the simulated account, so it is not moved across an order call.
- **Phase:** every bar.
- **Cost:** reads the account figure of the bar.
- **Returns:** a number.

#### trades.open.profit

**`trades.open.profit([index])`**

The profit of open trade number `index` at the close of the bar, in account money, after its fees and swap.

- **Effects:** reads the simulated account, so it is not moved across an order call.
- **Phase:** every bar.
- **Cost:** reads the account figure of the bar.
- **Returns:** a number.
- **Examples:** [Trade tally](https://millionchart.com/wiki/scripting/examples/sizing-and-trades#trade-tally).

#### trades.open.profit_percent

**`trades.open.profit_percent([index])`**

The profit of open trade number `index` at the close of the bar, as a percentage of its value at entry.

- **Effects:** reads the simulated account, so it is not moved across an order call.
- **Phase:** every bar.
- **Cost:** reads the account figure of the bar.
- **Returns:** a number.

#### trades.open.size

**`trades.open.size([index])`**

The size of open trade number `index`: positive for a long trade, negative for a short one.

- **Effects:** reads the simulated account, so it is not moved across an order call.
- **Phase:** every bar.
- **Cost:** reads the account figure of the bar.
- **Returns:** a number.

## Trade counts reference

Counts of the trades of the simulated account.

### Values

- `trades.closed_count`
- `trades.even_count`
- `trades.lost_count`
- `trades.open_count`
- `trades.won_count`
