Charts / 02

Custom indicators

Write your own chart indicators in plain JavaScript, or let an LLM write them from this page, and install them from the Indicators toolbox.

Charts / Custom indicators

Your own indicators, in JavaScript.

A Spectral custom indicator is one JavaScript file: a small manifest that describes the indicator and a calculate function that computes it. Add the file in the Indicators toolbox; Spectral checks it against the rules on this page, keeps a copy, and lists it next to the built-in indicators in every chart window, and keeps it after a restart. There is no proprietary scripting language to learn, and you can let an LLM write the file for you.

Looking for a ready-made one? The Indicator store lists every Spectral indicator with its source, to copy, download and adapt.

Indicators you write, or have an LLM write for you, are yours. The example and store indicator files and the type declarations (spectral-indicator.d.ts) are MIT-0: free to use, change and share, without attribution. Spectral itself, including the engine that runs them, stays proprietary.

01
Quick start

Add an indicator file.

  1. Open a chart, click Indicators, and find the Custom indicators section at the top of the toolbox.
  2. Click Add file… and pick a .js file. Spectral checks it before anything is installed, including that its live updates are exact and fast; a rejected file opens a report with every finding and how to fix it.
  3. A passing file appears in the custom section and in the indicator list, marked Custom. Click Add to put it on the chart.
  4. Open its settings on the chart to change inputs and colors. The ⓘ button in the toolbox opens its info page, where Download file saves a copy of the installed file.
  5. Edit the file any time, then click Reload on its row. Remove uninstalls it; charts and boxes that still reference it show it as unavailable until you add it again.

Spectral keeps an immutable copy of the file, so moving or editing the original never changes the chart until you reload. Custom indicators are stored on this computer and are not part of a Spectral archive.

02
Let an LLM write it

Describe the indicator; link this page.

The toolbox's Copy LLM prompt button copies the prompt below. Paste it into your assistant, replace the last line with what you want, and save the answer as a .js file. If Spectral rejects the file, open the report, click Copy fix prompt, and paste that back: it contains every finding with its line and the sentence that fixes it.

The prompt sends the LLM to the Indicator store first, through its machine-readable catalog. If an indicator already does what you describe, you get a link to it; if one is close, the LLM adapts its file instead of starting from scratch.

