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.
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.
Add an indicator file.
- Open a chart, click Indicators, and find the Custom indicators section at the top of the toolbox.
- Click Add file… and pick a
.jsfile. 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. - A passing file appears in the custom section and in the indicator list, marked Custom. Click Add to put it on the chart.
- 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.
- 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.
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.
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
calculateis code. - Top level holds only function declarations,
consthelpers 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 asfetch,window,globalThis, timers,cryptoorperformance. - Allowed:
ctx,Math,Number,Array,Object,Map,Set,JSON, string and array methods, and your own helper functions.
Fields and limits.
| Field | Required | Rule |
|---|---|---|
schemaVersion | yes | 3 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. |
id | yes | 3-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, version | yes | Up to 80 / 20 / 48 / 240 / 20 characters. Plain text: no long letter-digit runs, account-like tokens or hashes. |
pane | yes | 'price' draws on the candles; 'oscillator' opens its own pane below. |
live | no | { 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. |
usesVolume | no | true exposes bar.volume and enables ta.sessionVwap. |
inputs | no | Up to 24 user settings; see Inputs. |
plots, levels, zones, markers, columns, profiles | at least one | What the chart draws; see Outputs. |
palettes, tables, labels, barColors, bgColors, segments, boxes | no | Schema v3 drawing elements and the named colors they pick from; see Drawing elements. |
presets | no | Up to 8 { id, name, shortName, inputs } variants; each appears as its own toolbox entry. |
auxiliary | no | Schema 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. |
docs | no (recommended) | overview (required), howToRead, settings, notes; up to 2,000 characters each. They become the indicator's info page; see The info page. |
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.
| type | Extra fields | Value in ctx.inputs |
|---|---|---|
integer | min, max, step (integer bounds) | Rounded, clamped number |
number | min, max, step | Clamped number |
boolean | — | Boolean (a switch) |
select | options: 1-16 unique strings | One 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. |
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.
| Family | Max | Manifest entry | calculate returns |
|---|---|---|---|
plots | 16 | { 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). |
levels | 16 | { 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. |
zones | 8 | { label, color, opacity?, offset? } (opacity 0-0.8) | { upper, lower }, two series; the band between them is filled. offset shifts it like a plot. |
markers | 8 | { label, color, radius? } (radius 2-8) | Array of { index, value }: a dot at bar index and price value. |
columns | 8 | { 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. |
profiles | 4 | { 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.lengthentries, in bar order. Usenullwhere a value is not defined yet; non-finite numbers count asnull. lineWidthis 0.5-8;lineStyleis'solid','dashed'or'dotted'.offsetmoves the drawing, not the data: compute the series on the bars as usual and setoffset: 26to draw valueiat bari + 26(Ichimoku's leading spans) oroffset: -26to 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, andcalculatesees its default.- A profile row is
{ low, high, volume, up? }, whereupis the share traded on up bars (drawn inupColor). A'visible'profile returns{ priceLow, rowHeight, rows, valueArea?, bars }:bars[i]isnullor{ row, volume, up? }with that bar's volume in grid rowsrow,row + 1, and so on;rowsis how many rows to draw andvalueAreathe value-area percentage. Keep all its volumes under 64,000 numbers by choosingrowHeight. 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.
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.
| Field | Max | Manifest entry | calculate returns |
|---|---|---|---|
palettes | 8 | { 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>. |
tables | 4 | { 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. |
labels | 8 | { 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'. |
barColors | 2 | { label, palette } | One palette index or null per bar: recolors that candle. Price pane only; the first declared one with a value wins. |
bgColors | 2 | { label, palette, opacity? } (opacity 0-0.6) | One palette index or null per bar: shades the pane background behind that bar. |
segments | 8 | { 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. |
boxes | 8 | { 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 returnresult.colors.<plotKey>: one palette index (ornullfor its own color) per bar, for example green while rising and red while falling. - Plot styles.
styleis'line'(default),'step','circles','cross','area'or'histogram'. - Marker shapes.
shapeis'circle','square','diamond','triangleUp','triangleDown','arrowUp','arrowDown','cross','x','flag'or'char'(one character inchar);sizeis'tiny'to'large';placementis'absolute'(default, atvalue),'aboveBar'or'belowBar'(just above the high or below the low, sovaluemay be left out; price pane only); a marker item'spaletteindex picks its color and itstooltipis shown on hover. - Panes. Tables, labels, segments, boxes and
bgColorsdraw on the indicator's pane, price or oscillator.barColors,profiles, inline level labels (labelStyle: 'inline') andaboveBar/belowBarmarkers are price pane only; the file is rejected withE-OUTPUT-PANE-MISMATCHotherwise. - 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,x1andx2are 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 newestmaxVisiblelabels (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 withctx.format(number,price,percent,compact,thousands; schema v3 only) instead ofString(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).
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, withtime(the bar's open) in Unix seconds;volumeonly withusesVolume: true. History can be a handful of bars or tens of thousands: returnnullwhere a lookback is not yet filled instead of throwing.auxiliary: the bars of every series declared inauxiliary, 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,percentRankandscan, which carries state from bar to bar. Each returns an array as long as its input; windowed functions returnnulluntil the window is full, whileemastarts at the first bar without a warm-up.rsiandsessionVwapmatch 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)andweekStart(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 } } };
},| Field | Required | Rule |
|---|---|---|
| name (the key) | yes | camelCase, up to 14 characters; read as ctx.auxiliary.<name>. |
barSize | yes | A Spectral bar size of 1 minute or longer, for example '1 hour', '1 day' or '1 week'. |
duration | yes | History 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. |
useRth | no | Regular trading hours only; default true. |
whatToShow | no | 'TRADES', 'MIDPOINT', 'BID', 'ASK' or 'BID_ASK'; default: the chart's own. |
keepUpToDate | no | Keep 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. |
when | no | { 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.
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.
live | Meaning |
|---|---|
| omitted | The 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
- Carry values from bar to bar only through
ctx.ta. A running total, a trend direction, a trailing stop or a streak goes throughta.scan,ta.cumor a recursive helper (ema,rma,rsi,atr,sma,sessionVwap). A variable you update in a loop overbarsstarts from scratch in the window and gives a different value live. - Declare how far back you read.
lookbackis 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. - Call the
ctx.tahelpers the same way on every run: same order, same lengths, on series as long asctx.bars. Do not skip or add a call depending onbars.lengthor 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. bars.lengthis not the history length, and index 0 is not the first bar of the chart on a live tick. Never testindex === 0ofctx.barsor a series, or count bars, to decide anything except warm-up; use the helpers' own warm-up (null). The exception is theindexata.scanstep receives: it counts from the first bar of the whole history, soindex === 0there is fine.- Anchor period levels by time. A level that starts at a bar of the day or week is
{ price, fromTime: ctx.time.dayStart(bar) }(orweekStart), never{ price, fromIndex }found by searchingctx.bars: the window does not contain that bar. - No
Date, noMath.random, no values kept between runs (a top-level object or array thatcalculatewrites to, such as a cache keyed by bar time, or a value stored on a built-in such asMath), 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, areE-LIVE-NONDETERMINISTICunlesslive: '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 insidecalculate. - 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 declareslive: 'none'.
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 lookback 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. |
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 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 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 bars | ctx.auxiliary and { 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
// 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.
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.
| 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; 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,000 | The 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. |
| Markers | 20,000 dots per key, 4,000 shape markers per key (schema v3), 64,000 in all | R-OUTPUT-INVALID |
State one 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 for any one tick | Updates at bar close for a while (R-LIVE-SLOW), then live again. |
| Drawn at once | 3,000 items per indicator, 12,000 per pane | The newest items in view are drawn; the rest wait. |
| Tables shown per pane | 16 | The indicators added last show none. |
| Draw time | 3 ms per frame on average (8 ms on slow frames) per indicator, 12 ms per pane | Drawn reduced (Throttled), then hidden (Hidden); checked again every 30 s. |
Writing a fast file
- Calculate in one pass. Use the
ctx.tahelpers; 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.
hideBelowBarWidthhides 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.lookbackand 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.scanstate. 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.
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 part | Comes from | What to write |
|---|---|---|
| At a glance | description | One sentence: what the indicator shows. |
| Overview | docs.overview | What it computes and from what; the formula if it is short. |
| How to read it | docs.howToRead | How to interpret the lines, levels, zones, colors and markers, and what it does not tell you. |
| Settings and limitations | docs.settings | What the important inputs change, sensible values, warm-up, bar sizes or sessions it suits. |
| What it draws | generated from the outputs | Nothing; give every plot, level, zone, marker and column a clear label. |
| Notes | docs.notes | Anything else, for example differences from other platforms. |
| Options | each input's label, description, default and range | A description for every input. |
Spectral warns, without blocking the import, when howToRead, settings or an input description is missing (W-DOCS-INCOMPLETE).
What usually goes wrong, and the check before you add a file.
- Importing a library (
E-IMPORT): usectx.taor write the helper as a top-level function. let,varor a call at top level (E-TOP-LEVEL-STATEMENT): keep state insidecalculate.- Expressions in the manifest such as template literals or spreads (
E-MANIFEST-NOT-LITERAL): write plain literals. - Colors like
red,#fffor#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 withnullin the warm-up. - Reading
bar.volumewithoutusesVolume: true(W-VOLUME-UNDECLARED): declare it, or volume is undefined. - Nested loops over all bars (
R-SLOW): use rolling windows or thetahelpers. 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 bycalculate;E-LIVE-NONDETERMINISTIC): create the value insidecalculate, and carry values from bar to bar withta.scan. - A running total, trend or stop in your own variable across a loop over
bars(R-LIVE-INEXACT): carry it inta.scanorta.cum. - A
live.lookbacksmaller than whatcalculatereads (R-LIVE-INEXACT): set it to at least the lookback the report names. ctx.bars[index]inside ata.scanstep (R-LIVE-INEXACT): read the bar fromitem.- A day's level found by searching
ctx.bars(R-LIVE-INEXACT): use{ price, fromTime: ctx.time.dayStart(bar) }. ctx.tacalls that depend onbars.lengthor on the data (R-LIVE-STATE): call them the same way on every run and mask their results instead.DateorMath.randomin a live indicator (E-LIVE-NONDETERMINISTIC): usectx.time, orlive: 'none'.- A daily or weekly value computed from intraday bars: the values are wrong or missing; declare an
auxiliaryseries of that bar size instead.
Before you add a file, check that:
- It is one file with one
export default,schemaVersion: 3and a validid. - It has no imports, no async code and no host globals; the top level holds only functions and constants.
- Every input has a label, a default inside its range or options, and a description.
- Every returned output is declared, and every series has one value per bar.
- The pane fits the values: price-scale values on
'price', anything else on'oscillator'. docs.overview,docs.howToReadanddocs.settingsare written.liveis declared (a lookback covering every helper's need, or'none'); values carried from bar to bar go throughta.scan,ta.cumor a recursive helper; scan steps readitem; thectx.tacalls are the same on every run; day and week levels usefromTime; a mode that reads the whole history is inbarCloseWhen.
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.
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
| Code | Meaning | Fix |
|---|---|---|
E-FILE-NOT-REGULAR | Not a regular file | Pick a plain .js file on disk. |
E-FILE-EXTENSION | Unsupported file extension | Save the indicator as a .js or .mjs file. |
E-FILE-TOO-LARGE | File too large | Keep the file under 256 KiB; remove data tables or generated code. |
E-FILE-EMPTY | File is empty | The file must contain a default export. |
E-FILE-ENCODING | File is not UTF-8 | Save the file as UTF-8 text. |
E-SOURCE-BIDI | Hidden control characters | Remove NUL and bidirectional control characters from the source. |
E-SOURCE-MISSING | Source file missing | The original file was moved or deleted; re-import it from its new location. |
E-SYNTAX | Syntax error | Fix the JavaScript syntax error at the reported position. |
E-AST-TOO-COMPLEX | Source too complex | Reduce nesting depth and total size of the file. |
E-IDENT-NON-ASCII | Non-ASCII identifier | Use ASCII letters, digits and underscores in identifiers. |
E-IMPORT | Imports are not allowed | Remove the import and inline the helper into the file. |
E-IMPORT-DYNAMIC | Dynamic import is not allowed | Remove the import() call. |
E-IMPORT-META | import.meta is not allowed | Remove the import.meta reference. |
E-EXPORT-NAMED | Only a default export is allowed | Remove named exports and re-exports; keep a single export default. |
E-EXPORT-DEFAULT-MISSING | Exactly one default export is required | Add `export default { ... }` with the manifest and calculate. |
E-EXPORT-DEFAULT-SHAPE | Default export must be an object literal | Export a plain object literal directly: `export default { schemaVersion: 3, ... }`. |
E-TOP-LEVEL-STATEMENT | Unsupported top-level statement | Keep only function declarations, const helpers and the default export at top level. |
E-ASYNC | 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 | debugger is not allowed | Remove the debugger statement. |
E-THIS-TOP | Top-level this is not allowed | Do not reference `this` outside functions. |
E-CODEGEN | Code generation is not allowed | Remove eval and Function constructor usage. |
E-FORBIDDEN-GLOBAL | 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 | 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 | Prototype access is not allowed | Remove constructor/prototype/__proto__ member access. |
E-BUILTIN-WRITE | 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 | Unknown manifest key | Remove the key or check its spelling against the manifest reference. |
E-MANIFEST-NOT-LITERAL | Manifest value must be a literal | Write manifest values as plain literals (strings, numbers, booleans, arrays, objects); no expressions or functions. |
E-CALCULATE-MISSING | calculate is missing | Add a synchronous `calculate(ctx) { ... }` method to the default export. |
E-CALCULATE-SHAPE | calculate has the wrong shape | calculate must be a synchronous function taking one parameter (ctx). |
E-MANIFEST-KEY-MISSING | Required manifest key missing | Add the missing key. |
E-FORMAT-UNSUPPORTED | 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 | Invalid schemaVersion | Set `schemaVersion: 3`. |
E-SCHEMA-VERSION-UNSUPPORTED | schemaVersion needs a newer Spectral | Update Spectral, or ask for a schemaVersion 3 file. |
E-ID-INVALID | Invalid id | Use 3-48 lowercase letters, digits and single hyphens, starting with a letter. |
E-ID-EXISTS | An indicator with this id already exists | Change the id, or replace the existing indicator. |
E-TEXT-INVALID | Invalid text field | Provide a non-empty string within the length limit. |
E-TEXT-UNSAFE | Text looks like an identifier or hash | Avoid long hexadecimal or alphanumeric runs and account-like tokens in text fields. |
E-PANE-INVALID | Invalid pane | Set pane to 'price' or 'oscillator'. |
E-LIVE-INVALID | Invalid live mode | Set live to { lookback: <bars calculate reads before the forming bar> } or 'none', or omit it. |
E-LIVE-LOOKBACK | 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 | 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 | 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 | Invalid input key | Input keys are camelCase, start with a lowercase letter and are at most 21 characters. |
E-INPUT-TYPE-INVALID | Invalid input type | Use one of 'integer', 'number', 'boolean', 'select', 'source', 'text', 'time'. |
E-INPUT-DEFAULT-INVALID | Invalid input default | Provide a default that matches the input type and lies inside its range or options. |
E-INPUT-RANGE-INVALID | Invalid input range | min must be <= max, step must be positive, and integer inputs need integer bounds. |
E-INPUT-OPTIONS-INVALID | Invalid select options | Provide 1-16 unique non-empty option strings. |
E-INPUT-LIMIT | Too many inputs | Declare at most 24 inputs. |
E-PLOT-KEY-INVALID | Invalid output key | Output keys are camelCase, start with a lowercase letter and are at most 14 characters. |
E-PLOT-PRIMARY | Primary plot ambiguity | Mark exactly one plot as primary (or none; the first plot is primary). |
E-OUTPUT-LIMIT | 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 | 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 | 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 | Invalid color | Use a 6-digit hex color like #8AA9C3. |
E-STYLE-INVALID | 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 | Key collision | Rename the input so it does not collide with a generated style setting (e.g. <plot>Color). |
E-PRESET-INVALID | Invalid preset | Each preset needs id, name, shortName and inputs that match declared inputs. |
E-PRESET-LIMIT | Too many presets | Declare at most 8 presets. |
E-DOCS-INVALID | Invalid docs | docs.overview is required; each docs field is a string up to 2000 characters. |
E-PROFILE-UNSUPPORTED | Profiles need schemaVersion 2 | Set `schemaVersion: 2` to draw volume profiles, or remove the profiles field. |
E-AUX-UNSUPPORTED | Auxiliary bars need schemaVersion 2 | Set `schemaVersion: 2` to read auxiliary bars, or remove the auxiliary field. |
E-AUX-INVALID | 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 | Invalid auxiliary key | Auxiliary keys are camelCase, start with a lowercase letter and are at most 14 characters. |
E-AUX-LIMIT | Too many auxiliary sources | Declare at most 4 auxiliary sources. |
E-AUX-BAR-SIZE | Unsupported auxiliary bar size | Use a Spectral bar size of 1 min or longer, e.g. '1 day' or '1 week'. |
E-AUX-DURATION | 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 | 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 | 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 | Unknown palette | Set palette to the key of a palette declared under palettes (barColors and bgColors need one). |
E-TABLE-INVALID | 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 | Invalid label | Check style ('none', 'box', 'pin', 'arrow'), placement ('above', 'below', 'left', 'right', 'center'), hideBelowBarWidth (0-40) and maxVisible (1-2000). |
E-SHAPE-INVALID | 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 | Invalid segment | Set extend to 'none', 'right', 'left' or 'both'. |
E-BOX-INVALID | Invalid box | Set extend to 'none' or 'right' and hideBelowBarWidth from 0 to 40. |
E-TEXT-SIZE-INVALID | Invalid text size or font | Set textSize to 'small', 'normal' or 'large' and font to 'mono' or 'sans'. |
E-AUX-WHEN | 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 (do not block installation)
| Code | Meaning | Fix |
|---|---|---|
W-NONDETERMINISTIC | 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 | 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 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 | console usage | Remove console calls; they are not visible to the user. |
W-VOLUME-UNDECLARED | Volume used without usesVolume | Set `usesVolume: true` when calculate reads bar.volume. |
W-DOCS-MISSING | No docs | Add docs (overview, howToRead, settings) so the info page can explain the indicator. |
W-DOCS-INCOMPLETE | Info page incomplete | Add docs.howToRead, docs.settings and a description for every input; they fill the indicator info page. |
Runtime (shown on the chart after installation)
| Code | Meaning | Fix |
|---|---|---|
R-LOAD-FAILED | Module failed to load | Reload the indicator; if it persists, re-import the file. |
R-EXPORT-MISMATCH | Module does not match its manifest | Re-import the file; the stored copy and the manifest disagree. |
R-THROW | calculate threw an error | Fix the error in calculate, then Reload. |
R-OUTPUT-INVALID | calculate returned an invalid result | Return only declared keys with numeric arrays or nulls. |
R-OUTPUT-LENGTH | Series length mismatch | Every series must have exactly bars.length entries. |
R-OUTPUT-TEXT | 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 | 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 | 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 | 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 | 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 | 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 | 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 | Indicator timed out | The indicator was disabled for this session; fix the infinite loop and Reload. |
R-NOT-INSTALLED | Custom indicator not installed | Re-import it from the toolbox or remove it from the chart. |
R-INCOMPATIBLE | Indicator incompatible with this Spectral version | Update Spectral or re-generate the file against the current docs. |
Reference files and examples.
- custom-indicators.llm.mdThe complete reference for code generators. Hand this link to an LLM.
- spectral-indicator.d.tsType declarations; save next to your file for editor checks.
- custom-indicators.schema.jsonJSON Schema of the manifest (2020-12).
- error-codes.jsonEvery check code with its fix, machine-readable.
- LICENSE.txtMIT-0: the example and store indicator files and spectral-indicator.d.ts are free to use, change and share.
- examples/rsi-bands.jsOscillator with bands, levels, a zone, markers and columns. Store page
- examples/ema-ribbon.jsPrice-pane ribbon of three EMAs with a shaded zone. Store page
- examples/inside-bars.jsCompleted-bar markers that update at bar close (live: none). Store page
- examples/regime-table.jsA table of ADX, +DI/-DI and EMA slope with palette-colored verdict cells, written with ctx.format. Store page