# Spectral custom indicators — reference for code generators (schema v3)

This document is complete: everything a Spectral custom indicator file may contain or use is described here.
Human-readable guide: https://spectral.trade/docs/custom-indicators. JSON Schema for the manifest: https://spectral.trade/docs/custom-indicators.schema.json. This file: https://spectral.trade/docs/custom-indicators.llm.md.
Published indicators with their source files: https://spectral.trade/indicators (catalog for code generators: https://spectral.trade/indicators/catalog.llm.md).
License: the example and store indicator files and the type declarations are MIT-0 (free to use, copy, modify and share without attribution; https://spectral.trade/docs/custom-indicators/LICENSE.txt); this reference itself is not. Indicators written for the user belong to the user.

## 0. How to answer

- Check the store first: https://spectral.trade/indicators/catalog.llm.md lists every published Spectral indicator with its source URL.
  If one already does what the user asks, say so and link its page instead of writing code. If one is close, fetch its
  `.js` file and adapt it: give it a new `id`, `name`, `shortName` and `version`, and update its documentation.
  Replace the store file's copyright header with the user's own, or drop it; MIT-0 does not require keeping it.
- Reply with the **complete file** in a single `js` code block, ready to save as `<id>.js` (for example `rsi-bands.js`).
  Do not split it, do not leave placeholders, and do not put explanations inside the code block.
- The user installs it in Spectral with **Indicators → Custom indicators → Add file…**. Spectral checks the file
  against every rule below, test-runs `calculate` once on 300 sample bars (and 300 sample bars of every
  auxiliary series) with the default inputs and every preset, and proves that its live updates equal a full
  recalculation and are fast (§6) before installing it; a rejected file comes back with codes from §12 and their
  fixes, the exact output, bar and values that differed, and the lookback that would work.
- Read §6 (fast live updates) before writing `calculate`: it decides how state and history may be used.
- When you receive such a report, change only what the findings name and return the whole corrected file again.
- Write the documentation fields (§9) as carefully as the code: they become the indicator's info page in Spectral.
- Go through the checklist in §11 before you answer.
- A table on the chart (a dashboard of values, a regime or signal summary) is a `tables` element (schema v3,
  "Drawing elements" in §4); never a plot or a level of text. Text on the chart at a bar (a swing price, a signal
  name) is a `labels` element; a price tag at the right edge is a label with `index: 'right-edge'`.
- A triangle, arrow, flag, cross or letter at a bar (a signal, a fractal, a flip) is a `markers` entry with
  `shape` (schema v3, "Marker shapes" in §4); place it with `placement: 'aboveBar'` or `'belowBar'` instead of
  computing a price offset. A trendline or a line between two bars is a `segments` element; a zone between two
  bars and two prices (a gap, an opening range, a session box) is a `boxes` element.

## 1. What to produce

One JavaScript ES module file (`.js` or `.mjs`, UTF-8, under 256 KiB) whose only export is a default
object literal: the **manifest** (plain literal fields that describe the indicator) plus one synchronous
`calculate(ctx)` method that computes the outputs for every bar.

```js
/** @type {import('./spectral-indicator').IndicatorV3} */
export default {
  schemaVersion: 3,              // 3 is current; files with schemaVersion 1 or 2 still work
  id: 'my-indicator',            // 3-48 chars: lowercase letters, digits, single hyphens, starts with a letter
  name: 'My Indicator',          // <= 80 chars
  shortName: 'MYI',              // <= 20 chars, shown on the chart
  version: '1.0.0',              // <= 20 chars
  author: 'Your name',           // <= 48 chars
  description: 'One sentence.',  // <= 240 chars, shown at the top of the info page
  pane: 'price',                 // 'price' (on the candles) or 'oscillator' (own pane below)
  live: { lookback: 'length' },  // §6: bars read before the forming bar: a number, an integer input with a max, or a sum ('length + 1', '2*length + signal'); 'none' = completed bars only
  usesVolume: false,             // optional: true exposes bar.volume and enables ta.sessionVwap
  inputs: { /* user-editable settings, see §3; give each one a description */ },
  plots: { /* lines, see §4 */ },
  levels: {}, zones: {}, markers: {}, columns: {},
  profiles: { /* optional: volume at price rows, schema v2, see §4 */ },
  auxiliary: { /* optional: daily, weekly or other bar sizes of the same symbol, see §5 */ },
  // optional drawing elements: palettes, tables, labels, barColors, bgColors, segments, boxes ("Drawing elements", §4)
  presets: [],                   // optional variants with different input values, see §8
  docs: {                        // the info page, see §9
    overview: '...',
    howToRead: '...',
    settings: '...',
    notes: '...',
  },
  calculate(ctx) {               // see §5
    return { plots: { /* key: Series */ } };
  },
};
```

## 2. File rules (checked before the manifest)

- Only these top-level statements: `function` declarations, `const` bound to a function or a literal, and the
  single `export default { ... }`. No other statements, no `let`/`var`, no top-level calls.
- No `import`, no `import()`, no `import.meta`, no named exports or re-exports.
- No `async`/`await`, generators, `Promise`, `.then`/`.catch`/`.finally`, a `then` key, `FinalizationRegistry`
  (`E-ASYNC`: nothing may run after `calculate` returns), `debugger`, top-level `this`, `eval` or `new Function`.
- No access to `constructor`, `prototype`, `__proto__`, `__defineGetter__`-style members, `caller` or `callee`.
- No host globals: `globalThis`, `self`, `window`, `global`, `process`, `require`, `module`, `exports`,
  `fetch`, `XMLHttpRequest`, `WebSocket`, `EventSource`, `WebTransport`, `importScripts`, `Worker`,
  `SharedWorker`, `BroadcastChannel`, `MessageChannel`, `indexedDB`, `caches`, `navigator`, `location`,
  `postMessage`, `close`, `addEventListener`, `removeEventListener`, `onmessage`, timers
  (`setTimeout`, `setInterval`, `setImmediate`, `queueMicrotask`, `requestAnimationFrame`), `Atomics`,
  `SharedArrayBuffer`, `WebAssembly`, `crypto`, `performance`. The source check rejects every one of them. The worker
  additionally removes the network, storage, timer, messaging and code-generation globals from its scope as a second
  layer, but not all of the list (for example `globalThis` and `performance` are only rejected by the check), so
  never depend on a global being absent at runtime.
- Allowed: `ctx` (§5), `Math`, `Number`, `Array`, `Object`, `Map`, `Set`, `JSON`, string/array methods and your
  own helpers. `Date`, `Math.random` and writes into a value kept between runs (a top-level value; also through an
  alias, a container, a parameter or its default, a method's `this` or a function that returns it) are an error
  (`E-LIVE-NONDETERMINISTIC`) unless `live: 'none'`, where they only produce a warning; use `ctx.time` for dates
  and times, and create every value inside `calculate`. A write into a built-in (`Math`, `Array`, a built-in
  prototype, …) or to its name (`Math = …`, unless your own `let Math` shadows it) is always an error
  (`E-BUILTIN-WRITE`): every indicator shares them, and at runtime they are frozen and their names read-only.
- ASCII identifiers only; no NUL or bidirectional control characters anywhere in the source.
- Manifest values must be literals: strings, numbers, booleans, arrays and objects without spreads, computed keys,
  function calls or template expressions (`` `a${b}` ``). Only `calculate` is code. A shared helper must be a
  top-level `function` (or a `const` arrow function) that `calculate` calls; it may not be referenced from the manifest.

## 3. Inputs (`inputs`)

Up to 24 entries. Keys are camelCase, start with a lowercase letter, at most 21 characters, and must not
collide with a generated style setting (`<outputKey>Color`, `<zoneKey>Opacity`). Every input needs `type`, `label`
(<= 32 chars) and `default`. Give every input a `description` (<= 240 chars): Spectral lists each input
with its description, default and allowed range on the info page, and warns when one is missing.

| type | default | extra fields | value in ctx.inputs |
| --- | --- | --- | --- |
| `integer` | integer | `min`, `max`, `step` (optional; integer bounds) | number, rounded and clamped to the range |
| `number` | number | `min`, `max`, `step` (optional) | number, clamped to the range |
| `boolean` | boolean |  | boolean |
| `select` | one of `options` | `options`: 1-16 unique strings (<= 32 chars) | string, always one of the options |
| `source` | one of 'open', 'high', 'low', 'close', 'hlc3' |  | string; pass it to `ctx.ta.source(bars, value)` |
| `text` | string |  | string (<= 64 chars) |
| `time` | Unix seconds, `0` for not set |  | number: the moment the user picked (a New York date and time in the settings), or `0`; handle `0` with a fallback such as the session start |

The default must lie inside `min`/`max` and, for `select`, be one of the `options`. Spectral renders inputs as a form in
the indicator's settings panel. Read inputs only through `ctx.inputs`; never hard-code a value that should be an input.

```js
inputs: {
  length: { type: 'integer', label: 'Length', default: 14, min: 2, max: 200, description: 'Number of bars in the RSI lookback.' },
  source: { type: 'source', label: 'Source', default: 'close', description: 'Price used for the calculation.' },
  mode: { type: 'select', label: 'Mode', default: 'classic', options: ['classic', 'smooth'], description: 'Classic uses raw RSI; smooth applies an extra EMA.' },
},
```

## 4. Outputs (what the chart draws)

Declare every output in the manifest; `calculate` must return exactly those keys. Keys are camelCase, start with a
lowercase letter, at most 14 characters, unique across all output families. At least one output is required.
Colors are 6-digit hex (`#RRGGBB`, never 3- or 8-digit and never names like `red`); every color becomes a user setting
named `<key>Color`.

| family | max | manifest entry | calculate returns | notes |
| --- | --- | --- | --- | --- |
| `plots` | 16 | `{ label, color, lineWidth?, lineStyle?, primary?, offset?, gaps? }` | `Series` (one number or null per bar) | Exactly one plot is primary (`primary: true`, or the first). The primary plot takes the indicator's main color/width/style and shows the latest value on the axis. `offset` draws the series that many bars later (positive, into the space right of the last bar) or earlier (negative), see below. `gaps` says what a `null` does to the line, see below. |
| `levels` | 16 | `{ label, color, lineWidth?, lineStyle?, showValue?, labelStyle? }` (`labelStyle`: schema v3) | `number | { price, fromIndex? } | { price, fromTime? } | null` | A horizontal line. A plain number spans the pane; `{ price, fromTime }` starts it at the first bar at or after `fromTime` (Unix seconds, for example `ctx.time.dayStart(bar)`; the left edge when that is before the first bar) and runs to the right edge; `{ price, fromIndex }` starts it at bar `fromIndex` (for example the last bar); `null` hides it. Anchor a level of a day or week by `fromTime` (§6). |
| `zones` | 8 | `{ label, color, opacity?, offset? }` (opacity 0-0.8) | `{ upper: Series, lower: Series }` | Filled band between two series; also gets a `<key>Opacity` setting. `offset` shifts it like a plot. |
| `markers` | 8 | `{ label, color, radius? }` (radius 2-8) | `Array<{ index, value }>` | `index` is a bar index (0-based), `value` the price/level to place the dot at. At most 20,000 per key and 64,000 across all keys (`R-OUTPUT-INVALID` above). Return a dot on every bar its condition holds on, not only the last: one returned only at `bars.length - 1` stays on that bar until the next bar closes, then disappears (`W-LIVE-MARKER`). |
| `columns` | 8 | `{ label, color }` | `Series` | Histogram bars; **oscillator pane only**. Several columns color one histogram (for example rising and falling): per bar, the first declared column with a value is drawn, so give each bar a value in one column and `null` in the others. |
| `profiles` | 4 | `{ label, color, upColor?, opacity?, placement }` (opacity 0-1) | see below | Volume at price as horizontal rows; **price pane and schema v2 only**. Also gets `<key>Opacity` and, with `upColor`, `<key>UpColor` settings. |

`lineWidth` is 0.5-8; `lineStyle` is one of 'solid', 'dashed', 'dotted'.

`offset` (plots and zones) displaces the drawing, not the data: compute the series on the bars as usual and set
`offset: 26` to draw value `i` at bar `i + 26`, so the last 26 values appear in the empty space right of the
last bar (Ichimoku's leading spans), or `offset: -26` to draw it 26 bars earlier (its lagging span). It is a whole
number from -500 to 500, or the key of an integer input that sets it; such an input only moves the drawing,
and `calculate` always sees its default. The key may be negated and adjusted by whole bars, so one input can move
several outputs: `offset: 'displacement'` and `offset: '-displacement'` draw forward and back by the input's
value, `'displacement-1'` and `'-displacement+1'` one bar less (TradingView's Ichimoku counts the current bar).

`gaps` (plots): by default a line joins across `null` values (`'bridge'`), so a sparse series such as a Zig Zag
through a few pivots draws as one line. Set `gaps: 'break'` to end the line at every `null` and start it again at
the next value instead: for example a trend line split into an up plot and a down plot, each `null` while the other
side is active.

`profiles` (schema v2) draw volume at price, for example a volume profile. `placement` picks what
`calculate` returns for the key:
- `'range'`: an array of complete profiles `{ fromIndex, toIndex, rows, valueAreaLow?, valueAreaHigh? }`, each
  drawn inside its own bars from `fromIndex` to `toIndex` (a session, a fixed range). `rows` is an array of
  `{ low, high, volume, up? }` (at most 1000 rows per profile and 16000 over all profiles); `up` is the part of
  `volume` traded on up bars and is drawn in `upColor`. Rows inside the value area are drawn stronger. Draw the
  point of control and the value-area edges as ordinary `levels` (`{ price, fromIndex }`).
- `'visible'`: one object `{ priceLow, rowHeight, rows, valueArea?, bars }` with each bar's volume on one price grid
  (row `r` spans `priceLow + r * rowHeight` to one row higher). `bars` has one entry per bar: `null`, or
  `{ row, volume, up? }` holding that bar's volume in rows `row`, `row + 1`, ... Spectral sums the bars on screen,
  groups the grid rows into `rows` rows and draws the profile at the right edge, so it follows scrolling and zooming
  without recalculating; `valueArea` (a percentage such as 70) marks the value area around the busiest row. Keep all
  `volume` arrays together under 64000 numbers by choosing `rowHeight` from the price range and the bar count.

Choose the pane deliberately: `'price'` for anything measured in price (averages, bands, levels, VWAP, markers on
candles); `'oscillator'` for anything on its own scale (RSI, momentum, z-scores, histograms).

Output rules enforced at runtime (a violation disables the indicator with a readable code, never the chart):
- every `Series` has exactly `ctx.bars.length` entries, in bar order; use `null` where the value is undefined yet;
- non-finite numbers (`NaN`, `Infinity`) are treated as `null`;
- return only declared keys; a declared key may be omitted (drawn as empty);
- marker indexes and a level's `fromIndex` must be within `[0, bars.length)`, prices and values finite;
- a zone needs both `upper` and `lower`, each a full-length series.

### Drawing elements (schema v3)

Schema v3 adds drawing elements: tables, text labels, per-bar candle and background colours, line segments, boxes,
plot styles and marker shapes. **This Spectral version draws every one of them** (and `palettes` for their colours).
New files declare `schemaVersion: 3` (it needs Spectral 1.5.0 or later); files with schemaVersion 1 or 2
keep working unchanged. A schemaVersion 1 or 2 file that uses any drawing element gets `E-ANNOTATION-UNSUPPORTED`.

| manifest field | max | entry | notes |
| --- | --- | --- | --- |
| `palettes` | 8 | `{ label, colors }` (1-8 hex colors) | Named colors elements pick by index (0-based); color N becomes the setting `<key>Color<N+1>`. `palette: '<key>'` on an element must name a declared palette (`E-PALETTE-REF`). |
| `tables` | 4 | `{ label, position, columns, textSize?, font?, color?, textColor?, opacity?, border?, offsetX?, offsetY? }` | `position`: 'top-left', 'top-center', 'top-right', 'middle-left', 'middle-center', 'middle-right', 'bottom-left', 'bottom-center', 'bottom-right' (also the setting `<key>Position`); `columns`: 1-12 `{ align?, width? }` (width 2-32 characters, the least a column takes: a longer cell widens it); offsets 0-200 px. At most 32 rows, 256 cells, 32 characters per cell and 4096 per table. Tables in the same position stack (in indicator order, 4 px apart): top ones downward, bottom ones upward, middle ones as a centred column, all at the first table's offsets; what runs past the pane is cut off. |
| `labels` | 8 | `{ label, color, textColor?, textSize?, font?, style?, placement?, palette?, hideBelowBarWidth?, maxVisible? }` | `style`: 'none', 'box', 'pin', 'arrow'; `placement`: 'above', 'below', 'left', 'right', 'center'; `maxVisible` 1-2000 (default 200). At most 2000 labels per key, 48 characters and 3 lines each, 65536 characters per indicator over the whole history (about 1,365 full tooltips). |
| `barColors` | 2 | `{ label, palette }` | Recolors candles per bar (**drawn**); **price pane only**. |
| `bgColors` | 2 | `{ label, palette, opacity? }` (opacity 0-0.6, default 0.15) | Shades the pane background per bar (**drawn**, price or oscillator pane); also gets a `<key>Opacity` setting. |
| `segments` | 8 | `{ label, color, lineWidth?, lineStyle?, extend?, palette? }` | `extend`: 'none', 'right', 'left', 'both'. At most 2000 per key. |
| `boxes` | 8 | `{ label, color, borderColor?, opacity?, lineWidth?, textSize?, extend?, palette?, hideBelowBarWidth? }` (opacity 0-1, default 0.2) | `extend`: 'none', 'right'. At most 2000 per key, box text 32 characters. Also gets `<key>Color` and `<key>Opacity` settings. |

Schema v3 fields of existing outputs: plots `style?` ('line', 'step', 'circles', 'cross', 'area', 'histogram', **drawn**) and `palette?`
(**drawn**); levels
`labelStyle?` (`'axis'`, the default value-axis chip, or `'inline'`: the label and price on the line at the right
edge, always shown, **drawn**, price pane only); zones `palette?` (**drawn**);
markers `shape?` ('circle', 'square', 'diamond', 'triangleUp', 'triangleDown', 'arrowUp', 'arrowDown', 'cross', 'x', 'flag', 'char'; `'char'` draws the one character in `char`), `size?`
('tiny', 'small', 'normal', 'large'), `placement?` ('absolute', 'aboveBar', 'belowBar'; aboveBar/belowBar price pane only), `palette?` and `hideBelowBarWidth?`
(0-40 px, like labels and boxes): **drawn**, see "Marker shapes" below. Text sizes are 'small', 'normal', 'large', fonts 'mono', 'sans'.
Tables, labels and segments get a `<key>Color` setting (a table only with `color`). Drawing-element keys share the
output key namespace. Schema v3 files also get `ctx.format` (§5) to write numbers as text.

#### Tables

A table is a small grid of text anchored to a corner, an edge or the centre of the indicator's pane (price or
oscillator); it ignores scrolling and zooming, and the user can move it with its `<key>Position` setting.
`calculate` returns, per declared table key, `{ palette?, rows }` or `null` (hidden):

| field | meaning |
| --- | --- |
| `rows` | An array of rows, each an array of cells, at most as many cells as the table has `columns` (a shorter row leaves the rest empty). At most 32 rows and 256 cells. |
| cell | `null` (empty), a string, a number (written like `ctx.format.number`: whole numbers without decimals, others with two), or `{ text, palette?, textPalette?, align?, weight?, tooltip? }`. At most 32 characters per cell and 4096 per table (`R-OUTPUT-TEXT`). |
| `palette` | The declared palette key whose colors the cells' `palette` (background) and `textPalette` (text color) indexes pick, 0-based (`R-OUTPUT-INVALID` for an unknown key or an index past its colors). |
| `weight`, `align` | `'normal'` or `'bold'`; 'left', 'center', 'right' overrides the column's `align` (default `'left'`). |
| `tooltip` | Hover text: at most 48 characters in 3 lines, shown next to the pointer while it is over the cell; it counts against the table's 4096 characters. |

Defaults: background `#161B22` at opacity 0.85, text `#D1D4DC`, `textSize: 'normal'`
(10, 11 or 13 px), `font: 'mono'`, no cell borders (`border: true` draws them). Every drawn string must pass
the identity check manifest text passes: no run of 8 or more hexadecimal characters (`'12345678'`, a hash), no
`U`, `DU` or `F` followed by three or more digits, no 22-character token (`R-TEXT-UNSAFE`, naming the row and
column). Write numbers with `ctx.format` (it groups long integers) instead of `String(value)`. Tab and line-break
characters become spaces and other control characters are dropped.

A table follows the forming bar like every output: on a tick `calculate` runs on the live window (§6) and the
table it returns replaces the last one, so compute its cells from values that hold on that window too (the
latest bar of `ctx.ta` series, not a loop over the whole history), or set `live: 'none'`. The documented example
`examples/regime-table.js` shows the pattern: ADX and EMA slope rows with palette-coloured verdict cells.

#### Labels

A label is a short text anchored to a bar and a value (or a pane edge), drawn on the indicator's pane (price or
oscillator) above its markers. `calculate` returns, per declared label key, an array of labels or `null`:

| field | meaning |
| --- | --- |
| `index` | The bar index (0 to `bars.length - 1`); up to 500 past the last bar draws in the empty space on the right; `'right-edge'` follows the last visible bar (a value tag at the right edge). |
| `value` | The price (or oscillator value) the label points at, or `'top'` / `'bottom'` for the pane edge (kept inside the pane). |
| `text` | At most 48 characters in at most 3 lines (`'\n'` breaks a line); at most 65536 characters for all labels of the indicator over the whole history (`R-OUTPUT-TEXT`); draw text only on bars that matter, never on every bar. |
| `palette` | An index into the label key's declared `palette` for this label's colour (`R-OUTPUT-INVALID` without one or past its colours). |
| `tooltip` | Hover text: at most 48 characters in 3 lines, shown next to the pointer while it is over the label; it counts against the labels' 65536 characters over the whole history. |

`style` draws the text plain (`'none'`: the text in `color`), in a filled box (`'box'`, the default), in a box with a
tail pointing at the anchor (`'pin'`) or in a box with an arrow to it (`'arrow'`); `placement` (default
`'above'`) puts it above, below, left or right of the anchor or centred on it. Boxed text is
`#FFFFFF` unless `textColor` says otherwise. At most `maxVisible` labels of a key (default 200) draw at once,
the newest (rightmost) winning; `hideBelowBarWidth` hides them while bars are narrower than that many pixels. At most
2000 labels per key: return the recent ones (`items.slice(-2000)`). Labels follow the same drawn-text rule
as table cells: write numbers with `ctx.format` (`format.price(high)`).

On a tick the labels of the live window replace the earlier labels of the forming bar; a label on an older bar
changes when the bar it depends on completes. A label that follows the newest bar (a price tag) uses
`index: 'right-edge'`: one anchored at `bars.length - 1` would stay on that bar once the next bar starts, so the
import's live check fails it (`R-LIVE-INEXACT`). Labels that depend on bars to their right (a confirmed swing) or on
the whole history are simplest with `live: 'none'`. The documented example `examples/swing-labels.js` labels each
confirmed swing high and low with its price (`format.price`), coloured by a palette (higher or lower than the last
swing), and draws the latest swing high and low as levels with `labelStyle: 'inline'`.

#### Per-bar colours and plot styles

`result.colors`, `result.barColors` and `result.bgColors` are series like `plots`: one entry per bar, each a
palette index (0-based) or `null` for no colour on that bar (`R-OUTPUT-LENGTH` for a wrong length,
`R-OUTPUT-INVALID` for an index past the palette or a fraction, naming the bar):

| result field | keys | draws |
| --- | --- | --- |
| `colors` | A plot or zone key that declares `palette` | The plot's line (each segment takes the colour of the bar it ends on) or the zone's fill, per bar; `null` keeps the plot's or zone's own `color`. A `'step'` plot's horizontal run sits at the previous bar's value but takes the colour of the bar it steps to: one bar later than Pine Script's stepline, so shift the colours one bar earlier when porting one. |
| `barColors` | A declared `barColors` key | The candle body (and its wick when wicks match bodies in the chart settings), on up and down bars alike; `null` keeps the chart's candle colours. With two keys the first declared one with a colour wins; a later indicator wins over an earlier one. |
| `bgColors` | A declared `bgColors` key | A full-height band behind the bar at the key's opacity (default 0.15, at most 0.6), behind the grid, indicators and candles; `null` leaves the bar unshaded. Bands layer instead of replacing each other: a later declared key paints over an earlier one, a later indicator over an earlier one (unlike `barColors`, where the first declared key wins). |

On the bars that follow the live tick (the forming bar, and the bar that just closed at a rollover), an indicator that
updates on every tick colours candles over one that updates at bar close (`live: 'none'`), and its background band lies
on top, whatever their order on the chart; on every other bar the chart order above applies.

A plot `style` draws its values as `'step'` (horizontal then vertical), `'circles'`, `'cross'`, `'area'` (filled down
to the pane's zero line, clamped to the pane: on the price pane the bottom) or `'histogram'` (bars from the zero line)
instead of a line; `'line'` is the default. All of them follow the live tick like plots: compute the colours from
values that hold on the live window (an EMA comparison, a range of the last `n` bars with `live: { lookback }` covering
it). The documented example `examples/regime-shading.js` shades the price pane by EMA regime (`bgColors`), colours the
fast EMA by the same palette (`colors`), draws the slow EMA as steps and recolours breakout candles (`barColors`).

#### Marker shapes

A marker that declares any schema v3 marker field draws a shape instead of the dot (`radius` then does not apply):
`shape` (default `'circle'`; `'char'` draws the one visible character in `char`), `size` ('tiny', 'small', 'normal', 'large':
6, 9, 12 or 16 px, default `'small'`), `placement` and `hideBelowBarWidth`. `calculate` returns, per marker key, an
array of `{ index, value?, palette?, tooltip? }`:

| field | meaning |
| --- | --- |
| `index` | The bar index (0 to `bars.length - 1`). |
| `value` | Where the shape sits with `placement: 'absolute'` (the default; required then). With `'aboveBar'` or `'belowBar'` (price pane only) Spectral places the shape just above the bar's high or below its low, so leave `value` out. |
| `palette` | An index into the marker's declared `palette` for this marker's colour (`R-OUTPUT-INVALID` without one or past its colours); without it the marker's `color`. |
| `tooltip` | Hover text, at most 48 characters in 3 lines, shown next to the pointer while it is over the shape; at most 65536 characters for all marker tooltips of the indicator over the whole history (about 1,365 full tooltips); put tooltips only on bars that matter, never on every bar. A dot (no shape) ignores it. |

At most 4,000 shape markers per key (a dot key holds 20,000) and 64,000 across all keys (a result past it fails with `R-OUTPUT-INVALID`). Markers follow the live rule of dots: on a tick the markers of the live window
replace the earlier markers of the forming bar. Return a marker on every bar its condition holds on, not only the last
(`R-LIVE-INEXACT` for a shape marker returned only at `bars.length - 1`). The documented example `examples/inside-bar-shapes.js` marks inside bars
with a triangle below the bar and their breakouts with an arrow above or below it, coloured by a palette.

#### Segments and boxes

A segment is a straight line between two bar + value anchors; a box the rectangle they span. Both draw on the
indicator's pane (price or oscillator): boxes below its lines, segments above them, both below the candles.
`calculate` returns, per declared key, an array or `null`:

| field | meaning |
| --- | --- |
| `x1`, `x2` | Bar indexes (0 to `bars.length - 1`, or up to 500 past the last bar, drawn in the empty space on the right); either may be the left one. `x2` may be `'right-edge'`: a box follows the last visible bar (an open zone); a segment ends at the newest loaded bar (a live leg; scrolled back, it runs off the right of the view at the same slope). |
| `y1`, `y2` | The values (prices) at `x1` and `x2`; a box spans from one to the other. |
| `palette` | An index into the key's declared `palette` for this item's colour (`R-OUTPUT-INVALID` without one or past its colours). |
| `text` | Boxes only: one line of at most 32 characters centred in the box (shown when it fits and bars are at least `hideBelowBarWidth` wide); the drawn-text rule of labels applies, at most 65536 characters for all boxes of the indicator over the whole history. |
| `tooltip` | Boxes only: hover text, at most 48 characters in 3 lines, shown next to the pointer while it is over the box; it counts against the boxes' 65536 characters over the whole history. |

`extend` continues a segment along its line to the right (`'right'`), left (`'left'`) or both pane edges, and stretches
a box to the right edge of the pane (`'right'`). A box is filled in its colour at `opacity` (the `<key>Opacity` setting) and
outlined in `borderColor` (default: its own colour); its text is drawn in the chart's text colour at `textSize` (default
`'small'`). At most 2000 segments and 2000 boxes per key: return the recent ones.

An item belongs to the bar of its right anchor: on a tick, the items whose right anchor lies in the live window
replace the earlier ones of those bars, while older items stay as they were (also when they extend right). An item
that follows the newest bar (an open zone, a live leg) ends at `x2: 'right-edge'`: one whose `x2` is
`bars.length - 1` would stay at that bar once the next bar starts (`R-LIVE-INEXACT`). Items
that join confirmed swings, or depend on bars to their right, are simplest with `live: 'none'`. The documented
examples `examples/fair-value-gaps.js` (boxes from a gap's first bar to the bar that filled it, or the right edge
while it is open, labelled with the gap size) and `examples/pivot-trendlines.js` (segments between consecutive
swing highs and lows, the latest ones extended right, and a box over the latest swing range) show both.

#### Tooltips

Labels, boxes, shape markers and table cells may carry a `tooltip`: hover text the chart shows in a small box next to
the pointer while it is over the item (the topmost item wins). It follows the label text rule (at most
48 characters in 3 lines; control and invisible characters are removed, and a run
that looks like an identifier fails with `R-TEXT-UNSAFE`, so write numbers with `ctx.format`). A tooltip never
competes with the chart's own hover: none shows while panning or dragging, while a drawing tool is active, or while the
pointer is over an order line, alert line or drawing. `examples/fair-value-gaps.js` gives every gap box a tooltip with
its size in price and as a percentage of the close, and whether it is filled or still open;
`examples/regime-table.js` explains the regime cell.

#### Draw budget and draw time

The chart limits how many drawing items it draws at once and how long an indicator may take to draw; both are in §7
(Draw budget, Tables, Draw time), with every other runtime limit.

## 5. `calculate(ctx)`

### When it runs

- At every bar close it runs once over the whole loaded history. Unless `live: 'none'`, it then runs again on
  every tick of the forming (not yet closed) bar, on a short window: the last `live.lookback + 1` completed bars
  and the forming bar as the last element of `ctx.bars` (§6). The last bar's high, low, close and volume change
  between calls. With `live: 'none'` it only sees completed bars.
- History length varies from a handful of bars to tens of thousands (scrolling back loads more). Never assume a
  minimum length: with fewer bars than a lookback, return `null` for those positions, never throw.
- Each call is independent. Do not keep state between calls (no top-level `let` or `var`, no writes into
  top-level objects or arrays or into built-ins), and carry values from bar to bar only through `ctx.ta` (§6).
  The import rejects the writes it can trace in the source, and also test-runs a live file's default inputs in a
  freshly loaded copy: a first run after loading that differs from a later run on the same bars is rejected
  (`R-LIVE-INEXACT`).
- It must be synchronous and pure, and its time must grow linearly with the bar count: about 50 ms for
  30,000 bars is the comfortable target. Prefer single passes and the `ctx.ta` helpers over nested loops
  over all bars. Spectral times every call (1000 ms, `calculate` plus the conversion of its result), checks the
  cost at import on many shapes of chart data, and runs custom indicators on workers of their own, showing a file
  still calculating as "Calculating…": §7 has every limit and what happens past it.

### What `ctx` contains (frozen; do not modify it)

- `bars`: array of `{ time, open, high, low, close, volume? }`, **oldest first**. `time` is the bar's open time in Unix
  seconds. `volume` exists only when the manifest sets `usesVolume: true`; it is the traded volume of the bar.
- `inputs`: the declared inputs with defaults applied and numbers clamped (see §3).
- `auxiliary`: the bars of every series declared in the manifest's `auxiliary` field, by alias (see "Bars of
  another bar size" below); `{}` when there are none.
- `barSize`: the chart's bar size, one of '5 secs', '10 secs', '15 secs', '30 secs', '1 min', '2 mins', '3 mins', '5 mins', '10 mins', '15 mins', '20 mins', '30 mins', '1 hour', '2 hours', '3 hours', '4 hours', '8 hours', '1 day', '1 week', '1 month'. Use it only for display-independent logic such as
  scaling a lookback; the indicator must work on every bar size.
- `ta`: bar-aligned helpers. Each returns a new array as long as its input and accepts `null` entries.
  Lengths are floored to integers and clamped to 1-10,000.

| helper | result | first non-null value |
| --- | --- | --- |
| `source(bars, source)` | number per bar for `'open' | 'high' | 'low' | 'close' | 'hlc3'` | bar 0 |
| `sma(values, length)` | simple moving average; a `null` input resets the window | index `length - 1` |
| `ema(values, length)` | exponential average seeded with the first value; nulls carry the last value | **bar 0** (no warm-up; early values are unstable) |
| `rma(values, length)` | Wilder smoothing: average of the first `length` values, then `(prev * (n - 1) + value) / n` | index `length - 1` |
| `wma(values, length)` | linearly weighted average | index `length - 1` |
| `sum`, `highest`, `lowest`, `stdev` `(values, length)` | windowed sum / max / min / population standard deviation; a `null` resets the window | index `length - 1` |
| `change(values, length = 1)` | `value - value[length bars ago]` | index `length` |
| `rsi(values, length)` | Wilder RSI on a 0-100 scale, identical to Spectral's built-in RSI | index `length` |
| `trueRange(bars)` | true range (`high - low` on bar 0) | bar 0 |
| `atr(bars, length)` | `rma(trueRange(bars), length)` | index `length - 1` |
| `sessionVwap(bars)` | volume-weighted average of hlc3, reset on every New York trading date (needs `usesVolume: true`) | first bar with volume |
| `crossover(a, b)`, `crossunder(a, b)` | booleans: `a[i-1] <= b[i-1] && a[i] > b[i]` (crossunder mirrored); `b` may be a series or a number | index 1 |
| `cum(values)` | running total of the finite values; a `null` adds nothing | first finite value |
| `percentRank(values, length)` | percent (0-100) of the previous `length` values at or below the current one (TradingView `percentrank`) | index `length` |
| `scan(items, initial, step)` | carries state from bar to bar: `step(state, item, index)` returns the next state; returns every item's state, each a frozen copy of plain data (null, booleans, numbers, strings up to 64 characters, arrays and plain objects; at most 256 values, 4 levels deep; over a whole run one scan copies at most 2,000,000 values, `R-SCAN-STATE`). Read the bar from `item`, never `ctx.bars[index]`: `index` counts from the first bar of the whole history, also on a live tick (§6). Return `state` itself when nothing changed | bar 0 |

- `time`: `ny(bar)` → `{ dateKey: 'YYYY-MM-DD', weekKey: 'YYYY-MM-DD', minutes }` in New York time (`weekKey` is the New York date of the Monday that starts the bar's week, so every bar of a Monday-to-Sunday week shares it; `minutes` since midnight);
  `isRegularSession(bar)` is true from 09:30 to 16:00 New York time (to 13:00 on NYSE early-close days); `dayStart(bar)` and `weekStart(bar)` are the
  Unix seconds of the New York midnight that starts the bar's day and its week (Monday), for `{ price, fromTime }`
  levels. Use these for session resets and time-of-day logic instead of `Date`.
- `format` (schema v3 files only): deterministic number-to-text helpers for drawn text, with no locale (the same
  text on every machine): `number(value, decimals = 2)` (`1234.5` → `'1234.50'`), `price(value)` (two decimals,
  four below 1), `percent(ratio, decimals = 2)` (`0.0123` → `'1.23%'`), `compact(value)` (`'1.2K'`, `'3.4M'`) and
  `thousands(value)` (`'12,345,678'`). `null`, `NaN` and `Infinity` give `'n/a'`; `decimals` is 0-6. The text never
  holds 8 digits in a row (integer parts from 10,000,000 are grouped), so it passes the text check that `String(12345678)`
  fails.

A typical pattern:

```js
calculate(ctx) {
  const { bars, inputs, ta } = ctx;
  const src = ta.source(bars, inputs.source);
  const basis = ta.sma(src, inputs.length);
  const dev = ta.stdev(src, inputs.length);
  const upper = basis.map((value, i) => (value === null || dev[i] === null ? null : value + inputs.mult * dev[i]));
  const lower = basis.map((value, i) => (value === null || dev[i] === null ? null : value - inputs.mult * dev[i]));
  return { plots: { basis, upper, lower }, zones: { band: { upper, lower } } };
},
```

### Bars of another bar size (`auxiliary`, schema v2)

`ctx.bars` only holds the chart's own bars, and an intraday chart usually loads days or weeks of them: far too little
for a daily EMA 50, a 100-day SMA or anything weekly, and computing such values from intraday bars gives wrong
results. Declare the bars you need instead. With `schemaVersion: 2`, the manifest field `auxiliary` names up to
4 extra series of the chart's symbol at another bar size; Spectral loads them beside the chart's bars (sharing them
with any other indicator or chart that uses the same series) and passes them as `ctx.auxiliary.<alias>`.

```js
auxiliary: {
  daily: { barSize: '1 day', duration: '2 Y' },
  weekly: { barSize: '1 week', duration: '5 Y', when: { all: ['showWeekly'] } },
  monthly: { barSize: '1 month', duration: '5 Y', when: { all: [{ input: 'period', in: ['Monthly', 'Yearly'] }] } },
},
```

| field | required | meaning |
| --- | --- | --- |
| alias (the key) | yes | camelCase, starts with a lowercase letter, at most 14 characters; read as `ctx.auxiliary.<alias>` |
| `barSize` | yes | a bar size of 1 min or longer: '1 min', '2 mins', '3 mins', '5 mins', '10 mins', '15 mins', '20 mins', '30 mins', '1 hour', '2 hours', '3 hours', '4 hours', '8 hours', '1 day', '1 week', '1 month'; or `'chart'` for the chart's own bar size (more history than the chart loaded, for example the same time of day on earlier days; at most `'2 W'`, and no bars on a seconds chart) |
| `duration` | yes | history to load: a count and a unit, for example `'2 Y'` or `'3 W'` (at most `365 D`, `52 W` or `12 M`; use `Y` beyond); at most the limit below |
| `useRth` | no | regular trading hours only; default `true` |
| `whatToShow` | no | market data the bars are built from, one of 'TRADES', 'MIDPOINT', 'BID', 'ASK', 'BID_ASK'; default: the chart's own |
| `keepUpToDate` | no | keep the series updating while the chart is open; default `false` (a snapshot taken when the chart loads). A file that carries values through `ctx.ta` and reads a series kept up to date shows its bar-close values while that series' forming bar changes (the chart says "Updates at bar close"; the import warns with `W-LIVE-HELD`): to update on every tick, leave `keepUpToDate` off, or carry values from the series' completed bars only |
| `when` | no | `{ all?: [...], any?: [...] }` of conditions: load the series only while every `all` condition and at least one `any` condition holds (an `all`-only list also serves as `any`). A condition is the key of a **boolean** input (holds while it is on) or `{ input: '<key>', in: [...] }` for a **select** input (holds while one of the listed options is selected; list declared options only). Use it so a switched-off group or an unselected period loads nothing. Number and text inputs cannot be conditions, and neither can the chart's bar size. |

Longest `duration` per bar size (the window must fit Spectral's cache for that bar size, even for symbols that trade
around the clock):

| barSize | longest duration |
| --- | --- |
| `1 min` | `3 W` |
| `2 mins` | `1 M` |
| `3 mins` | `2 W` |
| `5 mins` | `3 W` |
| `10 mins` | `1 M` |
| `15 mins` | `2 M` |
| `20 mins` | `2 M` |
| `30 mins` | `4 M` |
| `1 hour` | `6 M` |
| `2 hours` | `1 Y` |
| `3 hours` | `1 Y` |
| `4 hours` | `2 Y` |
| `8 hours` | `4 Y` |
| `1 day` | `10 Y` |
| `1 week` | `10 Y` |
| `1 month` | `10 Y` |

What `ctx.auxiliary.<alias>` contains:

- the same frozen bar objects as `ctx.bars` (`volume` only with `usesVolume: true`), **oldest first**; `time` is
  the bar's open time (a daily bar opens at 00:00 New York time on its date);
- every declared alias is present; a series that is switched off by `when` is an empty array. Spectral draws the
  indicator only once every series it needs has arrived (a series that cannot load, for example `ASK` data for an
  index, shows a load error instead), but still handle an empty array: return `null` levels or series, never throw;
- the last bar can be the current, incomplete day, week or hour;
- it is **not** aligned to `ctx.bars`: to use a higher-timeframe value per chart bar, walk both arrays, matching
  daily bars by New York date (`ctx.time.ny(bar).dateKey`) rather than by raw `time`.

```js
calculate(ctx) {
  const { bars, auxiliary, ta, time } = ctx;
  const daily = auxiliary.daily;
  const ema21 = ta.ema(ta.source(daily, 'close'), 21);
  // A level: the latest daily EMA 21, drawn from the last chart bar to the right edge.
  const latest = ema21.length > 0 ? ema21[ema21.length - 1] : null;
  // A series: the previous trading day's close for every chart bar, matched by New York date so
  // pre-market bars (before today's daily bar exists) still get yesterday's close.
  let next = 0;
  const previousClose = bars.map((bar) => {
    const date = time.ny(bar).dateKey;
    while (next < daily.length && time.ny(daily[next]).dateKey < date) next += 1;
    return next >= 1 ? daily[next - 1].close : null;
  });
  return {
    levels: { dailyEma21: latest === null ? null : { price: latest, fromIndex: bars.length - 1 } },
    plots: { previousClose },
  };
},
```

Spectral versions without schema v2 reject a `schemaVersion: 2` file with `E-SCHEMA-VERSION-UNSUPPORTED`; a file
that needs no auxiliary bars may keep `schemaVersion: 1`.

## 6. Fast live updates (`live`) — required reading

Spectral never recomputes the whole history on a tick. At every bar close it runs `calculate` once over all
completed bars and records the state of the `ctx.ta` helpers. On each tick of the forming bar it runs `calculate`
again on a short **window**: the last `live.lookback + 1` completed bars plus the forming bar (two at a bar rollover),
with the `ctx.ta` helpers resuming from the recorded state. The chart takes the window's values from the last
completed bar on. Spectral proves when the file is imported that this live result equals a full recalculation, bit
for bit, and checks it again on real data at every bar close; an indicator that is not exact or not fast updates
at bar close only (the chart shows why and what differed), so write it for the window from the start. The import
checks the default inputs, every preset and every select and boolean option; each integer or number input the
lookback does not name at its `max` on its own; every one at its `max` together; and the inputs the lookback names
at their `min` with every other one at its `max` (an input without a `max` at 10 times its default, at least 100
above it): the lookback must hold for every setting a user can choose. When a Spectral update changes what these
checks prove (exactness), every installed file that updates live is checked again; until it passes, it updates at bar
close. An update that only tightens the cost checks (speed, growth, data shapes) applies to imports and updates of a
file; an installed file keeps the verdict of its last check, and the chart's own runtime budgets still hold it.

Live ticks are timed on the chart too (§7, Live updates): a slow instance updates at bar close for a while. Keep a tick to a fraction of a millisecond: a short `live.lookback` and no loops over many bars.

| `live` | meaning |
| --- | --- |
| omitted | the same as `{ lookback: 0 }` |
| `{ lookback: N }` | on a tick `calculate` sees N completed bars before the forming bar (plus one, the last completed bar, whose value the chart joins). Whole bars, or a sum of whole numbers, integer input keys that have a `max` and `N*key`: `'length'`, `'length + 1'`, `'2*length + signal'` (no subtraction); at most 5,000 bars with those inputs at their max |
| `{ lookback, barCloseWhen }` | live, except under the settings `barCloseWhen` names, which update at bar close only: a boolean input key (while it is on), or `{ input: '<select key>', in: [<some of its options>] }`. Use it for a mode no lookback covers, for example an average over earlier sessions |
| `'none'` | completed bars only; the forming bar never changes the output. Use it for pattern marks and signals that must not appear and disappear while a bar forms (fractals, zig zag), for profiles, and for anything that reads the whole loaded history |

### The rules

1. **Carry values from bar to bar only through `ctx.ta`.** A running total, a trend direction, a trailing stop, a
   streak: `ctx.ta.scan`, `ctx.ta.cum` or a recursive helper (`ema`, `rma`, `rsi`, `atr`, `sma`,
   `sessionVwap`). A variable you update in a loop over `bars` starts from scratch in the window and gives a
   different value live.
2. **Declare how far back you read.** `lookback` is the number of completed bars before a bar that its value needs
   from helpers that do not carry state and from your own index arithmetic (`bars[i - n]`). The table below lists
   each helper's need; take the largest over everything `calculate` reads, and name in it every integer input that
   sets such a length (`'length + smooth'`, not `'length + 3'` for a `smooth` that defaults to 3). Too small fails
   the import with the smallest lookback that works and the inputs the lookback leaves out.
3. **Call the `ctx.ta` helpers the same way on every run:** same order, same lengths, on series as long as
   `ctx.bars`. Do not skip or add a call depending on `bars.length` or on the data, and do not return early before
   a helper call. A helper called on another series (an auxiliary series, a slice or a filtered array) carries no
   state: it reruns over that whole series on every tick, so keep such series short.
4. **`bars.length` is not the history length, and index 0 is not the first bar of the chart** on a live tick.
   Never test `index === 0` of `ctx.bars` or a series, or count bars, to decide anything except warm-up; use the
   helpers' own warm-up (`null`). The exception is the `index` a `ta.scan` step receives: it counts from the first
   bar of the whole history, so `index === 0` there is fine.
5. **Anchor period levels by time:** a level that starts at a bar of the day or week is
   `{ price, fromTime: ctx.time.dayStart(bar) }` (or `weekStart`), never `{ price, fromIndex }` found by searching
   `ctx.bars`: the window does not contain that bar.
6. **No `Date`, no `Math.random`, no values kept between runs** (a top-level object or array that `calculate`
   writes to, such as a cache keyed by bar time, or a value stored on a built-in), nothing that changes
   between two runs on the same bars. Writes the source check can trace are an import error unless
   `live: 'none'` (`E-LIVE-NONDETERMINISTIC`; into a built-in always, `E-BUILTIN-WRITE`); the import test run also compares a freshly loaded copy's first run
   with a run after earlier ones, with the default inputs, and rejects a difference (`R-LIVE-INEXACT`). Create every
   value inside `calculate`.
7. **Bar-close-only modes:** a setting whose values read the whole history (earlier sessions, a median over all bars)
   goes into `barCloseWhen`; a whole indicator like that declares `live: 'none'`. The default inputs and every preset
   must not all fall under `barCloseWhen`: make the default a live setting (a preset may be the bar-close mode), otherwise
   nothing the user adds from the toolbox would update live (`E-LIVE-BAR-CLOSE`).

### Minimum lookback per helper

| helper | bars it needs before the current one |
| --- | --- |
| `ema`, `rma`, `rsi`, `atr`, `sma`, `sessionVwap`, `cum`, `scan` | 0 (their state is recorded at the bar close) |
| `sum`, `stdev`, `wma`, `highest`, `lowest` `(values, length)` | `length - 1` (declare `length`; the grammar has no subtraction) |
| `change(values, length)`, `percentRank(values, length)` | `length` |
| `trueRange(bars)`, `crossover`, `crossunder` | 1 |
| your own `bars[i - n]`, `values[i - n]` | `n` |
| helpers chained (an `sma` of a `stdev`) | the sum of each stateless helper's need |

### `ctx.ta.scan` on a live tick

`step(state, item, index)`: read the bar from `item` (map `ctx.bars` into items first if you need more than the bar),
**never `ctx.bars[index]`**. `index` counts from the first bar of the whole history in every run, so on a live tick it
is not an index into the window's `ctx.bars`; use it only to tell the very first bar of the history (`index === 0`).
Return the state itself when nothing changed: it costs no copy.

### Decision table

| what the indicator does | write it with | `live` |
| --- | --- | --- |
| averages, bands, oscillators of the recent bars | `ctx.ta` helpers | `{ lookback: <largest need> }` |
| a running total (OBV, A/D, cumulative delta) | `ta.cum` or `ta.scan` | `{ lookback: 0 }` (plus any `bars[i - 1]` read: 1) |
| a trailing stop or trend state (Supertrend, Parabolic SAR) | `ta.scan` over items `{ bar, range, previousClose }` | `{ lookback: 1 }` or as read |
| a value that resets each session (session VWAP, opening range) | `ta.sessionVwap`, or `ta.scan` keyed by `ctx.time.ny(item).dateKey` | `{ lookback: 0 }` |
| levels from daily or weekly bars | `ctx.auxiliary` + `{ price, fromTime }` | `{ lookback: 0 }` |
| a rank over the last N values | `ta.percentRank` | `{ lookback: 'length' }` |
| marks confirmed later (fractals, pivots, zig zag), profiles | plain code | `'none'` |
| one mode reads every loaded bar (time-of-day averages) | that mode under `barCloseWhen` | `{ lookback, barCloseWhen }` |

### Wrong → right

```js
// OBV (usesVolume: true). Wrong: a running total in your own variable restarts in the live window.
let total = 0;
const obv = bars.map((bar, i) => (total += i > 0 ? Math.sign(bar.close - bars[i - 1].close) * bar.volume : 0));
// Right: ta.cum carries it (live: { lookback: 1 } for the bars[i - 1] read; the first bar contributes 0).
const moves = bars.map((bar, i) => (i > 0 ? Math.sign(bar.close - bars[i - 1].close) * (bar.volume ?? 0) : 0));
const obv = ta.cum(moves);
```

```js
// Supertrend. Wrong: bands and direction in let variables updated inside a loop over bars.
// Right: one ta.scan state over items that carry what each step reads (live: { lookback: 1 }, for previousClose).
const atr = ta.atr(bars, inputs.atrLength);
const items = bars.map((bar, i) => ({ bar, range: atr[i], previousClose: i > 0 ? bars[i - 1].close : null }));
const states = ta.scan(items, { upper: null, lower: null, up: true }, (state, { bar, range, previousClose }) => {
  if (range === null) return state;
  const middle = (bar.high + bar.low) / 2;
  const basicUpper = middle + inputs.factor * range;
  const basicLower = middle - inputs.factor * range;
  const upper = state.upper === null || basicUpper < state.upper || previousClose > state.upper ? basicUpper : state.upper;
  const lower = state.lower === null || basicLower > state.lower || previousClose < state.lower ? basicLower : state.lower;
  return { upper, lower, up: state.up ? bar.close >= lower : bar.close > upper };
});
```

```js
// Percent rank. Wrong: counting over values.slice(i - length, i) by hand without declaring the lookback.
// Right: ta.percentRank, live: { lookback: 'length' }.
const rank = ta.percentRank(ta.source(bars, 'close'), inputs.length);
```

```js
// Session VWAP (usesVolume: true). Wrong: sums reset with `if (date !== lastDate)` on variables outside the loop.
// Right: the session state in a scan keyed by the New York date (live: { lookback: 0 }).
const states = ta.scan(bars, { date: '', weight: 0, sum: 0 }, (state, bar) => {
  const date = time.ny(bar).dateKey;
  const base = date === state.date ? state : { date, weight: 0, sum: 0 };
  const volume = bar.volume ?? 0;
  return { date, weight: base.weight + volume, sum: base.sum + volume * (bar.high + bar.low + bar.close) / 3 };
});
const vwap = states.map((state) => (state.weight > 0 ? state.sum / state.weight : null));
```

```js
// Previous day's high. Wrong: searching ctx.bars for the first bar of today and drawing { price, fromIndex }.
// Right: daily bars from auxiliary and a level anchored by time (live: { lookback: 0 }).
const daily = auxiliary.daily;
const yesterday = daily.length >= 2 ? daily[daily.length - 2] : null;
const levels = { pdh: yesterday && bars.length > 0 ? { price: yesterday.high, fromTime: time.dayStart(bars[bars.length - 1]) } : null };
```

## 7. Performance and limits

Spectral keeps the chart smooth whatever an indicator does: a file that is too slow or draws too much loses only its
own updates or drawing, never the candles, the built-in indicators or other indicators. Every limit below is
measured while the app runs or checked when the file is imported; nothing here changes what a file may declare
(§1–§4 have those limits). Built-in indicators are never limited by these budgets.

### At a glance

| what | limit | past it |
| --- | --- | --- |
| One `calculate` call plus Spectral's conversion of its result | 1,000 ms | Those settings are turned off at that bar size for the app session (the chart says why). |
| A call that never returns | 30 s | Cut off (`R-TIMEOUT`). |
| A full run at import: the default inputs and every preset on 30,000 bars, and every data shape, also with every input at its max | 250 ms, growing no faster than the bars | The import rejects the file (`R-SLOW`). A `calculate` that throws on any data shape is rejected too (`R-THROW`). |
| Drawn text: marker tooltips, labels and boxes, each, over the whole history | 65,536 characters (about 1,365 full tooltips) | The import rejects the file (`R-OUTPUT-TEXT`). It checks 30,000 bars and scrolling back can hold more, so draw text only on bars that matter, never on every bar. |
| Custom indicators of one request | 3 s, cheapest first | The rest show "Calculating…" and follow in the next request. |
| Values one result returns (points, colours, markers, labels, boxes, segments, cells) | 600,000 | The import rejects the file (`R-OUTPUT-INVALID`); on a chart, that indicator alone shows "Too much indicator output". |
| Dot markers per key / shape markers per key (schema v3) / all keys | 20,000 / 4,000 / 64,000 | `R-OUTPUT-INVALID` |
| State one `ctx.ta.scan` copies over a whole run | 2,000,000 values | `R-SCAN-STATE` |
| A live tick | 4 ms on average over 32 ticks, 12 ms at the 95th percentile, 50 ms | Updates at bar close for a while (`R-LIVE-SLOW`), then live again. |
| Drawn at once per indicator / per pane | 3,000 / 12,000 items | The newest items in view are drawn, the rest wait. |
| Tables shown per pane | 16 | The indicators added last show none. |
| Draw time per indicator / per pane | 3 ms per frame on average (8 ms on slow frames) / 12 ms | Drawn reduced (Throttled), then hidden (Hidden); re-checked every 30 s. |

### Calculation time

- A call above 1,000 ms (`calculate` plus Spectral's conversion of its result, so a huge result counts too)
  turns those settings off at that bar size for the app session, worker restarts included; other settings, another bar
  size or a new file version are measured anew. A hang is cut off after 30 s.
- The import times a full run with every setting a user can choose, every input at its max included: at most
  250 ms, and its time must grow linearly with the bar count (a schema v3 file's full run may be at most
  4.5 times a quarter-size run, a v1/v2 file's 6 times; about 50 ms for 30,000 bars is the comfortable target).
- It also times a full run on other shapes of chart data, each within 250 ms: daily bars over 30 years,
  five-minute extended-hours bars with weekends, halts and zero-volume runs, one-minute bars of a $700 and a $3
  stock, and combinations of the boolean and select inputs (every pair of their values, up to 24 combinations, with
  every number input at its max). Its cost must not depend on `ctx.barSize`, the price level (no loop over price
  steps), gaps in time (no loop over calendar minutes) or an option.
- These checks apply when a file is imported or updated; an installed file keeps the verdict of its last check, and
  the runtime budgets on this page still hold it. A stricter check in a Spectral update (the v3 growth ratio of 4.5
  was 6) applies to the next import or update of a file, never to an installed one.

### Workers ("Calculating…")

Custom indicators run on two workers of their own, never beside the built-in indicators: a slow file delays only
custom indicators. Each indicator stays on its worker, so its live updates keep their state. The chart draws the
built-ins (and every custom indicator already done) at once and shows a file still calculating as loading
("Calculating…") until it is done. One request spends at most 3 s on custom indicators, the cheapest first; the
rest follow in the next request, still shown as loading, never as failed.

### Output size and memory

- One result may return at most 600,000 values: every point of every plot, zone edge and per-bar colour series,
  every marker, label, box, segment and table cell. That is 20 series on the longest chart of 30,000 bars (10
  plots that each colour every bar). The import counts the result of its full runs with every number input at its
  max (every data shape and option combination above) and rejects a file past it (`R-OUTPUT-INVALID`); on a chart,
  that indicator alone shows "Too much indicator output", and built-in indicators are always taken first. A file
  installed before this check keeps its verdict and meets the limit on the chart only. A `null` value still counts
  as a point.
- Markers: at most 20,000 dots per key, 4,000 shape markers per key (schema v3), and 64,000 across all keys
  (`R-OUTPUT-INVALID`). Labels, boxes and segments: 2,000 per key; text caps as in §4.
- `ctx.ta.scan`: a state of at most 256 values, and at most 2,000,000 copied values per scan over a whole run
  (`R-SCAN-STATE`); a step that returns its state unchanged copies nothing.
- The chart keeps the results of closed charts for a quick return within a memory budget and lets the least recently
  shown go first; the data of every open chart is always kept.

### Live updates

Live ticks are timed on the chart too, the chart's own work to take in each update included. An instance whose last 32 ticks take more than 4 ms on average, whose 95th
percentile is above 12 ms (two of 32) in two windows of 32 ticks in a row, or that takes more than 50 ms twice in a row
updates at bar close from its next tick (`R-LIVE-SLOW`, with the measured time). Spectral tries live updates again after 10 bars; each further slow pause lasts twice as long (20, 40
... 640 bars), and after that the instance updates at bar close for the rest of the session. A clean stretch of live
bars as long as the last pause steps that back again, so a busy moment of the computer never parks a file for good. Keep a tick to a fraction of a millisecond: a short `live.lookback` and no loops over many bars.

### Draw budget

Your indicator's data is always kept in full; the chart only limits what it draws at once, so that no indicator can
slow the candles, the built-in indicators or other indicators down. Per indicator and frame it draws at most
3000 markers, labels, boxes and segments together, and all custom indicators of one pane together at most
12000; past that, the indicators added to the pane last draw less first. The settled bars and the live
update of the forming bar are drawn separately, each within these budgets. The newest items in view are kept, so while
you pan, the oldest drawn items give way to those coming into view. Per kind:

| kind | drawn at once | which ones |
| --- | --- | --- |
| markers (dots and shapes, every key together) | 2000 | The newest within reach of the view that can draw (a marker without a value, or hidden by `hideBelowBarWidth`, does not count; one above or below the visible prices does), older ones first so the newest sit on top. |
| labels (every key together) | 400 | Each key first keeps its newest `maxVisible` that fit the pane; then the newest across keys. |
| boxes (every key together) | 256 | The newest (by right anchor) that show in the view; a box whose fill covers 90 % of the pane or more counts as 4. |
| segments (every key together) | 512 | The newest (by right anchor) that show in the view. |

An indicator under its budget draws exactly as before. Looking for the newest boxes and segments that show, the chart
passes over at most four times the kind's budget of newer ones that do not (outside the visible prices, or on bars not
loaded); older ones are then not drawn, so drop items that left the chart's range rather than keep returning them.
Each label's text is measured once, when it is first drawn; `hideBelowBarWidth` hides dense markers and labels when
the chart is zoomed out (hidden ones leave the budget to the rest; on boxes it hides only the text).

### Tables

One pane shows at most 16 tables of all its indicators together, the first in the pane's indicator order (the
indicators added last give way). Tables at the same position stack (§4). A shown table is painted once per new output
and only copied onto the chart on other frames; when its output changes, only the cells whose text changed are
measured again.

### Draw time

The chart also measures how long your indicator takes to draw. When it takes more than 3 ms per frame on average
(or more than 8 ms on slow frames), or the custom indicators of a pane take more than 12 ms together (then
the one that took the most of that frame gives way first), it is drawn reduced, one step at a time:

| step | legend | what is drawn |
| --- | --- | --- |
| 1 | Throttled | Half of each budget above. |
| 2 | Throttled | As step 1; shapes are drawn as plain dots, labels and box text are left out, and tables keep their last content. |
| 3 | Hidden | Nothing. Its values are still calculated, so it can come back. |

The legend badge's tooltip, the indicator's settings and its row in the toolbox say what it cost against which limit.
Every 30 s the chart tries the next step up again for 30 frames and keeps it while the indicator draws in under
1.5 ms (every 5 min once it went up and down three times within that
time); an indicator that draws on the chart's still layer (shapes, labels, boxes, segments, colours) must also draw fast
there for a few redraws of that layer (after a scroll or a new bar) before it steps up; **Retry now** draws it in full at once. The times are measured on the machine as it runs, so a heavily loaded
computer (other programs, many charts at once) can reduce an indicator for a while; it goes back to full drawing on
its own once it draws fast enough again. The step is remembered across restarts for the file version, settings
and kind of pane, for up to 30 days, and checked again in the first frames of each session (the reason
shows the date it was measured); a new version of the file or other settings start from full drawing. Built-in
indicators are never reduced.

### Best practices

- Calculate in one pass over the bars with the `ctx.ta` helpers; never loop over all bars inside a loop over bars,
  over price steps or over calendar time.
- Return drawing items only where they matter: a marker or label on a signal, not on every bar; the boxes and segments
  that are still relevant (open zones, the latest swings), not every one since the first bar.
- Keep `maxVisible` small and use `hideBelowBarWidth` so dense markers and labels hide when the chart is zoomed out.
- Prefer one coloured plot over many plots; colour series count against the 600,000 values like points.
- Keep tables small (a few rows) and change only the cells whose value changed; change label and box text only when
  its value changes.
- Keep a live tick short: a small `live.lookback`, and `live: 'none'` for anything that reads the whole history.
- Keep a `ctx.ta.scan` state to a few numbers and return the same state object when nothing changed.

## 8. Presets

`presets` (up to 8): `{ id, name, shortName, inputs }` where `id` is a lowercase slug (<= 24 chars, unique) and
`inputs` only names declared inputs with values of the right type and range. Each preset appears in the toolbox as
its own entry (for example "RSI BB (fast)") and shares the info page of the indicator.

## 9. The info page (documentation)

Every indicator in Spectral has an info page, opened from the ⓘ button in the Indicators toolbox. For a custom
indicator it is built from the manifest:

| Info page part | Comes from | What to write |
| --- | --- | --- |
| Title and short name | `name`, `shortName` | A clear name; a short name of a few characters for the chart legend. |
| "At a glance" | `description` | One sentence: what the indicator shows. |
| "Overview" | `docs.overview` (required) | What it computes and from what, in plain words; the formula if it is short. |
| "How to read it" | `docs.howToRead` | How a trader interprets the lines, levels, zones, colors and markers; typical situations; what it does not tell you. |
| "Settings and limitations" | `docs.settings` | What each important input changes and sensible ranges; warm-up (bars before values appear); bar sizes or sessions it suits; known limits. |
| "What it draws" | generated from the outputs | Nothing to write: use clear `label`s on every plot, level, zone, marker and column. |
| "Notes" | `docs.notes` | Anything else worth knowing, for example sources or differences from other platforms. |
| "Options" | each input's `label`, `description`, `default`, range or options, plus the color settings | A description for every input. |
| "About this indicator" and the author line | `author`, `version`, `live`, `usesVolume` | Nothing extra; Spectral words it. |

Each `docs` field is plain text up to 2000 characters; a blank line starts a new paragraph. Write for a trader, not a
programmer: no code, no variable names, no Markdown. Spectral warns (`W-DOCS-MISSING`, `W-DOCS-INCOMPLETE`) when the
overview, `howToRead`, `settings` or an input description is missing.

Text fields must not look like identifiers or secrets: no run of 22 or more letters/digits without a space, no
account-like tokens (`U1234567`, `DU...`, `acct_...`) and no hashes.

```js
docs: {
  overview: 'Bollinger Bands around a simple moving average of the chosen source. The bands sit the selected number of standard deviations above and below the average.',
  howToRead: 'Price near the upper band is strong relative to recent volatility; near the lower band, weak. Narrow bands mark quiet periods that often precede larger moves.\n\nA close outside a band is not a reversal signal by itself; confirm with price structure.',
  settings: 'Length sets the averaging window (20 is common); a longer window smooths more and reacts later. Multiplier sets the band width. The first values appear after Length bars.',
  notes: 'Uses population standard deviation, like most charting platforms.',
},
```

## 10. Common mistakes

| Mistake | Code | Fix |
| --- | --- | --- |
| `import` of a library (for example a TA package) | `E-IMPORT` | Use `ctx.ta` or write the helper as a top-level function. |
| `let`/`var` or a call at top level | `E-TOP-LEVEL-STATEMENT` | Move state into `calculate`; top level holds only functions and constant literals. |
| `async calculate`, `await`, `Promise` or `.then` | `E-ASYNC` | Make `calculate` synchronous; nothing may run after it returns. |
| A template literal, spread or function call in the manifest | `E-MANIFEST-NOT-LITERAL` | Write the value out as a plain literal. |
| A manifest key that does not exist (for example `overlay` or `category`) | `E-MANIFEST-KEY-UNKNOWN` | Use only the keys in §1. |
| A daily or weekly value computed from the chart's intraday bars | none (wrong values) | Declare an `auxiliary` series of that bar size and read `ctx.auxiliary.<alias>` (§5). |
| `auxiliary` with `schemaVersion: 1` | `E-AUX-UNSUPPORTED` | Set `schemaVersion: 2`. |
| An `auxiliary` `when` that names a number, text, time or source input, or a select input as a bare key | `E-AUX-WHEN` | Name boolean inputs as keys and select inputs as `{ input, in: [<options>] }`. |
| `inputs`, `plots` or another output family written as an array | `E-INPUT-KEY-INVALID`, `E-PLOT-KEY-INVALID` | Write them as objects keyed by name: `inputs: { length: { ... } }`. |
| Colors like `red`, `#fff` or `#RRGGBBAA` | `E-COLOR-INVALID` | Use 6-digit `#RRGGBB`; transparency is the zone `opacity`. |
| An input called `<plot>Color` or `<zone>Opacity` | `E-KEY-COLLISION` | Rename the input; those names are generated color settings. |
| Two plots with `primary: true` | `E-PLOT-PRIMARY` | Mark at most one plot as primary. |
| `columns` on the price pane | `E-OUTPUT-PANE-MISMATCH` | Use `pane: 'oscillator'` or a plot instead. |
| `profiles` on the oscillator pane, or with `schemaVersion: 1` | `E-OUTPUT-PANE-MISMATCH`, `E-PROFILE-UNSUPPORTED` | Use `pane: 'price'` and `schemaVersion: 2`. |
| A `markers` entry with `placement: 'aboveBar'` or `'belowBar'` on the oscillator pane | `E-OUTPUT-PANE-MISMATCH` | Use `pane: 'price'`, or `placement: 'absolute'` with a `value` on the oscillator's scale. |
| A `visible` profile whose bins exceed the budget | `R-OUTPUT-INVALID` | Choose a larger `rowHeight` (for example the price range divided by 2,000, and at least the average bar range divided by 2). |
| More than about 20 plots, zone edges and colour series on a long chart | `R-OUTPUT-INVALID` at import (an installed file: the chart shows "Too much indicator output") | One indicator may return at most 600,000 values (points, markers, labels, boxes, segments, cells): 20 series on the longest chart of 30,000 bars. The import counts its full runs with every number input at its max. Built-in indicators are always drawn first; custom indicators share what is left. Return fewer series (a `null` value still counts as a point). |
| A select default that is not one of its options, or a default outside min/max | `E-INPUT-DEFAULT-INVALID` | Pick a default inside the allowed values. |
| A series shorter than `bars` (for example `slice(length)`) | `R-OUTPUT-LENGTH` | Keep one entry per bar; put `null` in the warm-up positions. |
| Returning a key not declared in the manifest | `R-OUTPUT-INVALID` | Declare it, or remove it from the result. |
| Reading `bar.volume` without `usesVolume: true` | `W-VOLUME-UNDECLARED` | Set `usesVolume: true`; otherwise volume is undefined. |
| Nested loops over all bars (`O(n²)`) | `R-SLOW` | Use rolling windows or `ctx.ta` helpers. A full run must grow linearly with the bar count, `live: 'none'` files too: 30,000 bars in about 50 ms is the comfortable target; a slower run passes only if it grows no faster than the bars, up to 250 ms with every input at its max (lower the max of inputs that set long windows). |
| A running total, trend or stop kept in your own variable across a loop over `bars` | `R-LIVE-INEXACT` | Carry it in `ta.scan` or `ta.cum` (§6). |
| `live.lookback` smaller than what `calculate` reads | `R-LIVE-INEXACT` | Set it to at least the lookback the report names (the helper table in §6). |
| `ctx.bars[index]` inside a `ta.scan` step | `R-LIVE-INEXACT` | Read the bar from `item`; map the bars to items first if the step needs more. |
| A level found by searching `ctx.bars` for the first bar of a day (`{ price, fromIndex }`) | `R-LIVE-INEXACT` | Use `{ price, fromTime: ctx.time.dayStart(bar) }`. |
| `ctx.ta` calls that depend on `bars.length` or on the data | `R-LIVE-STATE` | Call the helpers the same way on every run; mask their results instead. |
| `Date` or `Math.random` in a live indicator | `E-LIVE-NONDETERMINISTIC` | Use `ctx.time`, or `live: 'none'`. |
| A cache kept between runs (`const memo = {}` at the top, written by `calculate`) | `E-LIVE-NONDETERMINISTIC` | Create the value inside `calculate`; carry values from bar to bar with `ta.scan`. |
| A value kept between runs the source check cannot trace (reached through a computed name, say) | `R-LIVE-INEXACT` | Create the value inside `calculate`: the import compares a freshly loaded copy's first run with a later run on the same bars. |
| Thin documentation | `W-DOCS-INCOMPLETE` | Fill `docs.howToRead`, `docs.settings` and every input description (§9). |

## 11. Checklist before you answer

1. One file, one `export default { ... }`, `schemaVersion: 3`, a valid `id`, all required text fields.
2. No imports, no async, no globals from §2; top level holds only functions and literal constants.
3. Every manifest value is a literal; every color is `#RRGGBB`.
4. Every input has `type`, `label`, `default` inside its range or options, and a `description`.
5. Every output the code returns is declared; every series has `bars.length` entries with `null` for warm-up.
6. The pane fits the scale of the values; `columns` only on `'oscillator'`, `profiles` only on `'price'`.
7. `usesVolume: true` if `bar.volume` or `ta.sessionVwap` is used.
8. `docs.overview`, `docs.howToRead` and `docs.settings` are written for a trader (§9).
9. `calculate` handles short histories and runs in a single pass.
10. Higher-timeframe values come from declared `auxiliary` series (with a `duration` inside its limit), and
    `calculate` handles an empty series.
11. Fast live updates (§6): `live` is declared (`{ lookback }` covering every helper's need from the table, or
    `'none'`); values carried from bar to bar go through `ta.scan`, `ta.cum` or a recursive helper; scan steps
    read `item`, not `ctx.bars[index]`; the `ctx.ta` calls are the same on every run; day and week levels use
    `fromTime`; no `Date`, `Math.random` or top-level value that `calculate` writes to; a mode that reads the
    whole history is in `barCloseWhen`.
12. A table or labels: `schemaVersion: 3`, declared under `tables` with its `columns`, cells no longer than the cap,
    numbers written with `ctx.format`, palette indexes inside the declared palette. Labels: `schemaVersion: 3`,
    declared under `labels`, at most 2000 per key (`slice(-2000)`), texts within 48 characters and
    3 lines, numbers written with `ctx.format`, text and tooltips only on bars that matter, never on every bar (marker tooltips, labels and boxes are each limited to 65,536 characters over the whole history (about 1,365 full tooltips); the import checks 30,000 bars and scrolling back can hold more). Marker shapes: `schemaVersion: 3`, `char` only with
    `shape: 'char'`, `palette` indexes only with a declared `palette` on the marker. Segments and boxes:
    `schemaVersion: 3`, at most 2000 per key (`slice(-2000)`), box text one line within 32 characters.
13. The answer is the complete file in one code block.

## 12. Error and warning codes

Spectral reports these with a line/column where it applies. Errors block installation; warnings do not.

### File and module structure

| Code | Meaning | Fix |
| --- | --- | --- |
| `E-FILE-NOT-REGULAR` <a id="e-file-not-regular"></a> | Not a regular file | Pick a plain .js file on disk. |
| `E-FILE-EXTENSION` <a id="e-file-extension"></a> | Unsupported file extension | Save the indicator as a .js or .mjs file. |
| `E-FILE-TOO-LARGE` <a id="e-file-too-large"></a> | File too large | Keep the file under 256 KiB; remove data tables or generated code. |
| `E-FILE-EMPTY` <a id="e-file-empty"></a> | File is empty | The file must contain a default export. |
| `E-FILE-ENCODING` <a id="e-file-encoding"></a> | File is not UTF-8 | Save the file as UTF-8 text. |
| `E-SOURCE-BIDI` <a id="e-source-bidi"></a> | Hidden control characters | Remove NUL and bidirectional control characters from the source. |
| `E-SOURCE-MISSING` <a id="e-source-missing"></a> | Source file missing | The original file was moved or deleted; re-import it from its new location. |
| `E-SYNTAX` <a id="e-syntax"></a> | Syntax error | Fix the JavaScript syntax error at the reported position. |
| `E-AST-TOO-COMPLEX` <a id="e-ast-too-complex"></a> | Source too complex | Reduce nesting depth and total size of the file. |
| `E-IDENT-NON-ASCII` <a id="e-ident-non-ascii"></a> | Non-ASCII identifier | Use ASCII letters, digits and underscores in identifiers. |
| `E-IMPORT` <a id="e-import"></a> | Imports are not allowed | Remove the import and inline the helper into the file. |
| `E-IMPORT-DYNAMIC` <a id="e-import-dynamic"></a> | Dynamic import is not allowed | Remove the import() call. |
| `E-IMPORT-META` <a id="e-import-meta"></a> | import.meta is not allowed | Remove the import.meta reference. |
| `E-EXPORT-NAMED` <a id="e-export-named"></a> | Only a default export is allowed | Remove named exports and re-exports; keep a single export default. |
| `E-EXPORT-DEFAULT-MISSING` <a id="e-export-default-missing"></a> | Exactly one default export is required | Add `export default { ... }` with the manifest and calculate. |
| `E-EXPORT-DEFAULT-SHAPE` <a id="e-export-default-shape"></a> | Default export must be an object literal | Export a plain object literal directly: `export default { schemaVersion: 3, ... }`. |
| `E-TOP-LEVEL-STATEMENT` <a id="e-top-level-statement"></a> | Unsupported top-level statement | Keep only function declarations, const helpers and the default export at top level. |
| `E-ASYNC` <a id="e-async"></a> | Async code is not allowed | Remove async/await, generators, Promise, .then/.catch/.finally, thenables and FinalizationRegistry; calculate must be synchronous and nothing may run after it returns. |
| `E-DEBUGGER` <a id="e-debugger"></a> | debugger is not allowed | Remove the debugger statement. |
| `E-THIS-TOP` <a id="e-this-top"></a> | Top-level this is not allowed | Do not reference `this` outside functions. |
| `E-CODEGEN` <a id="e-codegen"></a> | Code generation is not allowed | Remove eval and Function constructor usage. |
| `E-FORBIDDEN-GLOBAL` <a id="e-forbidden-global"></a> | Forbidden global | Indicator code may only use ctx, Math and plain JavaScript; remove the global reference. Your own variable may reuse a name like close or fetch if you declare it in the scope that uses it, but not self, globalThis, window, performance or crypto: rename those. |
| `E-UNDECLARED-IDENTIFIER` <a id="e-undeclared-identifier"></a> | Undefined name | Declare the name with const inside calculate (top level allows only const helpers, as functions or literal values), or fix the typo; it would throw a ReferenceError when calculate runs. |
| `E-PROTOTYPE-ACCESS` <a id="e-prototype-access"></a> | Prototype access is not allowed | Remove constructor/prototype/__proto__ member access. |
| `E-BUILTIN-WRITE` <a id="e-builtin-write"></a> | Writes to a built-in are not allowed | Do not write from calculate into a built-in (Math, Array, Object, a built-in prototype, …): every indicator shares them. Create every value inside calculate, or change a copy (such as .slice().sort()). |
| `E-MANIFEST-KEY-UNKNOWN` <a id="e-manifest-key-unknown"></a> | Unknown manifest key | Remove the key or check its spelling against the manifest reference. |
| `E-MANIFEST-NOT-LITERAL` <a id="e-manifest-not-literal"></a> | Manifest value must be a literal | Write manifest values as plain literals (strings, numbers, booleans, arrays, objects); no expressions or functions. |
| `E-CALCULATE-MISSING` <a id="e-calculate-missing"></a> | calculate is missing | Add a synchronous `calculate(ctx) { ... }` method to the default export. |
| `E-CALCULATE-SHAPE` <a id="e-calculate-shape"></a> | calculate has the wrong shape | calculate must be a synchronous function taking one parameter (ctx). |
| `E-MANIFEST-KEY-MISSING` <a id="e-manifest-key-missing"></a> | Required manifest key missing | Add the missing key. |
| `E-PROFILE-UNSUPPORTED` <a id="e-profile-unsupported"></a> | Profiles need schemaVersion 2 | Set `schemaVersion: 2` to draw volume profiles, or remove the profiles field. |
| `E-FORMAT-UNSUPPORTED` <a id="e-format-unsupported"></a> | ctx.format needs schemaVersion 3 | Set `schemaVersion: 3` to write numbers with ctx.format, or build the text without it. |

### Manifest rules

| Code | Meaning | Fix |
| --- | --- | --- |
| `E-SCHEMA-VERSION-INVALID` <a id="e-schema-version-invalid"></a> | Invalid schemaVersion | Set `schemaVersion: 3`. |
| `E-SCHEMA-VERSION-UNSUPPORTED` <a id="e-schema-version-unsupported"></a> | schemaVersion needs a newer Spectral | Update Spectral, or ask for a schemaVersion 3 file. |
| `E-ID-INVALID` <a id="e-id-invalid"></a> | Invalid id | Use 3-48 lowercase letters, digits and single hyphens, starting with a letter. |
| `E-ID-EXISTS` <a id="e-id-exists"></a> | An indicator with this id already exists | Change the id, or replace the existing indicator. |
| `E-TEXT-INVALID` <a id="e-text-invalid"></a> | Invalid text field | Provide a non-empty string within the length limit. |
| `E-TEXT-UNSAFE` <a id="e-text-unsafe"></a> | Text looks like an identifier or hash | Avoid long hexadecimal or alphanumeric runs and account-like tokens in text fields. |
| `E-PANE-INVALID` <a id="e-pane-invalid"></a> | Invalid pane | Set pane to 'price' or 'oscillator'. |
| `E-LIVE-INVALID` <a id="e-live-invalid"></a> | Invalid live mode | Set live to { lookback: <bars calculate reads before the forming bar> } or 'none', or omit it. |
| `E-LIVE-LOOKBACK` <a id="e-live-lookback"></a> | Invalid live lookback | Write live.lookback as whole bars or a sum of whole numbers and integer inputs that have a max (e.g. 'length + 1' or '2*length'), at most 5,000 bars with those inputs at their max. |
| `E-LIVE-NONDETERMINISTIC` <a id="e-live-nondeterministic"></a> | Non-deterministic code in a live indicator | Remove Date and Math.random, and do not write from calculate into values declared at the top of the file (create every value inside calculate): a live update must give the same values as a full recalculation (ctx.time has New York dates and times), or set live: 'none'. |
| `E-LIVE-BAR-CLOSE` <a id="e-live-bar-close"></a> | Invalid bar-close condition | Set live.barCloseWhen to a boolean input key, or { input: '<select key>', in: [<some of its options>] }; settings that match update at bar close only, every other setting on every tick. The default inputs and every preset must not all match it (nothing added from the toolbox would update live): make the default a live setting, or set live to 'none'. |
| `E-INPUT-KEY-INVALID` <a id="e-input-key-invalid"></a> | Invalid input key | Input keys are camelCase, start with a lowercase letter and are at most 21 characters. |
| `E-INPUT-TYPE-INVALID` <a id="e-input-type-invalid"></a> | Invalid input type | Use one of 'integer', 'number', 'boolean', 'select', 'source', 'text', 'time'. |
| `E-INPUT-DEFAULT-INVALID` <a id="e-input-default-invalid"></a> | Invalid input default | Provide a default that matches the input type and lies inside its range or options. |
| `E-INPUT-RANGE-INVALID` <a id="e-input-range-invalid"></a> | Invalid input range | min must be <= max, step must be positive, and integer inputs need integer bounds. |
| `E-INPUT-OPTIONS-INVALID` <a id="e-input-options-invalid"></a> | Invalid select options | Provide 1-16 unique non-empty option strings. |
| `E-INPUT-LIMIT` <a id="e-input-limit"></a> | Too many inputs | Declare at most 24 inputs. |
| `E-PLOT-KEY-INVALID` <a id="e-plot-key-invalid"></a> | Invalid output key | Output keys are camelCase, start with a lowercase letter and are at most 14 characters. |
| `E-PLOT-PRIMARY` <a id="e-plot-primary"></a> | Primary plot ambiguity | Mark exactly one plot as primary (or none; the first plot is primary). |
| `E-OUTPUT-LIMIT` <a id="e-output-limit"></a> | Too many outputs | Reduce the number of plots, levels, zones, markers, columns, profiles or (schema v3) tables, labels, barColors, bgColors, segments or boxes. |
| `E-OUTPUT-EMPTY` <a id="e-output-empty"></a> | Indicator produces nothing | Declare at least one plot, level, zone, marker, column or profile (schema v3: or a table, labels, barColors, bgColors, segments or boxes). |
| `E-OUTPUT-PANE-MISMATCH` <a id="e-output-pane-mismatch"></a> | Output not allowed on this pane | Columns are only available on the 'oscillator' pane, profiles, barColors, inline level labels and aboveBar/belowBar markers only on the 'price' pane. |
| `E-COLOR-INVALID` <a id="e-color-invalid"></a> | Invalid color | Use a 6-digit hex color like #8AA9C3. |
| `E-STYLE-INVALID` <a id="e-style-invalid"></a> | Invalid style value | Check lineWidth (0.5-8), lineStyle, gaps, opacity (0-0.8 for zones, 0-1 for profiles, tables and boxes, 0-0.6 for bgColors), radius (2-8), offset (a whole number from -500 to 500, or an integer input key such as displacement, -displacement or displacement-1), a profile placement (range or visible) and a plot style (line, step, circles, cross, area or histogram). |
| `E-KEY-COLLISION` <a id="e-key-collision"></a> | Key collision | Rename the input so it does not collide with a generated style setting (e.g. <plot>Color). |
| `E-PRESET-INVALID` <a id="e-preset-invalid"></a> | Invalid preset | Each preset needs id, name, shortName and inputs that match declared inputs. |
| `E-PRESET-LIMIT` <a id="e-preset-limit"></a> | Too many presets | Declare at most 8 presets. |
| `E-DOCS-INVALID` <a id="e-docs-invalid"></a> | Invalid docs | docs.overview is required; each docs field is a string up to 2000 characters. |
| `E-AUX-UNSUPPORTED` <a id="e-aux-unsupported"></a> | Auxiliary bars need schemaVersion 2 | Set `schemaVersion: 2` to read auxiliary bars, or remove the auxiliary field. |
| `E-AUX-INVALID` <a id="e-aux-invalid"></a> | Invalid auxiliary source | Give each auxiliary source a barSize and a duration, and only the documented fields: useRth, whatToShow, keepUpToDate, when. |
| `E-AUX-KEY-INVALID` <a id="e-aux-key-invalid"></a> | Invalid auxiliary key | Auxiliary keys are camelCase, start with a lowercase letter and are at most 14 characters. |
| `E-AUX-LIMIT` <a id="e-aux-limit"></a> | Too many auxiliary sources | Declare at most 4 auxiliary sources. |
| `E-AUX-BAR-SIZE` <a id="e-aux-bar-size"></a> | Unsupported auxiliary bar size | Use a Spectral bar size of 1 min or longer, e.g. '1 day' or '1 week'. |
| `E-AUX-DURATION` <a id="e-aux-duration"></a> | Invalid auxiliary duration | Write the duration as a count and a unit, e.g. '2 Y' (at most 365 D, 52 W or 12 M; use Y beyond), within the limit for its bar size. |
| `E-ANNOTATION-UNSUPPORTED` <a id="e-annotation-unsupported"></a> | Drawing elements need schemaVersion 3 | Set `schemaVersion: 3` to use palettes, tables, labels, barColors, bgColors, segments, boxes, a plot style or palette, a level labelStyle, a zone palette, or a marker shape, char, size, placement, palette or hideBelowBarWidth, or remove them. |
| `E-PALETTE-INVALID` <a id="e-palette-invalid"></a> | Invalid palette | Declare at most 8 palettes, each { label, colors } with 1-8 6-digit hex colors like #4CAF7A, keyed like an output. |
| `E-PALETTE-REF` <a id="e-palette-ref"></a> | Unknown palette | Set palette to the key of a palette declared under palettes (barColors and bgColors need one). |
| `E-TABLE-INVALID` <a id="e-table-invalid"></a> | Invalid table | Give each table a label, a position ('top-left' to 'bottom-right'), 1-12 columns { align?, width? } (width 2-32 characters), border true or false and offsetX/offsetY from 0 to 200 pixels. |
| `E-LABEL-INVALID` <a id="e-label-invalid"></a> | Invalid label | Check style ('none', 'box', 'pin', 'arrow'), placement ('above', 'below', 'left', 'right', 'center'), hideBelowBarWidth (0-40) and maxVisible (1-2000). |
| `E-SHAPE-INVALID` <a id="e-shape-invalid"></a> | Invalid marker shape | Check shape, size ('tiny', 'small', 'normal', 'large'), placement ('absolute', 'aboveBar', 'belowBar') and hideBelowBarWidth (0-40); shape: 'char' needs char, one visible character. |
| `E-SEGMENT-INVALID` <a id="e-segment-invalid"></a> | Invalid segment | Set extend to 'none', 'right', 'left' or 'both'. |
| `E-BOX-INVALID` <a id="e-box-invalid"></a> | Invalid box | Set extend to 'none' or 'right' and hideBelowBarWidth from 0 to 40. |
| `E-TEXT-SIZE-INVALID` <a id="e-text-size-invalid"></a> | Invalid text size or font | Set textSize to 'small', 'normal' or 'large' and font to 'mono' or 'sans'. |
| `E-AUX-WHEN` <a id="e-aux-when"></a> | Invalid auxiliary condition | List conditions in when.all and when.any, at least one in total: a declared boolean input key, or { input: '<select key>', in: [<its options>] }. |

### Warnings

| Code | Meaning | Fix |
| --- | --- | --- |
| `W-NONDETERMINISTIC` <a id="w-nondeterministic"></a> | Non-deterministic code | Avoid Date, Math.random and writes from calculate into values declared at the top of the file; results should depend only on bars and inputs. |
| `W-LIVE-HELD` <a id="w-live-held"></a> | Updates at bar close while a kept-up-to-date series forms | calculate carries values through ctx.ta and reads an auxiliary series with keepUpToDate: while its forming bar changes, the chart shows bar-close values. Set keepUpToDate: false on it, or compute the carried values from completed bars of it only. |
| `W-LIVE-MARKER` <a id="w-live-marker"></a> | A marker moves with the newest bar | calculate returns a marker only on the last bar (if (cond[last]) markers.push({ index: last })): the chart keeps it on that bar until the next bar closes, then drops it. Return the marker on every bar the condition holds on, not only the last. |
| `W-CONSOLE` <a id="w-console"></a> | console usage | Remove console calls; they are not visible to the user. |
| `W-VOLUME-UNDECLARED` <a id="w-volume-undeclared"></a> | Volume used without usesVolume | Set `usesVolume: true` when calculate reads bar.volume. |
| `W-DOCS-MISSING` <a id="w-docs-missing"></a> | No docs | Add docs (overview, howToRead, settings) so the info page can explain the indicator. |
| `W-DOCS-INCOMPLETE` <a id="w-docs-incomplete"></a> | Info page incomplete | Add docs.howToRead, docs.settings and a description for every input; they fill the indicator info page. |

### Runtime (from the import test run, or shown on the chart after installation)

| Code | Meaning | Fix |
| --- | --- | --- |
| `R-LOAD-FAILED` <a id="r-load-failed"></a> | Module failed to load | Reload the indicator; if it persists, re-import the file. |
| `R-EXPORT-MISMATCH` <a id="r-export-mismatch"></a> | Module does not match its manifest | Re-import the file; the stored copy and the manifest disagree. |
| `R-THROW` <a id="r-throw"></a> | calculate threw an error | Fix the error in calculate, then Reload. |
| `R-OUTPUT-INVALID` <a id="r-output-invalid"></a> | calculate returned an invalid result | Return only declared keys with numeric arrays or nulls. |
| `R-OUTPUT-LENGTH` <a id="r-output-length"></a> | Series length mismatch | Every series must have exactly bars.length entries. |
| `R-OUTPUT-TEXT` <a id="r-output-text"></a> | Drawn text too long | Shorten the text or return fewer items: a table cell holds at most 32 characters and a table at most 4,096 (cell tooltips included); a label at most 48 characters in 3 lines, a box text 32, a tooltip 48 in 3 lines; all labels, all boxes (texts and tooltips) and all shape-marker tooltips of one indicator at most 65,536 each. Abbreviate, or drop decimals with ctx.format. The import checks 30,000 bars and scrolling back can hold more: draw text only on bars that matter, never on every bar. |
| `R-TEXT-UNSAFE` <a id="r-text-unsafe"></a> | Drawn text looks like an identifier | Drawn text must not hold 8 or more hexadecimal characters in a row, an account-like code (U, DU or F and digits) or a 22-character token. Write numbers with ctx.format (it groups long integers) instead of String(value). |
| `R-SLOW` <a id="r-slow"></a> | calculate is too slow | Keep a full run linear in the bar count (30,000 bars in about 50 ms is comfortable; the import allows a quarter of a second with every input at its max, the chart turns those settings off at that bar size for the session above a second, counting the conversion of the result): no loop over all bars inside a loop over all bars, and a lower max for inputs that set long windows. |
| `R-LIVE-INEXACT` <a id="r-live-inexact"></a> | Live update differs from a full recalculation | Raise live.lookback to the number of bars calculate reads back, carry values from bar to bar only through ctx.ta.scan or ctx.ta.cum, keep no value between runs (create every value inside calculate), or set live: 'none'. |
| `R-SCAN-STATE` <a id="r-scan-state"></a> | ta.scan keeps too much state | Keep a ta.scan state small (a few numbers): over a whole run one scan may copy at most 2,000,000 state values (about 66 per bar on 30,000 bars). Return the same state object from a step that changes nothing; it costs no copy. |
| `R-LIVE-SLOW` <a id="r-live-slow"></a> | Live update is too slow | Lower live.lookback or remove loops over all bars from calculate, or set live: 'none'; until then the indicator updates when a bar completes. |
| `R-LIVE-STATE` <a id="r-live-state"></a> | ctx.ta calls differ between runs | Call the ctx.ta helpers in the same order with the same lengths on every run, on series as long as ctx.bars; do not make the calls depend on bars.length or on the data. |
| `R-TIMEOUT` <a id="r-timeout"></a> | Indicator timed out | The indicator was disabled for this session; fix the infinite loop and Reload. |
| `R-NOT-INSTALLED` <a id="r-not-installed"></a> | Custom indicator not installed | Re-import it from the toolbox or remove it from the chart. |
| `R-INCOMPATIBLE` <a id="r-incompatible"></a> | Indicator incompatible with this Spectral version | Update Spectral or re-generate the file against the current docs. |

## 13. Complete examples

### ema-ribbon.js

```js
// Copyright (c) 2026 Spectral
// SPDX-License-Identifier: MIT-0
// Free to use, copy, modify and share: https://spectral.trade/docs/custom-indicators/LICENSE.txt
/** @type {import('./spectral-indicator').IndicatorV1} */
export default {
  schemaVersion: 1,
  id: 'ema-ribbon',
  name: 'EMA Ribbon',
  shortName: 'Ribbon',
  version: '1.0.0',
  author: 'Spectral examples',
  description: 'Three exponential moving averages on the price pane with a shaded band between the fastest and the slowest.',
  pane: 'price',
  live: { lookback: 0 },
  inputs: {
    fast: { type: 'integer', label: 'Fast length', default: 8, min: 1, max: 500, description: 'Number of bars in the fast EMA.' },
    mid: { type: 'integer', label: 'Mid length', default: 21, min: 1, max: 500, description: 'Number of bars in the middle EMA.' },
    slow: { type: 'integer', label: 'Slow length', default: 55, min: 1, max: 500, description: 'Number of bars in the slow EMA.' },
    source: { type: 'source', label: 'Source', default: 'close', description: 'Price the three averages are calculated from.' },
  },
  plots: {
    fast: { label: 'Fast EMA', color: '#58A6FF', lineWidth: 1.5, primary: true },
    mid: { label: 'Mid EMA', color: '#C4A46A' },
    slow: { label: 'Slow EMA', color: '#F0883E' },
  },
  zones: { ribbon: { label: 'Ribbon', color: '#58A6FF', opacity: 0.08 } },
  docs: {
    overview: 'Three EMAs of different lengths; the shaded ribbon spans the fast and slow averages.',
    howToRead: 'A fast average above mid above slow with a widening ribbon shows a trending market; a compressed ribbon shows consolidation.',
    settings: 'Keep Fast < Mid < Slow. Shorter lengths react sooner but flip more often. EMAs start at the first bar, so the earliest values are less reliable.',
  },
  calculate(ctx) {
    const { ta, inputs, bars } = ctx;
    const source = ta.source(bars, inputs.source);
    const fast = ta.ema(source, inputs.fast);
    const mid = ta.ema(source, inputs.mid);
    const slow = ta.ema(source, inputs.slow);
    const upper = fast.map((value, index) => (value === null || slow[index] === null ? null : Math.max(value, slow[index])));
    const lower = fast.map((value, index) => (value === null || slow[index] === null ? null : Math.min(value, slow[index])));
    return { plots: { fast, mid, slow }, zones: { ribbon: { upper, lower } } };
  },
};
```

### fair-value-gaps.js

```js
// Copyright (c) 2026 Spectral
// SPDX-License-Identifier: MIT-0
// Free to use, copy, modify and share: https://spectral.trade/docs/custom-indicators/LICENSE.txt
/** @type {import('./spectral-indicator').IndicatorV3} */
export default {
  schemaVersion: 3,
  id: 'fair-value-gaps',
  name: 'Fair Value Gaps',
  shortName: 'FVG',
  version: '1.0.0',
  author: 'Spectral examples',
  description: 'Boxes every three-bar fair value gap from its first bar until price fills (or touches) it, labelled with the gap size; hovering a box shows its size in percent and whether it is still open.',
  pane: 'price',
  live: 'none',
  inputs: {
    minGap: { type: 'number', label: 'Minimum gap %', default: 0.05, min: 0, max: 5, step: 0.01, description: 'Smallest gap drawn, as a percentage of the price.' },
    maxBoxes: { type: 'integer', label: 'Gaps shown', default: 60, min: 1, max: 500, description: 'Most recent gaps drawn (open and filled).' },
    mitigation: { type: 'select', label: 'Mitigated when', default: 'Filled', options: ['Filled', 'Touched'], description: 'Filled: a later bar trades through the gap to its far side. Touched: a later bar trades back into the gap at all.' },
  },
  palettes: {
    gap: { label: 'Gap', colors: ['#3FB950', '#F85149', '#8B949E'] },
  },
  boxes: {
    gaps: { label: 'Fair value gaps', color: '#3FB950', palette: 'gap', opacity: 0.18, textSize: 'small', hideBelowBarWidth: 3 },
  },
  docs: {
    overview: 'A fair value gap (FVG, from ICT\'s inner-circle-trader teaching) is a three-bar pattern where the middle bar moved so fast that the outer bars do not overlap: bullish when the third bar\'s low is above the first bar\'s high, bearish when the third bar\'s high is below the first bar\'s low. The gap between them is boxed from the first of the three bars until price mitigates it.',
    howToRead: 'Open gaps (green bullish, red bearish) reach the latest bar; a mitigated gap is drawn grey and ends on the bar that mitigated it. Open gaps often act as support (bullish) or resistance (bearish) when price returns to them. Hover a box for its direction, size, share of the price and state.',
    settings: 'Minimum gap % hides small gaps; Gaps shown limits the drawn boxes to the most recent ones. Mitigated when chooses the rule that closes a gap: Filled (price trades through to the gap\'s far side, the default) or Touched (price trades back into it). The three colours and the box opacity are appearance settings.',
    notes: 'Rule: bullish FVG when low[i] > high[i - 2], the gap spanning high[i - 2] to low[i]; bearish when high[i] < low[i - 2], spanning high[i] to low[i - 2] (the common ICT definition; there is no formal standard for mitigation, so both readings are offered: a later low at or below the bottom of a bullish gap fills it, one at or below its top touches it; mirrored for bearish gaps). The bar that completes a gap never mitigates it. Minimum gap % compares the gap with the close that formed it. Marks completed bars only (live: none). The text is the gap size in price; the tooltip adds the size as a percentage of that close and whether the gap is open.',
  },
  calculate(ctx) {
    const { bars, inputs, format } = ctx;
    const gaps = [];
    // The price that mitigates a gap: its far side when it must fill, its near side when a touch is enough.
    const touch = inputs.mitigation === 'Touched';
    const edgeOf = (gap) => (gap.bullish === touch ? gap.top : gap.bottom);
    // Open gaps, ordered so the ones the next bar mitigates sit at the end: bullish by edge (ascending; a later low
    // at or under the edge mitigates it), bearish by edge (descending; a later high at or over the edge mitigates it).
    const openBullish = [];
    const openBearish = [];
    // Where to insert into an ordered list: after every entry `before` accepts (binary search).
    const insertAt = (list, before) => {
      let low = 0;
      let high = list.length;
      while (low < high) {
        const middle = (low + high) >> 1;
        if (before(list[middle])) low = middle + 1;
        else high = middle;
      }
      return low;
    };
    for (let index = 2; index < bars.length; index += 1) {
      const first = bars[index - 2];
      const bar = bars[index];
      // A gap is mitigated once a later bar reaches its edge (see edgeOf).
      while (openBullish.length > 0 && bar.low <= edgeOf(openBullish[openBullish.length - 1])) openBullish.pop().filledAt = index;
      while (openBearish.length > 0 && bar.high >= edgeOf(openBearish[openBearish.length - 1])) openBearish.pop().filledAt = index;
      const bullish = bar.low > first.high;
      const bearish = bar.high < first.low;
      if (!bullish && !bearish) continue;
      const bottom = bullish ? first.high : bar.high;
      const top = bullish ? bar.low : first.low;
      if ((top - bottom) / bar.close * 100 < inputs.minGap) continue;
      const gap = { from: index - 2, bottom, top, bullish, close: bar.close, filledAt: -1 };
      gaps.push(gap);
      const edge = edgeOf(gap);
      if (bullish) openBullish.splice(insertAt(openBullish, (open) => edgeOf(open) < edge), 0, gap);
      else openBearish.splice(insertAt(openBearish, (open) => edgeOf(open) > edge), 0, gap);
    }
    return {
      boxes: {
        gaps: gaps.slice(-inputs.maxBoxes).map((gap) => ({
          x1: gap.from,
          y1: gap.bottom,
          x2: gap.filledAt >= 0 ? gap.filledAt : 'right-edge',
          y2: gap.top,
          palette: gap.filledAt >= 0 ? 2 : gap.bullish ? 0 : 1,
          text: format.price(gap.top - gap.bottom),
          tooltip: `${gap.bullish ? 'Bullish' : 'Bearish'} gap ${format.price(gap.top - gap.bottom)} (${format.percent((gap.top - gap.bottom) / gap.close, 2)})\n${gap.filledAt >= 0 && touch ? 'Touched' : gap.filledAt >= 0 ? 'Filled' : 'Open'}`,
        })),
      },
    };
  },
};
```

### inside-bar-shapes.js

```js
// Copyright (c) 2026 Spectral
// SPDX-License-Identifier: MIT-0
// Free to use, copy, modify and share: https://spectral.trade/docs/custom-indicators/LICENSE.txt
/** Shape markers one key may return (Spectral's limit). */
const MAX_MARKERS = 4000;

/** @type {import('./spectral-indicator').IndicatorV3} */
export default {
  schemaVersion: 3,
  id: 'inside-bar-shapes',
  name: 'Inside Bar Breakouts',
  shortName: 'IB Break',
  version: '1.0.0',
  author: 'Spectral examples',
  description: 'Marks inside bars with a triangle below the bar and the first close beyond the mother bar with an arrow.',
  pane: 'price',
  live: 'none',
  inputs: {
    maxRatio: { type: 'number', label: 'Tight ratio', default: 0.5, min: 0.1, max: 1, step: 0.05, description: 'An inside bar whose range is at most this share of the mother bar range is drawn in the tight colour.' },
  },
  palettes: {
    inside: { label: 'Inside bar', colors: ['#58A6FF', '#D29922'] },
  },
  markers: {
    inside: { label: 'Inside bar', color: '#58A6FF', shape: 'triangleUp', size: 'small', placement: 'belowBar', palette: 'inside', hideBelowBarWidth: 2 },
    breakUp: { label: 'Breakout up', color: '#3FB950', shape: 'arrowUp', size: 'normal', placement: 'belowBar' },
    breakDown: { label: 'Breakout down', color: '#F85149', shape: 'arrowDown', size: 'normal', placement: 'aboveBar' },
  },
  docs: {
    overview: 'A small triangle under every inside bar (its high and low inside the mother bar, the bar before the first inside bar), and an arrow on the first bar that closes above or below the mother bar.',
    howToRead: 'A run of triangles shows compression; the arrow marks the close that broke out of it. Tight inside bars (the second colour) often precede the stronger breaks.',
    settings: 'Tight ratio sets which inside bars are drawn in the tight colour: their range as a share of the mother bar range.',
    notes: 'Marks completed bars only (live: none), so the forming bar never flickers in and out. On a long chart only the newest 4,000 inside bars and breakouts of each kind are marked (Spectral keeps at most 4,000 shape markers per key).',
  },
  calculate(ctx) {
    const { bars, inputs } = ctx;
    const inside = [];
    const breakUp = [];
    const breakDown = [];
    let mother = null;
    for (let index = 1; index < bars.length; index += 1) {
      const bar = bars[index];
      if (mother !== null) {
        if (bar.close > mother.high) { breakUp.push({ index }); mother = null; continue; }
        if (bar.close < mother.low) { breakDown.push({ index }); mother = null; continue; }
      }
      const previous = mother ?? bars[index - 1];
      const range = previous.high - previous.low;
      if (range > 0 && bar.high <= previous.high && bar.low >= previous.low) {
        mother = previous;
        const tight = (bar.high - bar.low) / range <= inputs.maxRatio;
        inside.push({ index, palette: tight ? 1 : 0 });
      } else if (mother !== null && (bar.high > mother.high || bar.low < mother.low)) {
        mother = null;
      }
    }
    // Spectral keeps at most 4,000 shape markers per key, so a long history returns its newest ones.
    const newest = (items) => (items.length > MAX_MARKERS ? items.slice(items.length - MAX_MARKERS) : items);
    return { markers: { inside: newest(inside), breakUp: newest(breakUp), breakDown: newest(breakDown) } };
  },
};
```

### inside-bars.js

```js
// Copyright (c) 2026 Spectral
// SPDX-License-Identifier: MIT-0
// Free to use, copy, modify and share: https://spectral.trade/docs/custom-indicators/LICENSE.txt
/** @type {import('./spectral-indicator').IndicatorV1} */
export default {
  schemaVersion: 1,
  id: 'inside-bars',
  name: 'Inside Bars',
  shortName: 'IB',
  version: '1.0.1',
  author: 'Spectral examples',
  description: 'Marks completed bars whose high and low sit inside the previous bar.',
  pane: 'price',
  live: 'none',
  inputs: {
    maxRatio: { type: 'number', label: 'Max range ratio', default: 1, min: 0.1, max: 1, step: 0.05, description: 'Largest inside-bar range as a share of the previous bar range. 1 marks every inside bar; lower values mark only tight ones.' },
    regularOnly: { type: 'boolean', label: 'Regular session only', default: false, description: 'Mark only regular-session bars: 09:30 to 16:00 New York time, to 13:00 on early-close days.' },
  },
  markers: { inside: { label: 'Inside bar', color: '#58A6FF', radius: 4 } },
  docs: {
    overview: 'A dot under every bar whose range is contained in the previous bar\'s range.',
    howToRead: 'Clusters of inside bars show compression; a break of the enclosing bar often starts the next move.',
    settings: 'Lower Max range ratio to mark only tight inside bars. Turn on Regular session only to ignore pre-market and after-hours bars.',
    notes: 'Marks completed bars only (live: none), so the forming bar never flickers in and out.',
  },
  calculate(ctx) {
    const { bars, inputs, time } = ctx;
    const inside = [];
    for (let index = 1; index < bars.length; index += 1) {
      const bar = bars[index];
      const previous = bars[index - 1];
      if (inputs.regularOnly && !time.isRegularSession(bar)) continue;
      const previousRange = previous.high - previous.low;
      if (previousRange <= 0) continue;
      const contained = bar.high <= previous.high && bar.low >= previous.low;
      if (contained && (bar.high - bar.low) / previousRange <= inputs.maxRatio) inside.push({ index, value: bar.low });
    }
    return { markers: { inside } };
  },
};
```

### pivot-trendlines.js

```js
// Copyright (c) 2026 Spectral
// SPDX-License-Identifier: MIT-0
// Free to use, copy, modify and share: https://spectral.trade/docs/custom-indicators/LICENSE.txt
/** @type {import('./spectral-indicator').IndicatorV3} */
export default {
  schemaVersion: 3,
  id: 'pivot-trendlines',
  name: 'Pivot Trendlines',
  shortName: 'Trendlines',
  version: '1.0.0',
  author: 'Spectral examples',
  description: 'Connects consecutive confirmed swing highs and swing lows, extends the latest high and low line to the right, and boxes the range between the latest swing high and low.',
  pane: 'price',
  live: 'none',
  inputs: {
    strength: { type: 'integer', label: 'Pivot strength', default: 5, min: 1, max: 30, description: 'Bars on each side a swing high must stand above (a swing low below) to count.' },
    history: { type: 'integer', label: 'Lines shown', default: 40, min: 0, max: 500, description: 'Most recent swing-to-swing lines drawn per side.' },
  },
  palettes: {
    slope: { label: 'Slope', colors: ['#3FB950', '#F85149'] },
  },
  segments: {
    swings: { label: 'Swing lines', color: '#8B949E', palette: 'slope', lineWidth: 1, lineStyle: 'dotted' },
    latest: { label: 'Latest trendlines', color: '#D29922', lineWidth: 1.5, extend: 'right' },
  },
  boxes: {
    range: { label: 'Swing range', color: '#A371F7', opacity: 0.08, extend: 'right', textSize: 'small', hideBelowBarWidth: 2 },
  },
  docs: {
    overview: 'A swing high is a high above the highs of the bars on each side (a swing low the mirror), confirmed once those bars closed. Each swing is joined to the previous swing on its side.',
    howToRead: 'Rising lines (green) show higher highs or higher lows, falling lines (red) lower ones. The two latest lines (amber) continue to the right edge: a close beyond the latest high line breaks a falling resistance. The violet box spans the latest swing high and low; a close outside it leaves the range.',
    settings: 'Pivot strength sets how many bars each side confirm a swing; Lines shown limits the older swing lines.',
    notes: 'A swing is only known once the bars to its right closed (live: none), so lines appear that many bars late.',
  },
  calculate(ctx) {
    const { bars, inputs } = ctx;
    const n = inputs.strength;
    const highs = [];
    const lows = [];
    for (let index = n; index < bars.length - n; index += 1) {
      let isHigh = true;
      let isLow = true;
      for (let offset = 1; offset <= n && (isHigh || isLow); offset += 1) {
        if (bars[index - offset].high >= bars[index].high || bars[index + offset].high > bars[index].high) isHigh = false;
        if (bars[index - offset].low <= bars[index].low || bars[index + offset].low < bars[index].low) isLow = false;
      }
      if (isHigh) highs.push({ index, value: bars[index].high });
      if (isLow) lows.push({ index, value: bars[index].low });
    }
    const lines = (pivots) => pivots.slice(1).map((pivot, position) => {
      const previous = pivots[position];
      return { x1: previous.index, y1: previous.value, x2: pivot.index, y2: pivot.value, palette: pivot.value >= previous.value ? 0 : 1 };
    });
    const highLines = lines(highs);
    const lowLines = lines(lows);
    const high = highs[highs.length - 1];
    const low = lows[lows.length - 1];
    const range = high && low ? [{
      x1: Math.min(high.index, low.index), y1: low.value, x2: Math.max(high.index, low.index), y2: high.value,
      text: `range ${ctx.format.price(high.value - low.value)}`,
    }] : [];
    return {
      boxes: { range },
      segments: {
        swings: [...highLines.slice(-inputs.history - 1, -1), ...lowLines.slice(-inputs.history - 1, -1)],
        latest: [...highLines.slice(-1), ...lowLines.slice(-1)].map(({ palette, ...line }) => line),
      },
    };
  },
};
```

### regime-shading.js

```js
// Copyright (c) 2026 Spectral
// SPDX-License-Identifier: MIT-0
// Free to use, copy, modify and share: https://spectral.trade/docs/custom-indicators/LICENSE.txt
/** @type {import('./spectral-indicator').IndicatorV3} */
export default {
  schemaVersion: 3,
  id: 'regime-shading',
  name: 'Regime Shading',
  shortName: 'Regime',
  version: '1.0.0',
  author: 'Spectral examples',
  description: 'Shades the price pane by EMA trend regime, colours the fast EMA by regime and recolours the candles that close beyond the recent closing range.',
  pane: 'price',
  live: { lookback: 'breakout' },
  inputs: {
    fast: { type: 'integer', label: 'Fast EMA', default: 20, min: 2, max: 200, description: 'Bars in the fast EMA.' },
    slow: { type: 'integer', label: 'Slow EMA', default: 50, min: 3, max: 400, description: 'Bars in the slow EMA.' },
    flat: { type: 'number', label: 'Flat band %', default: 0.05, min: 0, max: 2, description: 'A fast EMA within this percentage of the slow one counts as no trend.' },
    breakout: { type: 'integer', label: 'Breakout bars', default: 20, min: 2, max: 200, description: 'A close above the highest close (below the lowest close) of this many prior bars is a breakout.' },
  },
  palettes: {
    regime: { label: 'Regime', colors: ['#2EA043', '#DA3633', '#6E7681'] },
    breakout: { label: 'Breakout', colors: ['#3FB950', '#F85149'] },
  },
  plots: {
    fast: { label: 'Fast EMA', color: '#C4A46A', lineWidth: 2, palette: 'regime', primary: true },
    slow: { label: 'Slow EMA', color: '#8B949E', lineWidth: 1, style: 'step' },
  },
  bgColors: {
    regime: { label: 'Regime shading', palette: 'regime', opacity: 0.08 },
  },
  barColors: {
    breakout: { label: 'Breakout candles', palette: 'breakout' },
  },
  docs: {
    overview: 'Classifies every bar by the position of a fast EMA against a slow one: up (fast above), down (fast below) or flat (within the flat band). The pane background and the fast EMA take the regime colour; candles that close beyond the recent range are recoloured.',
    howToRead: 'Green shading and a green fast EMA mark an up regime, red a down regime, grey no trend. A bright green candle closed above every close of the prior Breakout bars, a bright red one below all of them; a breakout in the direction of the regime is the stronger signal.',
    settings: 'Fast and Slow EMA set the regime; a wider Flat band calls more bars flat. Breakout bars sets how far back the range reaches. Every colour, the shading opacity and the candle colours are appearance settings.',
  },
  calculate(ctx) {
    const { ta, inputs, bars } = ctx;
    const close = ta.source(bars, 'close');
    const fast = ta.ema(close, inputs.fast);
    const slow = ta.ema(close, inputs.slow);
    const highest = ta.highest(close, inputs.breakout);
    const lowest = ta.lowest(close, inputs.breakout);
    const band = inputs.flat / 100;
    // Palette indexes per bar: 0 up, 1 down, 2 flat; null leaves a bar unshaded.
    const regime = fast.map((value, index) => {
      const base = slow[index];
      if (value === null || base === null || base === 0) return null;
      const spread = (value - base) / base;
      return spread > band ? 0 : spread < -band ? 1 : 2;
    });
    // A breakout compares a close with the closes of the bars before it, so the previous bar's highest and lowest.
    const breakout = close.map((value, index) => {
      if (index === 0) return null;
      const high = highest[index - 1];
      const low = lowest[index - 1];
      if (high !== null && value > high) return 0;
      if (low !== null && value < low) return 1;
      return null;
    });
    return {
      plots: { fast, slow },
      colors: { fast: regime },
      bgColors: { regime },
      barColors: { breakout },
    };
  },
};
```

### regime-table.js

```js
// Copyright (c) 2026 Spectral
// SPDX-License-Identifier: MIT-0
// Free to use, copy, modify and share: https://spectral.trade/docs/custom-indicators/LICENSE.txt
/** @type {import('./spectral-indicator').IndicatorV3} */
export default {
  schemaVersion: 3,
  id: 'regime-table',
  name: 'Regime Table',
  shortName: 'Regime',
  version: '1.0.0',
  author: 'Spectral examples',
  description: 'A table on the price pane that classifies the latest bar as trending up, trending down or ranging from ADX, the directional indicators and the slope of an EMA.',
  pane: 'price',
  live: { lookback: 'slope' },
  inputs: {
    length: { type: 'integer', label: 'ADX length', default: 14, min: 2, max: 100, description: 'Bars in the Wilder averages of the directional movement and the true range.' },
    emaLength: { type: 'integer', label: 'EMA length', default: 50, min: 2, max: 400, description: 'Bars in the EMA whose slope sets the direction.' },
    slope: { type: 'integer', label: 'Slope bars', default: 5, min: 1, max: 50, description: 'How many bars back the EMA slope is measured.' },
    threshold: { type: 'number', label: 'Trend ADX', default: 25, min: 10, max: 50, description: 'ADX at or above this value counts as a trend.' },
  },
  palettes: {
    regime: { label: 'Regime', colors: ['#2EA043', '#DA3633', '#6E7681'] },
  },
  tables: {
    regime: { label: 'Regime', position: 'top-right', columns: [{ align: 'left' }, { align: 'right', width: 12 }], border: true },
  },
  docs: {
    overview: 'Reads the trend state of the latest bar: the Average Directional Index (Wilder) for trend strength, +DI against -DI for its direction, and the slope of an EMA as a second opinion.',
    howToRead: 'Trend up: ADX at or above the Trend ADX setting, +DI above -DI and a rising EMA. Trend down: the mirror image. Anything else is a range. The table updates with every tick of the forming bar; hover the regime cell for the ADX and slope behind it.',
    settings: 'ADX length sets how smooth the directional averages are. EMA length and Slope bars set the direction filter; a longer EMA or more slope bars react later but flip less often.',
  },
  calculate(ctx) {
    const { ta, inputs, bars, format } = ctx;
    const high = ta.source(bars, 'high');
    const low = ta.source(bars, 'low');
    const upMove = ta.change(high);
    const downMove = ta.change(low);
    const plusDm = upMove.map((up, index) => {
      const down = downMove[index] === null ? null : -downMove[index];
      return up === null || down === null ? null : up > down && up > 0 ? up : 0;
    });
    const minusDm = downMove.map((change, index) => {
      const up = upMove[index];
      const down = change === null ? null : -change;
      return up === null || down === null ? null : down > up && down > 0 ? down : 0;
    });
    const range = ta.rma(ta.trueRange(bars), inputs.length);
    const plusSmooth = ta.rma(plusDm, inputs.length);
    const minusSmooth = ta.rma(minusDm, inputs.length);
    const plusDi = range.map((tr, index) => (tr === null || plusSmooth[index] === null || tr === 0 ? null : 100 * plusSmooth[index] / tr));
    const minusDi = range.map((tr, index) => (tr === null || minusSmooth[index] === null || tr === 0 ? null : 100 * minusSmooth[index] / tr));
    const dx = plusDi.map((plus, index) => {
      const minus = minusDi[index];
      if (plus === null || minus === null || plus + minus === 0) return null;
      return 100 * Math.abs(plus - minus) / (plus + minus);
    });
    const adx = ta.rma(dx, inputs.length);
    const ema = ta.ema(ta.source(bars, 'close'), inputs.emaLength);

    const last = bars.length - 1;
    const then = last - inputs.slope;
    const emaNow = last >= 0 ? ema[last] : null;
    const emaThen = then >= 0 ? ema[then] : null;
    const slope = emaNow === null || emaThen === null || emaThen === 0 ? null : (emaNow - emaThen) / emaThen;
    const strength = last >= 0 ? adx[last] : null;
    const plus = last >= 0 ? plusDi[last] : null;
    const minus = last >= 0 ? minusDi[last] : null;
    const trending = strength !== null && strength >= inputs.threshold;
    let verdict = { text: 'Range', palette: 2 };
    if (trending && plus !== null && minus !== null && slope !== null) {
      if (plus > minus && slope > 0) verdict = { text: 'Trend up', palette: 0 };
      else if (minus > plus && slope < 0) verdict = { text: 'Trend down', palette: 1 };
    }
    const lastClose = last >= 0 ? bars[last].close : null;
    return {
      tables: {
        regime: {
          palette: 'regime',
          rows: [
            ['Regime', {
              ...verdict, weight: 'bold', align: 'center',
              tooltip: `ADX ${format.number(strength, 1)}, trend from ${format.number(inputs.threshold, 0)}\nEMA slope ${format.percent(slope, 2)}`,
            }],
            ['ADX', format.number(strength, 1)],
            ['+DI / -DI', `${format.number(plus, 1)} / ${format.number(minus, 1)}`],
            ['EMA slope', format.percent(slope, 2)],
            ['Close', lastClose === null || emaNow === null ? 'n/a' : lastClose >= emaNow ? 'above EMA' : 'below EMA'],
          ],
        },
      },
    };
  },
};
```

### rsi-bands.js

```js
// Copyright (c) 2026 Spectral
// SPDX-License-Identifier: MIT-0
// Free to use, copy, modify and share: https://spectral.trade/docs/custom-indicators/LICENSE.txt
/** @type {import('./spectral-indicator').IndicatorV1} */
export default {
  schemaVersion: 1,
  id: 'rsi-bands',
  name: 'RSI with Bollinger Bands',
  shortName: 'RSI BB',
  version: '1.0.0',
  author: 'Spectral examples',
  description: 'RSI with a Bollinger envelope around its moving average, 30/70 guides and crossover dots.',
  pane: 'oscillator',
  live: { lookback: 'bbLength' },
  inputs: {
    length: { type: 'integer', label: 'RSI length', default: 14, min: 2, max: 200, step: 1, description: 'Number of bars in the RSI lookback. Shorter reacts faster but is noisier.' },
    source: { type: 'source', label: 'Source', default: 'close', description: 'Price the RSI is calculated from.' },
    bbLength: { type: 'integer', label: 'Band length', default: 20, min: 2, max: 200, description: 'Number of RSI values in the band average and its standard deviation.' },
    bbMult: { type: 'number', label: 'Band width', default: 2, min: 0.5, max: 5, step: 0.1, description: 'Distance of each band from the average, in standard deviations.' },
    showBand: { type: 'boolean', label: 'Fill band', default: true, description: 'Shade the area between the upper and lower band.' },
  },
  plots: {
    rsi: { label: 'RSI', color: '#B7A1C8', lineWidth: 1.5, primary: true },
    basis: { label: 'Basis', color: '#C4A46A', lineWidth: 1 },
    upper: { label: 'Upper', color: '#788493', lineStyle: 'dashed' },
    lower: { label: 'Lower', color: '#788493', lineStyle: 'dashed' },
  },
  levels: {
    overbought: { label: '70', color: '#788493', lineStyle: 'dotted', showValue: true },
    oversold: { label: '30', color: '#788493', lineStyle: 'dotted' },
  },
  zones: { band: { label: 'Band', color: '#8AA9C3', opacity: 0.1 } },
  markers: { cross: { label: 'RSI crosses basis', color: '#3FB950', radius: 3 } },
  columns: { spread: { label: 'RSI minus basis', color: '#58A6FF' } },
  presets: [{ id: 'fast', name: 'RSI BB (fast)', shortName: 'RSI BB 7', inputs: { length: 7, bbLength: 10 } }],
  docs: {
    overview: 'Relative Strength Index with a Bollinger envelope drawn around its own moving average.',
    howToRead: 'RSI above the upper band marks unusually strong momentum; below the lower band, unusually weak. The 30/70 guides are the classic oversold/overbought levels.\n\nGreen dots mark RSI crossing above its own average; the histogram shows how far RSI is from that average.',
    settings: 'RSI length (14) sets how quickly RSI reacts. Band length (20) and Band width (2) set how far RSI must move to leave the band. The first values appear after RSI length + Band length bars.',
    notes: 'The band uses a population standard deviation, like the built-in Bollinger Bands.',
  },
  calculate(ctx) {
    const { ta, inputs, bars } = ctx;
    const rsi = ta.rsi(ta.source(bars, inputs.source), inputs.length);
    const basis = ta.sma(rsi, inputs.bbLength);
    const deviation = ta.stdev(rsi, inputs.bbLength);
    const upper = basis.map((value, index) => (value === null || deviation[index] === null ? null : value + inputs.bbMult * deviation[index]));
    const lower = basis.map((value, index) => (value === null || deviation[index] === null ? null : value - inputs.bbMult * deviation[index]));
    const crosses = ta.crossover(rsi, basis);
    const markers = [];
    for (let index = 0; index < bars.length; index += 1) {
      if (crosses[index] && rsi[index] !== null) markers.push({ index, value: rsi[index] });
    }
    return {
      plots: { rsi, basis, upper, lower },
      levels: { overbought: 70, oversold: 30 },
      zones: inputs.showBand ? { band: { upper, lower } } : { band: { upper: upper.map(() => null), lower: lower.map(() => null) } },
      markers: { cross: markers },
      columns: { spread: rsi.map((value, index) => (value === null || basis[index] === null ? null : value - basis[index])) },
    };
  },
};
```

### swing-labels.js

```js
// Copyright (c) 2026 Spectral
// SPDX-License-Identifier: MIT-0
// Free to use, copy, modify and share: https://spectral.trade/docs/custom-indicators/LICENSE.txt
/** @type {import('./spectral-indicator').IndicatorV3} */
export default {
  schemaVersion: 3,
  id: 'swing-labels',
  name: 'Swing Labels',
  shortName: 'Swings',
  version: '1.0.0',
  author: 'Spectral examples',
  description: 'Labels each confirmed swing high and low with its price and whether it is higher or lower than the last one, and draws the latest swing high and low as levels with inline labels.',
  pane: 'price',
  live: 'none',
  inputs: {
    strength: { type: 'integer', label: 'Pivot strength', default: 3, min: 1, max: 20, description: 'Bars on each side a swing high must stand above (a swing low below) to count.' },
    showLevels: { type: 'boolean', label: 'Latest swing levels', default: true, description: 'Draw the latest swing high and low as levels from the bar they formed on.' },
  },
  palettes: {
    swing: { label: 'Swing', colors: ['#D29922', '#A371F7'] },
  },
  labels: {
    highs: { label: 'Swing highs', color: '#D29922', palette: 'swing', style: 'pin', placement: 'above', hideBelowBarWidth: 2 },
    lows: { label: 'Swing lows', color: '#A371F7', palette: 'swing', style: 'pin', placement: 'below', hideBelowBarWidth: 2 },
  },
  levels: {
    lastHigh: { label: 'Swing high', color: '#D29922', lineStyle: 'dotted', labelStyle: 'inline' },
    lastLow: { label: 'Swing low', color: '#A371F7', lineStyle: 'dotted', labelStyle: 'inline' },
  },
  docs: {
    overview: 'Finds swing highs and lows the way fractal pivots do: a bar whose high is above the highs of the bars on each side (a low below their lows), confirmed once those bars have closed. Each swing gets a label with its price; HH, LH, HL and LL compare it with the swing before it.',
    howToRead: 'HH (higher high) and HL (higher low) in amber describe an up-trending structure, LH and LL in violet a down-trending one. A swing is labelled only after Pivot strength bars have closed on its right, so the newest swing appears a few bars late. The dotted levels mark the latest swing high and low, the usual breakout and stop references.',
    settings: 'Pivot strength sets how many bars on each side must stay below a swing high (above a swing low): a higher value finds fewer, more significant swings. Latest swing levels turns the two levels off.',
  },
  calculate(ctx) {
    const { bars, inputs, format } = ctx;
    const n = inputs.strength;
    const highs = [];
    const lows = [];
    let lastHigh = null;
    let lastLow = null;
    // A swing at bar i needs n closed bars on each side.
    for (let i = n; i < bars.length - n; i += 1) {
      let isHigh = true;
      let isLow = true;
      for (let k = 1; k <= n && (isHigh || isLow); k += 1) {
        if (bars[i - k].high >= bars[i].high || bars[i + k].high > bars[i].high) isHigh = false;
        if (bars[i - k].low <= bars[i].low || bars[i + k].low < bars[i].low) isLow = false;
      }
      if (isHigh) {
        const higher = lastHigh === null || bars[i].high >= lastHigh.price;
        highs.push({ index: i, value: bars[i].high, text: `${higher ? 'HH' : 'LH'} ${format.price(bars[i].high)}`, palette: higher ? 0 : 1 });
        lastHigh = { price: bars[i].high, fromIndex: i };
      }
      if (isLow) {
        const higher = lastLow === null || bars[i].low >= lastLow.price;
        lows.push({ index: i, value: bars[i].low, text: `${higher ? 'HL' : 'LL'} ${format.price(bars[i].low)}`, palette: higher ? 0 : 1 });
        lastLow = { price: bars[i].low, fromIndex: i };
      }
    }
    // The chart keeps at most 2,000 labels per key: the most recent swings.
    return {
      labels: { highs: highs.slice(-2000), lows: lows.slice(-2000) },
      levels: inputs.showLevels ? { lastHigh, lastLow } : {},
    };
  },
};
```

## 14. Type declarations

Save this next to the indicator file as `spectral-indicator.d.ts` to get editor type-checking through the
`@type` comment at the top of the examples.

```ts
// Copyright (c) 2026 Spectral
// SPDX-License-Identifier: MIT-0
// Free to use, copy, modify and share: https://spectral.trade/docs/custom-indicators/LICENSE.txt

/**
 * Spectral custom indicator authoring types (schema v1, v2 and v3).
 *
 * This file is the published contract: the worker adapter imports these types,
 * and the same file ships with the documentation so an editor or an LLM can
 * type-check an indicator file with
 *   /** @type {import('./spectral-indicator').IndicatorV3} *\/
 * Everything a file may use is described here; anything else is unavailable
 * inside the indicator sandbox.
 */

export type HexColor = `#${string}`;
export type LineStyle = 'solid' | 'dashed' | 'dotted';
export type PriceSource = 'open' | 'high' | 'low' | 'close' | 'hlc3';
/** One value per bar, in bar order; `null` where the value is not defined yet. */
export type Series = ReadonlyArray<number | null>;

export interface Bar {
  /** Bar open time, Unix seconds. */
  readonly time: number;
  readonly open: number;
  readonly high: number;
  readonly low: number;
  readonly close: number;
  /** Only present when the manifest sets `usesVolume: true`. */
  readonly volume?: number;
}

interface InputBase {
  label: string;
  /** Shown with the input on the info page; give every input one. */
  description?: string;
}
export type Input =
  | (InputBase & { type: 'integer'; default: number; min?: number; max?: number; step?: number })
  | (InputBase & { type: 'number'; default: number; min?: number; max?: number; step?: number })
  | (InputBase & { type: 'boolean'; default: boolean })
  | (InputBase & { type: 'select'; default: string; options: readonly string[] })
  | (InputBase & { type: 'source'; default: PriceSource })
  | (InputBase & { type: 'text'; default: string })
  /**
   * A moment, as Unix seconds (an anchor such as an anchored VWAP's start). The user picks a New York
   * date and time in the settings; 0 means not set, so give the indicator a sensible fallback.
   */
  | (InputBase & { type: 'time'; default: number });

/**
 * Schema v2: one extra bar series of the chart's symbol at another bar size,
 * loaded beside the chart's own bars and read as `ctx.auxiliary.<alias>`.
 */
export interface AuxiliarySource {
  /**
   * A Spectral bar size of 1 min or longer, e.g. `1 day`, `1 week`, `1 hour`; or `chart` for the chart's own bar
   * size (more history than the chart loaded, at most `2 W`; empty on seconds charts).
   */
  barSize: string;
  /** History to load, e.g. `2 Y` or `3 W` (at most 365 D, 52 W or 12 M; use Y beyond); capped per bar size. */
  duration: string;
  /** Regular trading hours only. Default true. */
  useRth?: boolean;
  /** Market data the bars are built from. Default: the chart's own (usually `TRADES`). */
  whatToShow?: 'TRADES' | 'MIDPOINT' | 'BID' | 'ASK' | 'BID_ASK';
  /**
   * Keep the series updating while the chart is open. Default false: a snapshot loaded with the chart, whose
   * still-forming last bar is left out while the chart updates live (it would never refresh).
   */
  keepUpToDate?: boolean;
  /**
   * Load the series only while every `all` and at least one `any` condition holds: a boolean input key holds while
   * the input is on, `{ input, in }` while the select input has one of the listed options.
   */
  when?: { all?: readonly AuxiliaryCondition[]; any?: readonly AuxiliaryCondition[] };
}

/** A boolean input key, or a select input key with some of its options, e.g. `{ input: 'period', in: ['Weekly'] }`. */
export type AuxiliaryCondition = string | { input: string; in: readonly string[] };

/**
 * Auxiliary bars by alias, oldest first. Every declared alias is present: a
 * series switched off by its `when` conditions reads as an empty array, and the
 * last bar can be the current, incomplete period. Spectral draws the indicator
 * once every active series has loaded; a series that cannot load (for example
 * ASK data for an index) shows a load error instead. Empty object for schema v1.
 */
export type AuxiliaryBars = Readonly<Record<string, readonly Bar[]>>;

/**
 * Draw a plot or zone this many bars later (positive, into the empty space right of the last bar, like
 * Ichimoku's leading spans) or earlier (negative, like its lagging span): a whole number from -500 to 500,
 * or the key of an integer input that sets it, optionally negated and adjusted by whole bars
 * (`'displacement'`, `'-displacement'`, `'displacement-1'`, `'-displacement+1'`). Such an input only moves
 * the drawing; `calculate` always sees its default, so compute the series unshifted and let the offset place it.
 */
export type Offset = number | string;

/**
 * How a plot treats a `null`: `'bridge'` (default) joins the line across it, `'break'` ends the line there and
 * starts it again at the next value (separate segments, like up and down trend lines).
 */
export type Gaps = 'bridge' | 'break';

/** A plot of a schema v1 or v2 file. */
export interface PlotV1 {
  label: string; color: HexColor; lineWidth?: number; lineStyle?: LineStyle; primary?: boolean; offset?: Offset; gaps?: Gaps;
}
/** A plot of a schema v3 file: the v1/v2 fields plus `style` and `palette` (schema v3 only). */
export interface Plot extends PlotV1 {
  /** Schema v3: how the series is drawn (`'area'` and `'histogram'` from the pane's zero line). Default `'line'`. */
  style?: PlotStyle;
  /** Schema v3: palette `result.colors.<plotKey>` picks a color from per bar. */
  palette?: string;
}
/** A level of a schema v1 or v2 file. */
export interface LevelV1 {
  label: string; color: HexColor; lineWidth?: number; lineStyle?: LineStyle; showValue?: boolean;
}
/** A level of a schema v3 file: the v1/v2 fields plus `labelStyle` (schema v3 only). */
export interface Level extends LevelV1 {
  /** Schema v3: `'inline'` draws the label and price on the line at the right edge instead of a value-axis chip (price pane only). */
  labelStyle?: 'axis' | 'inline';
}
/** A zone of a schema v1 or v2 file. */
export interface ZoneV1 {
  label: string; color: HexColor; opacity?: number; offset?: Offset;
}
/** A zone of a schema v3 file: the v1/v2 fields plus `palette` (schema v3 only). */
export interface Zone extends ZoneV1 {
  /** Schema v3: palette `result.colors.<zoneKey>` picks a fill color from per bar. */
  palette?: string;
}
/** A marker key of a schema v1 or v2 file: a dot. */
export interface MarkerV1 {
  label: string; color: HexColor; radius?: number;
}
/** A marker key of a schema v3 file: the dot, or a shape with the fields below (schema v3 only). */
export interface Marker extends MarkerV1 {
  /**
   * Schema v3 (the fields below): any of them draws a shape instead of the dot (`radius` then does not apply).
   * The drawn shape, default `'circle'`; `'char'` draws `char`.
   */
  shape?: MarkerShape;
  /** The one visible character a `shape: 'char'` marker draws. */
  char?: string;
  /** 6, 9, 12 or 16 px; default `'small'`. */
  size?: 'tiny' | 'small' | 'normal' | 'large';
  /** `'aboveBar'`/`'belowBar'`: just above the bar's high or below its low (`value` may be omitted). Default `'absolute'`. */
  placement?: 'absolute' | 'aboveBar' | 'belowBar';
  /** Palette a marker's `palette` index picks from. */
  palette?: string;
  /** Hide the markers while bars are narrower than this many pixels (0-40). */
  hideBelowBarWidth?: number;
}
export interface Column { label: string; color: HexColor }
/**
 * Schema v2: volume at price, drawn as horizontal rows on the price pane (at most 4, `pane: 'price'`).
 * `placement: 'range'` returns complete profiles drawn inside their own bars (a session, a fixed
 * range); `'visible'` returns each bar's volume on one price grid, and Spectral sums the bars on
 * screen and draws that profile at the right edge, so it follows scrolling and zooming.
 */
export interface Profile {
  label: string;
  color: HexColor;
  /** Color of the volume traded on up bars; give rows an `up` share to use it. */
  upColor?: HexColor;
  /** Fill opacity from 0 to 1. Default 0.35. */
  opacity?: number;
  placement: 'range' | 'visible';
}
/** One price row of a complete profile; `up` is the part of `volume` traded on up bars. */
export interface ProfileRow { low: number; high: number; volume: number; up?: number }
/** A complete profile over bars `fromIndex` to `toIndex`, with its value area when it has one. */
export interface RangeProfile {
  fromIndex: number;
  toIndex: number;
  /** At most 1,000 rows; at most 16,000 rows over all profiles of one output. */
  rows: readonly ProfileRow[];
  valueAreaLow?: number;
  valueAreaHigh?: number;
}
/**
 * Per-bar volume on one price grid: row `r` spans `priceLow + r * rowHeight` to one row higher.
 * `bars[i]` is null or `{ row, volume, up? }`: bar i's volume in rows `row`, `row + 1`, ... At most
 * 64,000 numbers in all `volume` arrays together; pick `rowHeight` so the grid stays within that.
 */
export interface VisibleProfile {
  priceLow: number;
  rowHeight: number;
  /** Rows drawn: the grid rows the bars on screen touch are grouped into this many (1 to 1,000). */
  rows: number;
  /** Percent of the visible volume drawn as the value area around the point of control (e.g. 70). */
  valueArea?: number;
  bars: ReadonlyArray<{ row: number; volume: readonly number[]; up?: readonly number[] } | null>;
}
/** Schema v3 drawing elements: plain data Spectral draws; text is checked like manifest text. */
export type TextSize = 'small' | 'normal' | 'large';
export type TextAlign = 'left' | 'center' | 'right';
export type PanePosition = 'top-left' | 'top-center' | 'top-right' | 'middle-left' | 'middle-center' | 'middle-right'
  | 'bottom-left' | 'bottom-center' | 'bottom-right';
export type PlotStyle = 'line' | 'step' | 'circles' | 'cross' | 'area' | 'histogram';
export type MarkerShape = 'circle' | 'square' | 'diamond' | 'triangleUp' | 'triangleDown' | 'arrowUp' | 'arrowDown'
  | 'cross' | 'x' | 'flag' | 'char';
/** A bar index; `'right-edge'` follows the last visible bar (a segment: the newest bar); an index past the last bar projects into the empty space (at most 500). */
export type BarAnchor = number | 'right-edge';

/** Named colors (1-8); elements pick one by index (0-based), and every color is a user setting `<paletteKey>Color<N>`. */
export interface Palette { label: string; colors: readonly HexColor[] }

export interface TableColumn { align?: TextAlign; /** Least width in characters, 2-32 (a longer cell widens the column). */ width?: number }
/** A table anchored to the pane (at most 4); the user can move it with the `<key>Position` setting. */
export interface Table {
  label: string; position: PanePosition; columns: readonly TableColumn[];
  textSize?: TextSize; font?: 'mono' | 'sans'; color?: HexColor; textColor?: HexColor; opacity?: number; border?: boolean;
  /** Pixels from the anchored pane edge, 0-200. */
  offsetX?: number; offsetY?: number;
}
export type TableCell = string | number | null
  | { text: string; palette?: number; textPalette?: number; align?: TextAlign; weight?: 'normal' | 'bold'; tooltip?: string };
/** At most 32 rows, 256 cells, 32 characters per cell and 4,096 per table (cell tooltips count too). */
export interface TableData { palette?: string; rows: ReadonlyArray<ReadonlyArray<TableCell>> }

/**
 * A label key (schema v3). `color` fills the box, pin or arrow (or colours the text of `style: 'none'`), and is the
 * setting `<key>Color`; an item's `palette` index picks from `palette` instead. Defaults: `style: 'box'`,
 * `placement: 'above'`, white text, `textSize: 'normal'`, `font: 'mono'`.
 */
export interface Label {
  label: string; color: HexColor; textColor?: HexColor; textSize?: TextSize; font?: 'mono' | 'sans';
  style?: 'none' | 'box' | 'pin' | 'arrow'; placement?: 'above' | 'below' | 'left' | 'right' | 'center';
  palette?: string; hideBelowBarWidth?: number;
  /** Most labels drawn at once, the newest win (1-2,000; default 200). */
  maxVisible?: number;
}
/**
 * At most 2,000 per key, 48 characters and 3 lines each. `value` may be a pane edge. `tooltip` (at most 48 characters
 * in 3 lines, like every tooltip) shows while the pointer is over the label.
 */
export interface LabelItem { index: BarAnchor; value: number | 'top' | 'bottom'; text: string; palette?: number; tooltip?: string }
/**
 * A shape marker: `value` may be left out when the marker is placed `aboveBar`/`belowBar`; `palette` picks its colour;
 * `tooltip` shows while the pointer is over it. At most 4,000 per key (a dot key: 20,000), 64,000 over all keys. A dot
 * marker (no `shape`) reads `{ index, value }` only.
 */
export interface MarkerItem { index: number; value?: number; palette?: number; tooltip?: string }

/** Recolors the chart's candles per bar (price pane, at most 2; the first declared non-null wins). */
export interface BarColors { label: string; palette: string }
/** Shades the pane background per bar (at most 2); opacity 0-0.6. */
export interface BgColors { label: string; palette: string; opacity?: number }

export interface Segment { label: string; color: HexColor; lineWidth?: number; lineStyle?: LineStyle; extend?: 'none' | 'right' | 'left' | 'both'; palette?: string }
/**
 * `x1`/`x2` are bar indexes (at most 500 past the last bar); `x2` may be `'right-edge'`: the segment ends at the newest
 * loaded bar (a live leg; scrolled back, it runs off the right of the view at the same slope). At most 2,000 per key.
 */
export interface SegmentItem { x1: number; y1: number; x2: BarAnchor; y2: number; palette?: number }
export interface Box {
  label: string; color: HexColor; borderColor?: HexColor; opacity?: number; lineWidth?: number; textSize?: TextSize;
  extend?: 'none' | 'right'; palette?: string; hideBelowBarWidth?: number;
}
/** At most 2,000 per key; box text at most 32 characters; `tooltip` shows while the pointer is over the box. */
export interface BoxItem { x1: number; y1: number; x2: BarAnchor; y2: number; text?: string; palette?: number; tooltip?: string }

export interface Preset {
  id: string;
  name: string;
  shortName: string;
  inputs: Readonly<Record<string, number | boolean | string>>;
}

export interface TimeInfo {
  /** New York calendar date, `YYYY-MM-DD`. */
  dateKey: string;
  /** The New York date of the Monday that starts the bar's week, `YYYY-MM-DD` (a Sunday belongs to the week that began on the Monday before it). */
  weekKey: string;
  /** Minutes since New York midnight. */
  minutes: number;
}

/**
 * Plain data `ta.scan` carries from bar to bar: null, booleans, numbers, strings of at most 64 characters, and
 * arrays or plain objects of them; at most 256 values in all (containers included), nested at most 4 levels. Over a
 * whole run one scan may copy at most 2,000,000 state values (R-SCAN-STATE); a step that returns its state unchanged
 * copies nothing.
 */
export type ScanState = null | boolean | number | string | readonly ScanState[] | { readonly [key: string]: ScanState };

/**
 * Pure, bar-aligned technical-analysis helpers. Every function returns an array with one entry per input.
 * On a live tick `calculate` sees only its `live.lookback` window: `sum`, `stdev`, `wma`, `highest` and `lowest` need
 * `length - 1` bars before a bar, `change` and `percentRank` `length`, `trueRange` and `crossover`/`crossunder` 1;
 * `sma`, `ema`, `rma`, `rsi`, `atr`, `sessionVwap`, `cum` and `scan` carry their state from the bar close.
 */
export interface Ta {
  source(bars: readonly Bar[], source: PriceSource): number[];
  sma(values: Series, length: number): (number | null)[];
  ema(values: Series, length: number): (number | null)[];
  rma(values: Series, length: number): (number | null)[];
  wma(values: Series, length: number): (number | null)[];
  stdev(values: Series, length: number): (number | null)[];
  sum(values: Series, length: number): (number | null)[];
  highest(values: Series, length: number): (number | null)[];
  lowest(values: Series, length: number): (number | null)[];
  change(values: Series, length?: number): (number | null)[];
  rsi(values: Series, length: number): (number | null)[];
  trueRange(bars: readonly Bar[]): (number | null)[];
  atr(bars: readonly Bar[], length: number): (number | null)[];
  /** Session-anchored VWAP (resets at each New York trading date). Requires `usesVolume: true`. */
  sessionVwap(bars: readonly Bar[]): (number | null)[];
  crossover(a: Series, b: Series | number): boolean[];
  crossunder(a: Series, b: Series | number): boolean[];
  /** Running total of the finite values: null before the first one, then a null entry adds nothing. */
  cum(values: Series): (number | null)[];
  /**
   * Percent (0-100) of the previous `length` values that are at or below the current one (TradingView
   * `percentrank`); null for the first `length` bars and while any of those values is null.
   */
  percentRank(values: Series, length: number): (number | null)[];
  /**
   * Carry a value from bar to bar (a running total, a trend direction, a trailing stop): `step` receives the
   * previous state (`initial` before the first item), the item and its index, and returns the next state.
   * Returns every item's state, oldest first; each state is a frozen copy of plain data (see `ScanState`).
   * Keep everything a bar inherits from earlier bars in a scan state rather than in your own variables.
   * `index` counts from the first bar of the whole history, also on a live tick, where `ctx.bars` is a short
   * window: read the bar from `item`, never `ctx.bars[index]`. Return `state` itself when nothing changed (no copy).
   */
  scan<S extends ScanState, T>(items: readonly T[], initial: S, step: (state: S, item: T, index: number) => S): S[];
}

export interface TimeApi {
  ny(bar: Bar): TimeInfo;
  /** True inside the New York regular session (09:30-16:00; 09:30-13:00 on NYSE early-close days). */
  isRegularSession(bar: Bar): boolean;
  /** Unix seconds of the New York midnight that starts the bar's New York date (`ny(bar).dateKey`). */
  dayStart(bar: Bar): number;
  /** Unix seconds of the New York midnight that starts the Monday of the bar's week (`ny(bar).weekKey`). */
  weekStart(bar: Bar): number;
}

export interface Context {
  readonly bars: readonly Bar[];
  /** Schema v2: the bars of each declared `auxiliary` series, by alias. */
  readonly auxiliary: AuxiliaryBars;
  /** Declared inputs, defaults applied and numeric values clamped to their ranges. */
  readonly inputs: Readonly<Record<string, number | boolean | string>>;
  /** The chart's bar size as Spectral names it, e.g. `1 min`, `5 mins`, `1 day`. */
  readonly barSize: string;
  readonly ta: Ta;
  readonly time: TimeApi;
}

/**
 * Schema v3: deterministic number-to-text helpers for tables, labels and tooltips (no locale: the same text on every
 * machine). `null`, `NaN` and `Infinity` give `'n/a'`; `decimals` is a whole number from 0 to 6. The text never holds
 * 8 digits in a row (integer parts from 10,000,000 are grouped by thousands), so it passes the check drawn text gets.
 */
export interface Format {
  /** `value` rounded to `decimals` (default 2): `1234.5` → `'1234.50'`. */
  number(value: number | null, decimals?: number): string;
  /** A price as the chart's axis writes one: two decimals, four below 1. */
  price(value: number | null): string;
  /** A ratio as a percentage with `decimals` (default 2): `0.0123` → `'1.23%'`. */
  percent(value: number | null, decimals?: number): string;
  /** Short magnitudes: `950`, `12.35`, `1.2K`, `3.4M`, `5B`, `1.1T`. */
  compact(value: number | null): string;
  /** Rounded to a whole number and grouped by thousands: `'12,345,678'`. */
  thousands(value: number | null): string;
}

/** The ctx a schema v3 file's `calculate` receives: the v1/v2 ctx plus `format`. */
export interface ContextV3 extends Context {
  readonly format: Format;
}

/** What `calculate` of a schema v1 or v2 file returns: plots, levels, zones, dot markers, columns and (v2) profiles. */
export interface ResultV1 {
  /** One series per declared plot key, each `bars.length` long. */
  plots?: Record<string, Series>;
  /**
   * One price per declared level key; `null` hides the level. A plain number
   * spans the whole chart; `{ price, fromIndex }` starts the level at bar
   * `fromIndex` and extends it to the right edge. `{ price, fromTime }` starts it
   * at the first bar at or after `fromTime` (Unix seconds, e.g.
   * `ctx.time.dayStart(bar)`): at the left edge when that is before the first
   * bar, hidden when it is after the last one. Give `fromIndex` or `fromTime`,
   * not both.
   */
  levels?: Record<string, number | { price: number; fromIndex?: number; fromTime?: number } | null>;
  zones?: Record<string, { upper: Series; lower: Series }>;
  /** Marker positions by bar index. */
  markers?: Record<string, ReadonlyArray<{ index: number; value: number }>>;
  columns?: Record<string, Series>;
  /** Schema v2. Per declared profile key: the profiles of a `range` profile, or the bins of a `visible` one; null hides it. */
  profiles?: Record<string, ReadonlyArray<RangeProfile> | VisibleProfile | null>;
}

/** What `calculate` of a schema v3 file returns: the v1/v2 result plus the drawing elements (schema v3 only). */
export interface Result extends Omit<ResultV1, 'markers'> {
  /** Marker positions by bar index (a shape marker: `MarkerItem`). */
  markers?: Record<string, ReadonlyArray<{ index: number; value: number } | MarkerItem>>;
  /**
   * Schema v3, drawn. Per plot or zone key that declares `palette`: one palette index (or null: its own color) per
   * bar. A plot segment takes the color of the bar it ends on.
   */
  colors?: Record<string, Series>;
  /**
   * Schema v3, drawn. Per declared table key: its rows, or null to hide it. A number cell is written like
   * `ctx.format.number` (whole numbers without decimals, others with two); every cell text must pass the drawn-text
   * check (`R-TEXT-UNSAFE`), so write numbers with `ctx.format`.
   */
  tables?: Record<string, TableData | null>;
  /**
   * Schema v3, drawn. Per declared label key: its labels (absent or null: none). Each is anchored to bar `index`
   * (an index up to 500 past the last bar draws in the empty space on the right; `'right-edge'` follows the last
   * visible bar) and to `value`, or to the pane's `'top'` or `'bottom'` edge. Every text must pass the drawn-text
   * check (`R-TEXT-UNSAFE`), so write numbers with `ctx.format`.
   */
  labels?: Record<string, ReadonlyArray<LabelItem> | null>;
  /** Schema v3, drawn. Per declared barColors key: one palette index (or null: the chart's colors) per candle. */
  barColors?: Record<string, Series>;
  /** Schema v3, drawn. Per declared bgColors key: one palette index (or null: unshaded) per bar of the pane. */
  bgColors?: Record<string, Series>;
  /**
   * Schema v3, drawn. Per declared segment key: its segments (absent or null: none), each between two bar + value
   * anchors; a segment's `x2` may be `'right-edge'`.
   */
  segments?: Record<string, ReadonlyArray<SegmentItem> | null>;
  /** Schema v3, drawn. Per declared box key: its boxes (absent or null: none); a box's `x2` may be `'right-edge'`. */
  boxes?: Record<string, ReadonlyArray<BoxItem> | null>;
}

interface IndicatorBase {
  id: string;
  name: string;
  shortName: string;
  version: string;
  author: string;
  description: string;
  pane: 'price' | 'oscillator';
  /**
   * How the indicator follows the forming bar. `{ lookback }`: a tick reruns `calculate` on the last `lookback + 1`
   * completed bars plus the forming bar (the extra, last completed bar is the one whose value the chart joins), so
   * `lookback` is how many bars before the forming bar calculate reads
   * (whole bars, or a sum of whole numbers, integer input keys that have a `max`, and `N*key`, e.g.
   * `'length + 1'`; at most 5,000 bars with those inputs at their max). Omitted: `{ lookback: 0 }`. `'none'`:
   * completed bars only.
   * `barCloseWhen` names settings that update at bar close only, for a mode no lookback covers: a boolean input
   * key (while it is on) or `{ input, in }` with some options of a select input; every other setting is live.
   */
  live?: 'none' | { lookback: number | string; barCloseWhen?: string | { input: string; in: string[] } };
  usesVolume?: boolean;
  inputs?: Record<string, Input>;
  columns?: Record<string, Column>;
  presets?: readonly Preset[];
  /**
   * The indicator's info page in Spectral: overview, how to read it, settings and limitations, notes.
   * Plain text for a trader; a blank line starts a new paragraph.
   */
  docs?: { overview: string; howToRead?: string; settings?: string; notes?: string };
}

/** The outputs and `calculate` of a schema v1 or v2 file: no schema v3 fields, no `ctx.format`. */
interface IndicatorV1Outputs {
  plots?: Record<string, PlotV1>;
  levels?: Record<string, LevelV1>;
  zones?: Record<string, ZoneV1>;
  markers?: Record<string, MarkerV1>;
  calculate(ctx: Context): ResultV1;
}

/** A schema v1 file: the chart's own bars only. */
export interface IndicatorV1 extends IndicatorBase, IndicatorV1Outputs {
  schemaVersion: 1;
}

/** A schema v2 file: v1 plus `auxiliary` bar series of other bar sizes (at most 4) and volume `profiles`. */
export interface IndicatorV2 extends IndicatorBase, IndicatorV1Outputs {
  schemaVersion: 2;
  /** Keys are aliases (camelCase, at most 14 characters) read as `ctx.auxiliary.<alias>`. */
  auxiliary?: Record<string, AuxiliarySource>;
  profiles?: Record<string, Profile>;
}

/**
 * A schema v3 file: v2 plus drawing elements (tables, labels, bar and background colors, segments, boxes; plot
 * styles and marker shapes) and their palettes. This Spectral version draws every one of them.
 */
export interface IndicatorV3 extends IndicatorBase {
  schemaVersion: 3;
  plots?: Record<string, Plot>;
  levels?: Record<string, Level>;
  zones?: Record<string, Zone>;
  markers?: Record<string, Marker>;
  auxiliary?: Record<string, AuxiliarySource>;
  profiles?: Record<string, Profile>;
  palettes?: Record<string, Palette>;
  tables?: Record<string, Table>;
  labels?: Record<string, Label>;
  barColors?: Record<string, BarColors>;
  bgColors?: Record<string, BgColors>;
  segments?: Record<string, Segment>;
  boxes?: Record<string, Box>;
  calculate(ctx: ContextV3): Result;
}
```