Write a Spectral custom indicator as one JavaScript ES module file (.js).
Read the format first: https://spectral.trade/docs/custom-indicators (machine-readable: https://spectral.trade/docs/custom-indicators.llm.md).
Check the store first: https://spectral.trade/indicators/catalog.llm.md lists every published Spectral indicator with its source URL. If one already does this, say so and link its page instead of writing code; if one is close, fetch its .js and adapt it (new id, name and version). Otherwise write a new file.
Rules: schemaVersion 3; exactly one `export default { ...manifest, calculate(ctx) { ... } }`; manifest values are literals; no import, async, network, timers or globals; calculate returns arrays aligned with ctx.bars (null where undefined); colors are #RRGGBB. Daily, weekly or other higher-timeframe values come from declared `auxiliary` bar series (ctx.auxiliary), never from resampling ctx.bars.
Drawing elements (read "Drawing elements" in the reference): a table, text labels, marker shapes, candle or background colors, segments and boxes are declared in the manifest like plots and returned by calculate; write numbers in drawn text with ctx.format.
Live updates (read "Fast live updates" in the reference first): declare live: { lookback: <bars calculate reads before the forming bar> } or 'none', carry values from bar to bar only through ctx.ta.scan, ctx.ta.cum or the recursive helpers (scan steps read item, not ctx.bars[index]), anchor day and week levels with { price, fromTime }, and never use Date, Math.random or values kept between runs (create every value inside calculate); Spectral rejects a file whose live update differs from a full recalculation or is too slow.
Performance (read "Performance and limits" in the reference): keep drawing small (items where they matter, not 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, so draw text only on bars that matter, never on every bar. Make the cost independent of the bar size, price level, gaps in time and options; the limits and draw budgets are listed there.
Documentation: fill docs.overview, docs.howToRead and docs.settings, and give every input a description. Spectral shows them on the indicator's info page, so write them for a trader.
Answer with the complete file in one code block, ready to save as <id>.js, and check it against the checklist in the reference first.
Indicator I want: <describe what it computes, which pane it belongs on, its inputs with defaults, and the plots, levels, markers or drawing elements it draws>

The machine-readable reference at https://spectral.trade/docs/custom-indicators.llm.md contains the full format, every rule, all error codes and the complete examples in one file.

03
File format

One default export: manifest plus calculate.

/** @type {import('./spectral-indicator').IndicatorV3} */
export default {
  schemaVersion: 3,
  id: 'ema-ribbon',               // lowercase slug, 3-48 chars
  name: 'EMA Ribbon',
  shortName: 'Ribbon',            // shown on the chart
  version: '1.0.0',
  author: 'Your name',
  description: 'Three EMAs with a shaded band between fast and slow.',
  pane: 'price',                  // 'price' or 'oscillator'
  inputs: {
    fast: { type: 'integer', label: 'Fast length', default: 8, min: 1, max: 500 },
    slow: { type: 'integer', label: 'Slow length', default: 55, min: 1, max: 500 },
    source: { type: 'source', label: 'Source', default: 'close' },
  },
  plots: {
    fast: { label: 'Fast EMA', color: '#58A6FF', primary: true },
    slow: { label: 'Slow EMA', color: '#F0883E' },
  },
  zones: { ribbon: { label: 'Ribbon', color: '#58A6FF', opacity: 0.08 } },
  docs: { overview: 'Two EMAs; the ribbon spans them.' },
  calculate(ctx) {
    const source = ctx.ta.source(ctx.bars, ctx.inputs.source);
    const fast = ctx.ta.ema(source, ctx.inputs.fast);
    const slow = ctx.ta.ema(source, ctx.inputs.slow);
    const upper = fast.map((v, i) => (v === null || slow[i] === null ? null : Math.max(v, slow[i])));
    const lower = fast.map((v, i) => (v === null || slow[i] === null ? null : Math.min(v, slow[i])));
    return { plots: { fast, slow }, zones: { ribbon: { upper, lower } } };
  },
};
  • Manifest values are literals. Strings, numbers, booleans, arrays and plain objects; no expressions, calls or spreads. Only calculate is code.
  • Top level holds only function declarations, const helpers bound to literals or functions, and the default export.
  • Not allowed: import, import(), named exports, async/await, generators, eval, new Function, debugger, prototype or constructor access, and host globals such as fetch, window, globalThis, timers, crypto or performance.
  • Allowed: ctx, Math, Number, Array, Object, Map, Set, JSON, string and array methods, and your own helper functions.
04
Manifest reference

Fields and limits.

FieldRequiredRule
schemaVersionyes3 for new files, which can use every drawing element. Files with 1 or 2 keep working; 1 cannot declare auxiliary and neither can use drawing elements.
idyes3-48 characters: lowercase letters, digits and single hyphens, starting with a letter. Stable identity of the indicator; re-importing the same id replaces the indicator and keeps chart settings and boxes working.
name, shortName, author, description, versionyesUp to 80 / 20 / 48 / 240 / 20 characters. Plain text: no long letter-digit runs, account-like tokens or hashes.
paneyes'price' draws on the candles; 'oscillator' opens its own pane below.
liveno{ lookback } updates every tick on a short window of recent bars (omitted means { lookback: 0 }); the lookback is a whole number, or a string that names integer inputs that have a max, alone or summed with whole numbers and N*key terms, such as 'length', 'length + 1' or '2*length + signal', optionally with barCloseWhen settings; 'none' updates at bar close from completed bars only. See Fast live updates.
usesVolumenotrue exposes bar.volume and enables ta.sessionVwap.
inputsnoUp to 24 user settings; see Inputs.
plots, levels, zones, markers, columns, profilesat least oneWhat the chart draws; see Outputs.
palettes, tables, labels, barColors, bgColors, segments, boxesnoSchema v3 drawing elements and the named colors they pick from; see Drawing elements.
presetsnoUp to 8 { id, name, shortName, inputs } variants; each appears as its own toolbox entry.
auxiliarynoSchema v2 or later. Up to 4 extra bar series of the chart's symbol at another bar size, for example daily or weekly bars on a 5-minute chart; see Daily, weekly and other bar sizes.
docsno (recommended)overview (required), howToRead, settings, notes; up to 2,000 characters each. They become the indicator's info page; see The info page.
05
Inputs

Settings the user can change.

Every input needs type, label and default. Keys are camelCase (up to 21 characters) and must not collide with a generated color setting such as fastColor. Spectral renders them as a form in the indicator's settings panel and hands the values to calculate as ctx.inputs, with numbers clamped to their range.

typeExtra fieldsValue in ctx.inputs
integermin, max, step (integer bounds)Rounded, clamped number
numbermin, max, stepClamped number
boolean—Boolean (a switch)
selectoptions: 1-16 unique stringsOne of the options
source—'open' | 'high' | 'low' | 'close' | 'hlc3'; pass it to ta.source
text—String up to 64 characters
time—A moment as Unix seconds, 0 when not set; the settings panel shows a New York date and time. Use it for anchors such as an anchored VWAP's start.
06
Outputs

What the chart draws.

Declare outputs in the manifest and return exactly those keys from calculate. Keys are camelCase (up to 14 characters) and unique across families; colors are #RRGGBB and become user settings.

FamilyMaxManifest entrycalculate returns
plots16{ label, color, lineWidth?, lineStyle?, primary?, offset?, gaps? }One number or null per bar. Exactly one plot is primary (or the first); it carries the indicator's main style and axis label. offset draws the series that many bars later (into the space right of the last bar) or earlier: a whole number, or an integer input's key, optionally negated and adjusted ('-displacement+1'). A line joins across null values; gaps: 'break' ends it there instead (separate up and down segments).
levels16{ label, color, lineWidth?, lineStyle?, showValue?, labelStyle? }number | null: a horizontal line across the pane; null hides it. Schema v3 adds labelStyle: 'axis' (default, a chip on the value axis) or 'inline' (the label and price on the line at the right edge, price pane only). { price, fromTime } starts the line at the first bar at or after fromTime (Unix seconds, for example ctx.time.dayStart(bar)) and runs it to the right edge; anchor a level of a day or week this way. { price, fromIndex } starts it at bar fromIndex, for example the last bar.
zones8{ label, color, opacity?, offset? } (opacity 0-0.8){ upper, lower }, two series; the band between them is filled. offset shifts it like a plot.
markers8{ label, color, radius? } (radius 2-8)Array of { index, value }: a dot at bar index and price value.
columns8{ label, color }One number or null per bar, drawn as histogram bars. Oscillator pane only. Several columns color one histogram (for example rising and falling bars): per bar, the first declared column with a value is drawn, so put each bar's value in one column and null in the others.
profiles4{ label, color, upColor?, opacity?, placement } (opacity 0-1)Volume at price as horizontal rows, schema v2 or later, price pane only. placement: 'range' returns complete profiles { fromIndex, toIndex, rows, valueAreaLow?, valueAreaHigh? }, drawn inside their own bars; 'visible' returns each bar's volume on one price grid, and Spectral sums the bars on screen and draws the profile at the right edge.
  • Every series has exactly ctx.bars.length entries, in bar order. Use null where a value is not defined yet; non-finite numbers count as null.
  • lineWidth is 0.5-8; lineStyle is 'solid', 'dashed' or 'dotted'.
  • offset moves 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 (Ichimoku's leading spans) or offset: -26 to draw it earlier (its lagging span). Use a whole number from -500 to 500, or the key of an integer input; such an input only moves the drawing, and calculate sees its default.
  • A profile row is { low, high, volume, up? }, where up is the share traded on up bars (drawn in upColor). A 'visible' profile returns { priceLow, rowHeight, rows, valueArea?, bars }: bars[i] is null or { row, volume, up? } with that bar's volume in grid rows row, row + 1, and so on; rows is how many rows to draw and valueArea the value-area percentage. Keep all its volumes under 64,000 numbers by choosing rowHeight. Draw the point of control and the value-area edges as levels.
  • A violation at runtime disables that indicator with a readable code and a Reload action; the chart and the other indicators keep working.
07
Drawing elements

Tables, labels, colors, lines and boxes.

Schema v3 adds drawing elements: a table of values on the pane, text labels, candles and backgrounds colored per bar, line segments, boxes, plot styles and marker shapes, and the palettes they take their colors from. They are plain data that calculate returns; Spectral measures, culls and paints them, so an indicator never gets a canvas. Declare schemaVersion: 3 to use them; a schema v1 or v2 file that declares one gets E-ANNOTATION-UNSUPPORTED, and files that use none keep working unchanged. The reference ("Drawing elements" in section 4) gives every field, limit and default.

FieldMaxManifest entrycalculate returns
palettes8{ label, colors } (1-8 colors)Nothing: elements name a palette and pick its colors by index (0-based). Every color becomes a setting <key>Color<N>.
tables4{ label, position, columns, textSize?, font?, color?, textColor?, opacity?, border?, offsetX?, offsetY? }{ palette?, rows } or null: up to 32 rows and 256 cells of text, numbers or { text, palette?, textPalette?, align?, weight?, tooltip? }. Anchored to one of nine pane positions ('top-left' … 'bottom-right'); the user can move it with <key>Position.
labels8{ label, color, textColor?, textSize?, font?, style?, placement?, palette?, hideBelowBarWidth?, maxVisible? }Array of { index, value, text, palette?, tooltip? }: text at a bar and a price, or at the pane edge (value: 'top' or 'bottom'); index: 'right-edge' follows the last bar. Styles 'none', 'box', 'pin', 'arrow'.
barColors2{ label, palette }One palette index or null per bar: recolors that candle. Price pane only; the first declared one with a value wins.
bgColors2{ label, palette, opacity? } (opacity 0-0.6)One palette index or null per bar: shades the pane background behind that bar.
segments8{ label, color, lineWidth?, lineStyle?, extend?, palette? }Array of { x1, y1, x2, y2, palette? }: a straight line between two bar + price anchors; extend 'left', 'right' or 'both' continues it to the pane edge.
boxes8{ label, color, borderColor?, opacity?, lineWidth?, textSize?, extend?, palette?, hideBelowBarWidth? }Array of { x1, y1, x2, y2, text?, palette?, tooltip? }: a rectangle between two anchors with optional text; x2: 'right-edge' or extend: 'right' runs it to the right edge.
  • Per-bar colors of plots and zones. Give a plot or zone palette: '<key>' and return result.colors.<plotKey>: one palette index (or null for its own color) per bar, for example green while rising and red while falling.
  • Plot styles. style is 'line' (default), 'step', 'circles', 'cross', 'area' or 'histogram'.
  • Marker shapes. shape is 'circle', 'square', 'diamond', 'triangleUp', 'triangleDown', 'arrowUp', 'arrowDown', 'cross', 'x', 'flag' or 'char' (one character in char); size is 'tiny' to 'large'; placement is 'absolute' (default, at value), 'aboveBar' or 'belowBar' (just above the high or below the low, so value may be left out; price pane only); a marker item's palette index picks its color and its tooltip is shown on hover.
  • Panes. Tables, labels, segments, boxes and bgColors draw on the indicator's pane, price or oscillator. barColors, profiles, inline level labels (labelStyle: 'inline') and aboveBar/belowBar markers are price pane only; the file is rejected with E-OUTPUT-PANE-MISMATCH otherwise.
  • Limits. At most 2,000 labels, segments or boxes per key (return the recent ones with slice(-2000)); markers: 20,000 dots per key, 4,000 shape markers per key (schema v3) and 64,000 in all (R-OUTPUT-INVALID). Label and tooltip text is at most 48 characters in 3 lines, box text one line of 32; a table takes 32 rows, 256 cells of 32 characters and 4,096 characters in all; all labels (and all boxes) together 65,536 characters.
  • Anchors. index, x1 and x2 are bar indexes; up to 500 past the last bar draws into the empty space on the right.
  • Zoom. hideBelowBarWidth (0-40 px) hides labels, markers or boxes while bars are narrower than that; a label key draws its newest maxVisible labels (default 200). Tables ignore scrolling and zooming.
  • Tooltips. Table cells, labels, boxes and shape markers take a tooltip, checked like other drawn text, and are shown on hover.
  • Text. Every drawn string passes the same identity check as manifest text (R-TEXT-UNSAFE): no 8 hexadecimal characters in a row, so write numbers with ctx.format (number, price, percent, compact, thousands; schema v3 only) instead of String(value). Text sizes are 'small', 'normal' and 'large', fonts 'mono' and 'sans'.
  • Live updates. Drawing elements follow the forming bar like every output: a table returned on a live tick replaces the last one, so compute it from values that hold on the live window, or set live: 'none'.
/** @type {import('./spectral-indicator').IndicatorV3} */
export default {
  schemaVersion: 3,
  // ... id, name, pane: 'price', live, inputs ...
  palettes: { regime: { label: 'Regime', colors: ['#2EA043', '#DA3633', '#6E7681'] } },
  tables: { regime: { label: 'Regime', position: 'top-right', columns: [{ align: 'left' }, { align: 'right' }], border: true } },
  calculate(ctx) {
    const { bars, format } = ctx;
    const adx = adxSeries(ctx, 14); // Wilder's ADX from ctx.ta, as in the complete file
    const last = bars.length - 1;
    const verdict = adx[last] !== null && adx[last] >= 25 ? { text: 'Trend', palette: 0 } : { text: 'Range', palette: 2 };
    return {
      tables: {
        regime: { palette: 'regime', rows: [['Regime', { ...verdict, weight: 'bold' }], ['ADX', format.number(adx[last], 1)]] },
      },
    };
  },
};

The complete file is examples/regime-table.js (store page).

08
calculate(ctx)

Bars, inputs and the ta library.

calculate runs inside Spectral's indicator worker with the full visible history and must be synchronous, pure and fast: its time must grow linearly with the bar count (about 50 ms for 30,000 bars is the comfortable target; the import rejects a file that grows faster, or takes more than 250 ms with any setting, every input at its max included, with R-SLOW, live: 'none' files included). A call above one second turns those settings off at that bar size for the session; a hang is cut off after 30 seconds. Unless live: 'none', it also runs on every tick of the forming bar, on a short window of recent bars with the forming bar last (see Fast live updates), so keep no state between calls and carry values from bar to bar only through ctx.ta. ctx is frozen and contains:

  • bars: { time, open, high, low, close, volume? }, oldest first, with time (the bar's open) in Unix seconds; volume only with usesVolume: true. History can be a handful of bars or tens of thousands: return null where a lookback is not yet filled instead of throwing.
  • auxiliary: the bars of every series declared in auxiliary, by name (see below); an empty object when there are none.
  • inputs: the declared inputs with defaults applied.
  • barSize: the chart's bar size as Spectral names it, from '5 secs' to '1 month' (for example '5 mins' or '1 day'). The indicator must work on every bar size.
  • ta: source, sma, ema, rma, wma, stdev, sum, highest, lowest, change, rsi, trueRange, atr, sessionVwap, crossover, crossunder, cum, percentRank and scan, which carries state from bar to bar. Each returns an array as long as its input; windowed functions return null until the window is full, while ema starts at the first bar without a warm-up. rsi and sessionVwap match Spectral's built-in indicators. The reference lists each helper's exact warm-up.
  • time: ny(bar) gives the New York date key, week key and minutes since midnight; isRegularSession(bar) is true between 09:30 and 16:00 New York time (to 13:00 on NYSE early-close days); dayStart(bar) and weekStart(bar) give the New York midnight that starts the bar's day and week (Monday), for { price, fromTime } levels.

Daily, weekly and other bar sizes

ctx.bars holds only the chart's own bars, and an intraday chart usually loads days or weeks of them: too little for a daily EMA 50, a 100-day SMA or anything weekly. With schemaVersion: 2 or 3, declare the bars you need in auxiliary. Spectral loads them beside the chart's bars, shares them with any other chart or indicator that uses the same series, and draws the indicator once they have arrived.

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'] }] } },
},
calculate(ctx) {
  const daily = ctx.auxiliary.daily;               // oldest first, like ctx.bars
  const ema21 = ctx.ta.ema(ctx.ta.source(daily, 'close'), 21);
  const latest = ema21.length > 0 ? ema21[ema21.length - 1] : null;
  return { levels: { dailyEma21: latest === null ? null : { price: latest, fromIndex: ctx.bars.length - 1 } } };
},
FieldRequiredRule
name (the key)yescamelCase, up to 14 characters; read as ctx.auxiliary.<name>.
barSizeyesA Spectral bar size of 1 minute or longer, for example '1 hour', '1 day' or '1 week'.
durationyesHistory to load, such as '2 Y' or '3 W' (at most 365 D, 52 W or 12 M; use Y beyond). The longest allowed window depends on the bar size: three weeks of 1-minute bars, six months of hourly bars, ten years of daily or weekly bars.
useRthnoRegular trading hours only; default true.
whatToShowno'TRADES', 'MIDPOINT', 'BID', 'ASK' or 'BID_ASK'; default: the chart's own.
keepUpToDatenoKeep updating the series 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.
whenno{ all?, any? } lists of conditions: load the series only while every all condition and at least one any condition holds, so a switched-off group or an unselected period loads nothing. A condition is the key of a boolean input (holds while it is on) or { input: 'period', in: ['Monthly', 'Yearly'] } for a select input (holds while one of the listed options is selected; list declared options only). Number and text inputs and the chart's bar size cannot be conditions.

A series switched off by when is an empty array; return null rather than throwing. A series that cannot load, for example ASK data for an index, shows a load error and the indicator draws nothing. The last bar can be the current, incomplete day or week, and the series is not aligned to ctx.bars: walk both by time to use a daily value per chart bar. The store's Daily & Weekly EMA Levels is a complete example.

09
Fast live updates

Live on every tick, without recomputing history.

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.

When you add the file, Spectral proves that this live result equals a full recalculation, bit for bit, and that it is fast. A file whose live updates differ or are too slow is rejected with R-LIVE-INEXACT, R-LIVE-SLOW or R-LIVE-STATE; the report names the exact output, bar and values that differed, and the lookback that would work. The proof covers every setting a user can choose: the default inputs, every preset and every select and boolean option, each integer or number input the lookback does not name at its max, all of them at their max together, and the inputs the lookback names at their min (an input without a max is tried at 10 times its default). So name in live.lookback every integer input that sets a length. After installation Spectral checks it again on real data at every bar close; an indicator that stops being exact or fast updates at bar close only, and the chart shows why and what differed. When a Spectral update changes these checks, every installed live file is checked again and updates at bar close until it passes. So write the file for the window from the start.

liveMeaning
omittedThe same as { lookback: 0 }.
{ lookback: N }Updates every tick. On a tick calculate sees N completed bars before the forming bar, plus 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 }Updates every tick, except under the settings barCloseWhen names, which update at bar close only; see Settings that update at bar close.
'none'Updates at bar close: completed bars only, the forming bar never changes the output. 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 or a streak goes through ta.scan, 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]). Take the largest need from the table below. A lookback that is too small fails the import, and the report names the smallest one that works.
  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 such as Math), nothing that changes between two runs on the same bars. Writes the source check can trace, also through an alias, a parameter or a function that returns the value, are E-LIVE-NONDETERMINISTIC unless live: 'none'; the import also runs a freshly loaded copy of a live file with its default inputs and rejects a first run that differs from a later one (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'.

Minimum lookback per helper

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

ta.scan on a live tick

step(state, item, index) reads the bar from item, never from 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. Map ctx.bars into items first when a step needs more than the bar, and use index only to tell the very first bar of the history (index === 0). Return the state itself when nothing changed: it costs no copy.

Which live to declare

What the indicator doesWrite it withlive
Averages, bands, oscillators of the recent barsctx.ta helpers{ lookback: <largest need> }
A running total (OBV, A/D, cumulative delta)ta.cum or ta.scan{ lookback: 0 }, plus 1 for a bars[i - 1] read
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 barsctx.auxiliary and { price, fromTime }{ lookback: 0 }
A rank over the last N valuesta.percentRank{ lookback: 'length' }
Marks confirmed later (fractals, pivots, zig zag), profilesplain code'none'
One mode reads every loaded bar (time-of-day averages)that mode under barCloseWhen{ lookback, barCloseWhen }

Wrong → right

// 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);
// 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 };
});
// 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);
// 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));
// 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 };

Settings that update at bar close

When one mode of an indicator reads every loaded bar, for example an average over earlier sessions, no lookback covers it. Name that mode in barCloseWhen: a boolean input key (bar close while it is on), or { input: '<select key>', in: [<some of its options>] }. Settings that match update at bar close only, every other setting on every tick. The store's Relative Volume works this way: compared with prior bars, it updates every tick; in its time-of-day modes, at bar close.

live: { lookback: 'length', barCloseWhen: { input: 'mode', in: ['Time of day', 'Time of day (cumulative)'] } },

The store page of every indicator says whether it updates every tick or at bar close.

10
Performance

A slow file only costs itself.

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 your other indicators. Spectral measures every limit below while the chart runs, or checks it when you add the file; built-in indicators are never limited. Section 7 of the reference ("Performance and limits") gives every detail.

WhatLimitPast it
One calculate call, plus Spectral's conversion of its result1,000 msThose settings are turned off at that bar size for the app session; other settings and bar sizes are measured on their own.
A full run when you add the file (every input at its max, every data shape)250 ms, growing linearly with the bars (schema v3: at most 4.5 times a quarter-size run)The file is rejected with R-SLOW.
Values one result returns (points, colors, markers, labels, boxes, segments, table cells)600,000The file is rejected with R-OUTPUT-INVALID (counted on full runs with every number input at its max); an installed file shows "Too much indicator output" for that indicator alone.
Markers20,000 dots per key, 4,000 shape markers per key (schema v3), 64,000 in allR-OUTPUT-INVALID
State one ta.scan copies over a whole run2,000,000 valuesR-SCAN-STATE
A live tick4 ms on average over 32 ticks, 12 ms at the 95th percentile, 50 ms for any one tickUpdates at bar close for a while (R-LIVE-SLOW), then live again.
Drawn at once3,000 items per indicator, 12,000 per paneThe newest items in view are drawn; the rest wait.
Tables shown per pane16The indicators added last show none.
Draw time3 ms per frame on average (8 ms on slow frames) per indicator, 12 ms per paneDrawn reduced (Throttled), then hidden (Hidden); checked again every 30 s.

Writing a fast file

  • Calculate in one pass. Use the ctx.ta helpers; never loop over all bars inside a loop over bars, over price steps or over calendar minutes. When you add the file, Spectral also times 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 up to 24 combinations of the boolean and select inputs, so the cost must not depend on the bar size, the price, gaps in time or an option.
  • Draw what matters. A marker or label on a signal, not on every bar; only the boxes and segments that are still relevant (open zones, the latest swings), and stop returning those that left the chart's price range. Each kind draws its newest items in view first, at most 2,000 markers, 400 labels, 256 boxes and 512 segments at once. hideBelowBarWidth hides dense markers and labels when you zoom out and leaves their budget to the rest. A draw limit never rejects a file: its data is kept in full.
  • Small tables. Keep a table to a few rows and change only the cells whose value changed; only those are measured again. Tables at the same position stack, all at the first table's offsets.
  • Short live ticks. A short live.lookback and no loops over many bars keep a tick to a fraction of a millisecond. A slow instance updates at bar close, tries live again after 10 bars (each further pause twice as long), and returns to live after a clean stretch.
  • A small ta.scan state. Keep it to a few numbers and return the same state object when nothing changed: that costs no copy.

Throttled, Hidden and Calculating…

  • Throttled and Hidden. A legend badge says the indicator draws reduced or not at all because it took too long to draw. That is a state of the running chart, not an error in the file: its values are still calculated, the badge's tooltip, its settings and its toolbox row say what it cost, the chart checks it again every 30 s, and Retry now draws it in full at once. Spectral remembers the reduced or hidden state for up to 30 days per file version and settings; a new version or other settings start in full.
  • Calculating… Custom indicators run on workers of their own, never beside the built-in indicators, so a slow file delays only custom indicators. The chart draws everything that is done and shows the rest as "Calculating…" until it is; one request spends at most 3 s on custom indicators, the cheapest first.
  • Live updates delayed. The line stops at its last calculated candle until the calculation catches up.
11
The info page

Document it like a built-in indicator.

Every indicator has an info page, opened from the ⓘ button in the Indicators toolbox. For a custom indicator Spectral builds it from the file, so the documentation fields deserve as much care as the code. Write for a trader: plain sentences, no code or variable names. A blank line starts a new paragraph.

Info page partComes fromWhat to write
At a glancedescriptionOne sentence: what the indicator shows.
Overviewdocs.overviewWhat it computes and from what; the formula if it is short.
How to read itdocs.howToReadHow to interpret the lines, levels, zones, colors and markers, and what it does not tell you.
Settings and limitationsdocs.settingsWhat the important inputs change, sensible values, warm-up, bar sizes or sessions it suits.
What it drawsgenerated from the outputsNothing; give every plot, level, zone, marker and column a clear label.
Notesdocs.notesAnything else, for example differences from other platforms.
Optionseach input's label, description, default and rangeA description for every input.

Spectral warns, without blocking the import, when howToRead, settings or an input description is missing (W-DOCS-INCOMPLETE).

12
Common mistakes

What usually goes wrong, and the check before you add a file.

  • Importing a library (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): keep state inside calculate.
  • Expressions in the manifest such as template literals or spreads (E-MANIFEST-NOT-LITERAL): write plain literals.
  • Colors like red, #fff or #RRGGBBAA (E-COLOR-INVALID): use 6-digit #RRGGBB.
  • An input named <plot>Color (E-KEY-COLLISION): that name is a generated color setting.
  • A series shorter than the bars, for example after slice (R-OUTPUT-LENGTH): keep one value per bar with null in the warm-up.
  • Reading bar.volume without usesVolume: true (W-VOLUME-UNDECLARED): declare it, or volume is undefined.
  • Nested loops over all bars (R-SLOW): use rolling windows or the 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 cache kept between runs (const memo = {} at the top, written by calculate; E-LIVE-NONDETERMINISTIC): create the value inside calculate, and carry values from bar to bar with ta.scan.
  • A running total, trend or stop in your own variable across a loop over bars (R-LIVE-INEXACT): carry it in ta.scan or ta.cum.
  • A live.lookback smaller than what calculate reads (R-LIVE-INEXACT): set it to at least the lookback the report names.
  • ctx.bars[index] inside a ta.scan step (R-LIVE-INEXACT): read the bar from item.
  • A day's level found by searching ctx.bars (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 them the same way on every run and mask their results instead.
  • Date or Math.random in a live indicator (E-LIVE-NONDETERMINISTIC): use ctx.time, or live: 'none'.
  • A daily or weekly value computed from intraday bars: the values are wrong or missing; declare an auxiliary series of that bar size instead.

Before you add a file, check that:

  1. It is one file with one export default, schemaVersion: 3 and a valid id.
  2. It has no imports, no async code and no host globals; the top level holds only functions and constants.
  3. Every input has a label, a default inside its range or options, and a description.
  4. Every returned output is declared, and every series has one value per bar.
  5. The pane fits the values: price-scale values on 'price', anything else on 'oscillator'.
  6. docs.overview, docs.howToRead and docs.settings are written.
  7. live is declared (a lookback covering every helper's need, or 'none'); values carried from bar to bar go through ta.scan, ta.cum or a recursive helper; scan steps read item; the ctx.ta calls are the same on every run; day and week levels use fromTime; a mode that reads the whole history is in barCloseWhen.
13
Design rules

What the checker enforces, and why.

  • No network, no clock, no randomness. An indicator sees bars and inputs and nothing else, so results are reproducible and your account data stays private.
  • Literal manifest. Spectral reads the manifest without running your code, so the settings form, the toolbox entry and the documentation exist before the first evaluation.
  • Bounded work. One synchronous pass per evaluation that grows linearly with the bars: at most 250 ms on 30,000 bars with every input at its max. Spectral evaluates indicators in a worker so a slow or broken file never freezes the chart.
  • Exact, fast live updates. A tick reruns only a short window, never the whole history, and the result must equal a full recalculation. Spectral proves both when you add the file, so live updates stay fast however much history the chart has loaded.
  • Plain text only. Names and labels must not look like identifiers, account numbers or hashes; this keeps indicator boxes shareable.
  • Declared outputs only. Returning an undeclared key, a series of the wrong length or a marker outside the bars is a runtime error, reported on the chart with a fix.
14
Error codes

Every check, with its fix.

The report in Spectral names these codes with a line and column where it applies. Copy report gives you the plain-text version; Copy fix prompt wraps it for an LLM.

File and module structure

CodeMeaningFix
E-FILE-NOT-REGULARNot a regular filePick a plain .js file on disk.
E-FILE-EXTENSIONUnsupported file extensionSave the indicator as a .js or .mjs file.
E-FILE-TOO-LARGEFile too largeKeep the file under 256 KiB; remove data tables or generated code.
E-FILE-EMPTYFile is emptyThe file must contain a default export.
E-FILE-ENCODINGFile is not UTF-8Save the file as UTF-8 text.
E-SOURCE-BIDIHidden control charactersRemove NUL and bidirectional control characters from the source.
E-SOURCE-MISSINGSource file missingThe original file was moved or deleted; re-import it from its new location.
E-SYNTAXSyntax errorFix the JavaScript syntax error at the reported position.
E-AST-TOO-COMPLEXSource too complexReduce nesting depth and total size of the file.
E-IDENT-NON-ASCIINon-ASCII identifierUse ASCII letters, digits and underscores in identifiers.
E-IMPORTImports are not allowedRemove the import and inline the helper into the file.
E-IMPORT-DYNAMICDynamic import is not allowedRemove the import() call.
E-IMPORT-METAimport.meta is not allowedRemove the import.meta reference.
E-EXPORT-NAMEDOnly a default export is allowedRemove named exports and re-exports; keep a single export default.
E-EXPORT-DEFAULT-MISSINGExactly one default export is requiredAdd `export default { ... }` with the manifest and calculate.
E-EXPORT-DEFAULT-SHAPEDefault export must be an object literalExport a plain object literal directly: `export default { schemaVersion: 3, ... }`.
E-TOP-LEVEL-STATEMENTUnsupported top-level statementKeep only function declarations, const helpers and the default export at top level.
E-ASYNCAsync code is not allowedRemove async/await, generators, Promise, .then/.catch/.finally, thenables and FinalizationRegistry; calculate must be synchronous and nothing may run after it returns.
E-DEBUGGERdebugger is not allowedRemove the debugger statement.
E-THIS-TOPTop-level this is not allowedDo not reference `this` outside functions.
E-CODEGENCode generation is not allowedRemove eval and Function constructor usage.
E-FORBIDDEN-GLOBALForbidden globalIndicator 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-IDENTIFIERUndefined nameDeclare 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-ACCESSPrototype access is not allowedRemove constructor/prototype/__proto__ member access.
E-BUILTIN-WRITEWrites to a built-in are not allowedDo 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-UNKNOWNUnknown manifest keyRemove the key or check its spelling against the manifest reference.
E-MANIFEST-NOT-LITERALManifest value must be a literalWrite manifest values as plain literals (strings, numbers, booleans, arrays, objects); no expressions or functions.
E-CALCULATE-MISSINGcalculate is missingAdd a synchronous `calculate(ctx) { ... }` method to the default export.
E-CALCULATE-SHAPEcalculate has the wrong shapecalculate must be a synchronous function taking one parameter (ctx).
E-MANIFEST-KEY-MISSINGRequired manifest key missingAdd the missing key.
E-FORMAT-UNSUPPORTEDctx.format needs schemaVersion 3Set `schemaVersion: 3` to write numbers with ctx.format, or build the text without it.

Manifest rules

CodeMeaningFix
E-SCHEMA-VERSION-INVALIDInvalid schemaVersionSet `schemaVersion: 3`.
E-SCHEMA-VERSION-UNSUPPORTEDschemaVersion needs a newer SpectralUpdate Spectral, or ask for a schemaVersion 3 file.
E-ID-INVALIDInvalid idUse 3-48 lowercase letters, digits and single hyphens, starting with a letter.
E-ID-EXISTSAn indicator with this id already existsChange the id, or replace the existing indicator.
E-TEXT-INVALIDInvalid text fieldProvide a non-empty string within the length limit.
E-TEXT-UNSAFEText looks like an identifier or hashAvoid long hexadecimal or alphanumeric runs and account-like tokens in text fields.
E-PANE-INVALIDInvalid paneSet pane to 'price' or 'oscillator'.
E-LIVE-INVALIDInvalid live modeSet live to { lookback: <bars calculate reads before the forming bar> } or 'none', or omit it.
E-LIVE-LOOKBACKInvalid live lookbackWrite 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-NONDETERMINISTICNon-deterministic code in a live indicatorRemove 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-CLOSEInvalid bar-close conditionSet 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-INVALIDInvalid input keyInput keys are camelCase, start with a lowercase letter and are at most 21 characters.
E-INPUT-TYPE-INVALIDInvalid input typeUse one of 'integer', 'number', 'boolean', 'select', 'source', 'text', 'time'.
E-INPUT-DEFAULT-INVALIDInvalid input defaultProvide a default that matches the input type and lies inside its range or options.
E-INPUT-RANGE-INVALIDInvalid input rangemin must be <= max, step must be positive, and integer inputs need integer bounds.
E-INPUT-OPTIONS-INVALIDInvalid select optionsProvide 1-16 unique non-empty option strings.
E-INPUT-LIMITToo many inputsDeclare at most 24 inputs.
E-PLOT-KEY-INVALIDInvalid output keyOutput keys are camelCase, start with a lowercase letter and are at most 14 characters.
E-PLOT-PRIMARYPrimary plot ambiguityMark exactly one plot as primary (or none; the first plot is primary).
E-OUTPUT-LIMITToo many outputsReduce the number of plots, levels, zones, markers, columns, profiles or (schema v3) tables, labels, barColors, bgColors, segments or boxes.
E-OUTPUT-EMPTYIndicator produces nothingDeclare at least one plot, level, zone, marker, column or profile (schema v3: or a table, labels, barColors, bgColors, segments or boxes).
E-OUTPUT-PANE-MISMATCHOutput not allowed on this paneColumns are only available on the 'oscillator' pane, profiles, barColors, inline level labels and aboveBar/belowBar markers only on the 'price' pane.
E-COLOR-INVALIDInvalid colorUse a 6-digit hex color like #8AA9C3.
E-STYLE-INVALIDInvalid style valueCheck 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-COLLISIONKey collisionRename the input so it does not collide with a generated style setting (e.g. <plot>Color).
E-PRESET-INVALIDInvalid presetEach preset needs id, name, shortName and inputs that match declared inputs.
E-PRESET-LIMITToo many presetsDeclare at most 8 presets.
E-DOCS-INVALIDInvalid docsdocs.overview is required; each docs field is a string up to 2000 characters.
E-PROFILE-UNSUPPORTEDProfiles need schemaVersion 2Set `schemaVersion: 2` to draw volume profiles, or remove the profiles field.
E-AUX-UNSUPPORTEDAuxiliary bars need schemaVersion 2Set `schemaVersion: 2` to read auxiliary bars, or remove the auxiliary field.
E-AUX-INVALIDInvalid auxiliary sourceGive each auxiliary source a barSize and a duration, and only the documented fields: useRth, whatToShow, keepUpToDate, when.
E-AUX-KEY-INVALIDInvalid auxiliary keyAuxiliary keys are camelCase, start with a lowercase letter and are at most 14 characters.
E-AUX-LIMITToo many auxiliary sourcesDeclare at most 4 auxiliary sources.
E-AUX-BAR-SIZEUnsupported auxiliary bar sizeUse a Spectral bar size of 1 min or longer, e.g. '1 day' or '1 week'.
E-AUX-DURATIONInvalid auxiliary durationWrite 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-UNSUPPORTEDDrawing elements need schemaVersion 3Set `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-INVALIDInvalid paletteDeclare at most 8 palettes, each { label, colors } with 1-8 6-digit hex colors like #4CAF7A, keyed like an output.
E-PALETTE-REFUnknown paletteSet palette to the key of a palette declared under palettes (barColors and bgColors need one).
E-TABLE-INVALIDInvalid tableGive 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-INVALIDInvalid labelCheck style ('none', 'box', 'pin', 'arrow'), placement ('above', 'below', 'left', 'right', 'center'), hideBelowBarWidth (0-40) and maxVisible (1-2000).
E-SHAPE-INVALIDInvalid marker shapeCheck shape, size ('tiny', 'small', 'normal', 'large'), placement ('absolute', 'aboveBar', 'belowBar') and hideBelowBarWidth (0-40); shape: 'char' needs char, one visible character.
E-SEGMENT-INVALIDInvalid segmentSet extend to 'none', 'right', 'left' or 'both'.
E-BOX-INVALIDInvalid boxSet extend to 'none' or 'right' and hideBelowBarWidth from 0 to 40.
E-TEXT-SIZE-INVALIDInvalid text size or fontSet textSize to 'small', 'normal' or 'large' and font to 'mono' or 'sans'.
E-AUX-WHENInvalid auxiliary conditionList 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 (do not block installation)

CodeMeaningFix
W-NONDETERMINISTICNon-deterministic codeAvoid 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-HELDUpdates at bar close while a kept-up-to-date series formscalculate 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-MARKERA marker moves with the newest barcalculate 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-CONSOLEconsole usageRemove console calls; they are not visible to the user.
W-VOLUME-UNDECLAREDVolume used without usesVolumeSet `usesVolume: true` when calculate reads bar.volume.
W-DOCS-MISSINGNo docsAdd docs (overview, howToRead, settings) so the info page can explain the indicator.
W-DOCS-INCOMPLETEInfo page incompleteAdd docs.howToRead, docs.settings and a description for every input; they fill the indicator info page.

Runtime (shown on the chart after installation)

CodeMeaningFix
R-LOAD-FAILEDModule failed to loadReload the indicator; if it persists, re-import the file.
R-EXPORT-MISMATCHModule does not match its manifestRe-import the file; the stored copy and the manifest disagree.
R-THROWcalculate threw an errorFix the error in calculate, then Reload.
R-OUTPUT-INVALIDcalculate returned an invalid resultReturn only declared keys with numeric arrays or nulls.
R-OUTPUT-LENGTHSeries length mismatchEvery series must have exactly bars.length entries.
R-OUTPUT-TEXTDrawn text too longShorten 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-UNSAFEDrawn text looks like an identifierDrawn 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-SLOWcalculate is too slowKeep 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-INEXACTLive update differs from a full recalculationRaise 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-STATEta.scan keeps too much stateKeep 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-SLOWLive update is too slowLower 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-STATEctx.ta calls differ between runsCall 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-TIMEOUTIndicator timed outThe indicator was disabled for this session; fix the infinite loop and Reload.
R-NOT-INSTALLEDCustom indicator not installedRe-import it from the toolbox or remove it from the chart.
R-INCOMPATIBLEIndicator incompatible with this Spectral versionUpdate Spectral or re-generate the file against the current docs.
15
Downloads

Reference files and examples.