# ChartingPark custom indicator reference

Reference revision: 2026-12-03. Describes the current JavaScript indicator API.
This revision identifies the document, not a supported `version` field in scripts.

This is the complete supported **editor script contract**, intended for human authors and AI code generators.
It is not a tutorial. Give an AI this entire Markdown file when asking it to write a ChartingPark indicator.
The TypeScript notation describes the contract; the editor accepts JavaScript only.

## Contents

- [Authoring rules](#authoring-rules)
- [Complete script shape](#complete-script-shape)
- [Root fields](#root-fields)
- [Inputs](#inputs)
- [Plots and colors](#plots-and-colors)
- [Indicator drawings](#indicator-drawings)
- [Candle data](#candle-data)
- [Calculation and output](#calculation-and-output)
- [History and warmup](#history-and-warmup)
- [Execution lifecycle](#execution-lifecycle)
- [Errors](#errors)
- [Executable examples](#executable-examples)
- [Unsupported capabilities](#unsupported-capabilities)
- [Execution privileges and persistence](#execution-privileges-and-persistence)

## Authoring rules

For an AI generating a script:

1. Return a complete JavaScript function body containing `return { ... }`. Do not emit a module, HTML, TypeScript, or Pine Script.
2. Declare `pane`, a `plots` object, and a synchronous `calculate(bars, inputs, context)` function.
3. Declare user settings in `inputs`. Numeric, boolean, and dropdown settings are supported.
4. Return one array per plot, or `{ values, colors }`. Every array must have exactly `bars.length` entries.
5. Use finite numbers for valid observations and `null` for unavailable observations. Never return `undefined`, `NaN`, infinity, or a promise.
6. Keep bars in their supplied order. Do not mutate bars or inputs, filter output positions away, or pad output arrays for display offsets.
7. Calculate from the supplied data on every call. Do not depend on earlier calls or array indexes staying unchanged.
8. For a causal indicator, calculate output `i` using only bars `0` through `i`. The runtime does not enforce causality within the supplied array.
9. Declare `warmupBars(inputs)` when preceding observations are needed. Still handle insufficient history and empty input.
10. Use only the fields and facilities documented here. No `ta`, PineJS, KLineCharts API, canvas context, imports, or data-fetching API is supplied.

## Complete script shape

This type model describes accepted authoring syntax. It is not code to paste into the editor.

```ts
type ThemeToken =
  | 'background' | 'grid' | 'text' | 'up' | 'down' | 'line'
  | 'indicator' | 'drawing' | 'orderEntry' | 'orderStopLoss' | 'orderTakeProfit';

type NumericInput = {
  type: 'number';
  label: string;
  default: number;
  min?: number;
  max?: number;
  integer?: boolean;
};

type Input = NumericInput
  | { type: 'boolean'; label: string; default: boolean }
  | { type: 'select'; label: string; default: string; options: string[] };
type Inputs = Readonly<Record<string, number | string | boolean>>;
type Output = (number | null)[] | { values: (number | null)[]; colors?: (ThemeToken | null)[] };

type Plot = {
  label?: string;
  kind?: 'line' | 'columns' | 'points' | 'markers';
  shape?: 'arrowUp' | 'arrowDown';
  position?: 'above' | 'below' | 'at';
  offset?: number;
  color?: ThemeToken;
  negativeColor?: ThemeToken;
  fillTo?: string;
};

type Bar = {
  readonly time: number;
  readonly open: number;
  readonly high: number;
  readonly low: number;
  readonly close: number;
  readonly status: 'final' | 'provisional';
  readonly volume?: number;
};

type Point = { time: number; value: number };
type Drawing = { color?: ThemeToken; lineWidth?: number } & (
  | { type: 'line'; from: Point; to: Point; extend?: 'none' | 'left' | 'right' | 'both' }
  | { type: 'box'; from: Point; to: Point }
  | { type: 'label'; at: Point; text: string }
);

type IndicatorContext = Readonly<{
  instrument: InstrumentDescriptor;
  resolution: ResolutionDescriptor;
}>;

type ScriptIndicator = {
  pane: 'main' | 'separate';
  inputs?: Record<string, Input>;
  levels?: number[];
  plots: Record<string, Plot>;
  draw?: (bars: readonly Bar[], inputs: Inputs, values: Record<string, Output>, context: IndicatorContext) => readonly Drawing[];
  warmupBars?: (inputs: Inputs) => number;
  calculate: (
    bars: readonly Bar[],
    inputs: Inputs,
    context: IndicatorContext,
  ) => Record<string, Output>;
};
```

The source runs in a strict JavaScript function with no supplied arguments. Normal local functions,
variables, loops, arrays, and JavaScript built-ins such as `Math` are available. Top-level `return`
is required because this source is a function body. `export default`, static `import`, and TypeScript
type annotations are not valid in this format. Do not rely on `this` in callbacks.

The editor's **Name** field supplies the indicator display name. It also assigns a definition ID.
Neither `name` nor `id` is a supported root script field. All root fields are listed below.
Unrecognized root fields are not forwarded into the native definition. Unknown properties are not
uniformly rejected by current validation; absence of an error does not mean a feature is supported.

## Root fields

| Field | Required | Meaning and constraints |
| --- | --- | --- |
| `pane` | Yes | `"main"` draws on the main price pane and its price scale. `"separate"` creates an independent indicator pane and scale. |
| `inputs` | No | Object mapping input keys to numeric, boolean, or select definitions. Omitted means no inputs. Keys must be nonempty after trimming. |
| `plots` | Yes | Object mapping output keys to static plot definitions. Each key must be nonempty after trimming. The key identifies the corresponding output array. May be empty when `draw` is provided. |
| `levels` | No | Array of finite reference values, such as `[30, 70]`. Included in the pane scale and drawn as horizontal guides. |
| `warmupBars` | No | Synchronous function of the current input values. Returns a nonnegative safe integer. Omitted means zero additional lookback demand. |
| `draw` | No | Synchronous `draw(bars, inputs, values, context)` returning the complete annotation array after calculation. |
| `calculate` | Yes | Synchronous function receiving bars and current input values. Returns aligned output arrays. |

All plots in one script use the script's pane. A script cannot assign different plots to different
panes, select a comparison symbol, or request a separate price scale in the main pane.
A plot's configuration is static for the compiled definition; `plots` is an object, not a callback.

## Inputs

### Setting fields

| Field | Required | Meaning |
| --- | --- | --- |
| `type` | Yes | `"number"`, `"boolean"`, or `"select"`. |
| `label` | Yes | Displayed name; a string containing nonblank text. |
| `default` | Yes | Initial value, valid for the chosen type. |
| `min`, `max` | No | Number settings: finite, inclusive bounds. Unbounded when omitted. |
| `integer` | No | Number settings: boolean; defaults to `false`. |
| `options` | For `"select"` | A nonempty array of unique, nonblank strings. |

### Value rules

These rules apply to defaults and current values:

- **Number:** finite numbers only; `"20"` is not converted. When both bounds are supplied, `min <= max`. With `integer: true`, values must pass `Number.isSafeInteger`, and the settings control uses a step of 1. Otherwise, decimals are allowed.
- **Boolean:** `true` or `false` only. Example: `{ type: 'boolean', label: 'Show signals', default: true }`.
- **Select:** must match an option exactly. Example: `{ type: 'select', label: 'Method', default: 'SMA', options: ['SMA', 'EMA'] }`.

Undeclared settings are rejected. Free-text and color input types are not supported.

### Reading settings

Inside `calculate()`, `inputs.period` is the current value, not the setting definition or a `.value` object. Changing `label` does not change `period` in code. Names that are not valid JavaScript identifiers need bracket access.

For a price-source dropdown, offer `open`, `high`, `low`, and `close`, then read `bar[inputs.source]`. No extra data request is needed.

## Plots and colors

### Plot fields

All fields below are optional.

| Field | Default | Meaning |
| --- | --- | --- |
| `label` | Plot name | Displayed name; does not rename the plot in code. |
| `kind` | `"line"` | `"line"`, `"columns"`, `"points"`, or `"markers"`. |
| `shape` | `"arrowUp"` | Markers: `"arrowUp"` or `"arrowDown"`. |
| `position` | `"at"` | Markers: `"above"`, `"below"`, or `"at"` the returned value. |
| `offset` | `0` | Safe integer from `-10000` to `10000`; shifts the plot by candles. |
| `color` | Chart's indicator color | A theme color name listed below. |
| `negativeColor` | Same as `color` | Color for negative columns/points and the lower side of a fill. |
| `fillTo` | No fill | Another plot's name. Fills between the plots, including their offsets. |

### Colors

Accepted theme color names:

```text
background, grid, text, up, down, line, indicator, drawing,
orderEntry, orderStopLoss, orderTakeProfit
```

The application chooses their actual colors. Raw CSS values such as `"red"` or `"#ff0000"` are not accepted in scripts. Colors chosen in the indicator’s settings take precedence over script colors, including `negativeColor` and colors per candle.

### Gaps, fills, and offsets

- **Lines:** connect adjacent values; `null` leaves a gap. `negativeColor` does not recolor negative line segments.
- **Columns:** extend from zero to each value; zero is included in the scale. Negative columns and points use `negativeColor` when supplied.
- **Fills:** need adjacent values from both plots; missing endpoints leave gaps. Above the target, the fill uses the source plot's color; below it, `negativeColor` when supplied. Crossings can split the color.
- **Offsets:** positive moves right; negative moves left. Value `i` appears at position `i + offset`. Return one entry per source candle as usual. Offsets do not request future data.

Line width, point size, column geometry, fill opacity, and axis format are controlled by the chart. Visible values affect automatic scaling; manual scales can clip plots.

### Colors per candle

- Return `{ values, colors }`, with one color entry per candle.
- Use a theme color name, or `null` for the normal color, including `negativeColor` where applicable.
- For lines and fills, a candle's color applies to the segment ending there. Missing values leave gaps.
- For fills, `null` keeps the normal above/below coloring.

### Markers

- Return a value for an arrow, or `null` for none.
- To mark candles, return their highs or lows and set `position` to `"above"` or `"below"`.
- `"above"` and `"below"` add a fixed gap; `"at"` centers the arrow on its value.
- Offsets apply. Values affect automatic scaling, and arrows stay clipped to the pane.

### Style settings

The **Style** tab provides a color picker for each plot, named by its `label` or plot name. Drawing-only indicators have no plot color controls.

- **Use default colors** restores the plot's theme and per-candle colors.
- Color changes do not rerun calculations and are saved in chart snapshots.
- Replacing a script with different setting definitions or plot names closes the settings panel and discards pending edits.

## Indicator drawings

### Arguments and result

`draw(bars, inputs, values, context)` runs after each successful calculation. `values` contains the results from `calculate()`.

Return an array, or `[]` for none. Drawing-only scripts use `plots: {}` and return `{}` from `calculate()`.

### Drawing types

Set `type` to one of these values:

| Value | Meaning |
| --- | --- |
| `"line"` | `from` and `to`. Optional `extend`: `"none"` (default), `"left"`, `"right"`, or `"both"`. Left/right mean earlier/later time, regardless of anchor order. |
| `"box"` | Opposite corners in `from` and `to`. Fill opacity follows the chart theme. |
| `"label"` | Position in `at`; plain `text`, up to 500 characters. Single-line text appears above the position. Offscreen positions hide labels. HTML is not interpreted. |

### Coordinates and style

Positions use `{ time, value }`:

- `time`: a safe integer UTC timestamp in milliseconds. Prefer candle timestamps.
- `value`: a finite number in the indicator's scale.

Set optional `color` and `lineWidth` on the drawing, not its position. `color` defaults to `"indicator"` and accepts theme color names. `lineWidth` accepts 1–10 CSS pixels.

Return at most **500 drawings per indicator**. More produces `INDICATOR_ERROR`; drawings are not silently truncated.

### Display and updates

- Drawings appear after plots, in returned order, within the indicator's pane. They have no crosshair value readouts.
- Visible portions, including extended lines, affect automatic scaling. Manual scales take precedence and can clip drawings.
- Each calculation replaces the previous drawings. Replay provides only revealed candles; panning does not recalculate.
- Hiding an indicator hides its drawings but keeps its pane. Removing it removes its drawings. Calculation errors clear that indicator's plots and drawings; other indicators continue.
- Script drawings cannot be selected, dragged, or undone with manual drawing tools. Save the script and settings; the drawings regenerate rather than being saved in drawing snapshots.

## Candle data

`bars` contains loaded candles, oldest first, with unique timestamps. It includes offscreen candles, but not necessarily all history available from the provider.

| Field | Type | Meaning |
| --- | --- | --- |
| `time` | Number | Bar opening time as UTC epoch **milliseconds**, not seconds. Safe integer in the supported JavaScript date range. |
| `open` | Finite number | Opening price. |
| `high` | Finite number | Highest price; at least `open` and `close`. |
| `low` | Finite number | Lowest price; at most `open` and `close`. |
| `close` | Finite number | Closing price or current evolving close. |
| `status` | String | `"final"` or `"provisional"`, as admitted from the data source. |
| `volume` | Optional finite number | Nonnegative volume when supplied. Missing volume is not zero; units depend on the provider/instrument. |

### Reading candles

- Candles are read-only source data, even when the chart displays a transformed bar type.
- Timestamps stay in UTC regardless of the displayed timezone.
- Missing market intervals are not padded. Twenty array entries means twenty candles, not twenty minutes or days.
- Missing volume is not zero. Use `null` when your calculation needs volume that is unavailable.
- Earlier history can shift array positions. Live updates can change the last candle without changing array length; do not cache by length alone.
- Candles have no `closeTime`, `endTime`, symbol, interval, timezone, session object, or chart controller. Instrument and interval information comes from `context`.

### Instrument and interval metadata

The third argument of `calculate(bars, inputs, context)` contains the current instrument and
interval. `draw(bars, inputs, values, context)` receives the same context as its fourth argument.
Existing scripts can omit unused arguments.

| Field | Meaning |
| --- | --- |
| `context.instrument.key` | Instrument identifier supplied by the host. |
| `context.instrument.symbol`, `name` | Display symbol and name, normalized by the chart. |
| `context.instrument.pricePrecision` | Number of decimal places for prices, from 0 to 15. |
| `context.instrument.tickSize` | Optional positive minimum price increment. Missing means unknown. |
| `context.instrument.category`, `exchange`, `logoUrl` | Optional host-supplied classification and display metadata. Category is "forex", "crypto", "stocks", "commodities", or "indices". |
| `context.instrument.session` | Optional normalized trading schedule; see the schedule fields below. |
| `context.resolution.key` | Host interval identifier, such as `"5m"`. |
| `context.resolution.kind` | `"fixed"` or `"calendar"`. |
| `context.resolution.unit` | Fixed: `"second"`, `"minute"`, `"hour"`. Calendar: `"day"`, `"week"`, `"month"`. |
| `context.resolution.multiplier` | Positive integer count of units, such as 5 for five minutes. |

Context is read-only and belongs to the current chart. Changing instrument or interval recalculates with the new metadata. During replay, it describes the revealed candles.

### Trading schedule

When present, `session` contains an IANA `timezone` and a `weekly` array. Each entry has
ISO weekday `days` (Monday = 1, Sunday = 7) and `periods`. Each period has `open` and
`close` HH:mm wall-clock strings, optional `openDayOffset` (-1 or 0), and optional
`closeDayOffset` (0 or 1). Optional `exceptions` maps YYYY-MM-DD trading dates to replacement
period arrays; an empty array closes that date. These fields describe the schedule, not an
automatic session-calculation helper.

Precision is not tick size: a price with two decimals may move in increments of 0.25.
Check whether `tickSize` exists before using it. Never infer it from `pricePrecision`.

Context does not expose chart commands, viewport state, or extra data requests.


## Calculation and output

### Arguments

| Argument | Meaning |
| --- | --- |
| `bars` | Available candles, oldest first, including loaded candles outside the visible chart. |
| `inputs` | Current values of your settings. |
| `context` | Instrument and interval metadata. |

### Returned values

- Return exactly the names declared in `plots`.
- For each plot, return a regular array, or `{ values, colors }` for colors per candle.
- Each array must have exactly `bars.length` entries. Values must be finite numbers or `null`.
- Do not return promises, typed arrays, single numbers, or arrays with empty positions.

### Missing values and errors

- Use `null` where a value cannot be calculated. Never remove those entries with `filter()`.
- With no candles, return an empty array for each plot.
- Handle missing data and division by zero. Invalid results hide that indicator’s output.

### Replay

Use only candles through position `i` when calculating the value at `i`. Replay hides unrevealed candles, but your array may still contain later candles relative to an earlier result.

A display offset does not prevent future-data use. Unfinished candles and newly loaded history may change earlier results, especially for cumulative calculations.

## History and warmup

### Return value

- Return a nonnegative safe integer from the current `inputs`. No candles are passed to this function.
- Return the same count for the same settings, without changing outside state.
- ChartingPark calls it when preparing settings, not once per candle.

### Loading limits

ChartingPark uses the largest request among visible indicators, not their sum. Ordinary automatic loading has these limits per request budget:

| Limit | Maximum |
| --- | --- |
| Earlier candles | 100,000 |
| History pages | 8 |
| Consecutive empty pages | 2 |

A larger return value does not increase these limits. Missing history or provider errors may stop loading sooner.

### If history is unavailable

Return `null` until enough candles arrive. Do not fetch history inside `calculate()` or invent missing candles. Replay keeps its own loading policy and never reveals future candles through warmup.

## Execution lifecycle

### When code runs

| Action | Behavior |
| --- | --- |
| Open or type a draft | Does not run the script. |
| Add or apply a script | Runs the script body, checks settings, then calculates for the chart. |
| Receive new or changed candles, including earlier history | Recalculates with all available candles. |
| Change input settings | Recalculates and requests earlier history if needed. |
| Change instrument or interval | Keeps settings and recalculates for the new data. |
| Pan, zoom, or move the crosshair | Reuses existing results when data and settings are unchanged. |
| Change colors | Keeps calculated values. |
| Hide an indicator | Stops its calculations and excludes it from automatic scaling. Showing it recalculates if data changed. |
| Remove an indicator | Removes its output and separate panel. Its editor draft can remain. |

### Applying code changes

- Keeps visibility and compatible input settings. Changing a default does not replace a still-valid setting.
- Matches inputs by name and value type. If retained values are invalid, **all inputs reset to the new defaults**.
- Keeps color overrides for plot names that still exist.
- Changing `pane` moves the indicator. Removing its old panel can also remove manual drawings on that panel.

### Between calculations

Calculate from the supplied data each time. Do not accumulate values in variables outside `calculate()`; they may be shared by multiple instances.

There is no per-candle `init`/`main` protocol, asynchronous completion callback, incremental-update argument, or cleanup hook. Drafts last until their workspace or standalone chart closes.

## Errors

### What failed?

| Problem | What happens |
| --- | --- |
| Invalid JavaScript or script fields | The editor reports the error; the new script is not added. |
| Invalid settings or warmup count | The change is rejected; existing settings stay in place. |
| Calculation throws or returns invalid values | That indicator’s output disappears. Other indicators continue. |

Valid JavaScript syntax does not guarantee a valid calculation. Fix the reported problem and apply the script again.

### Debugging

- Check output names, array lengths, missing values, and division by zero.
- Open the editor's **Log** tab to see `console.log()`, `console.info()`, `console.warn()`,
  `console.error()`, and `console.debug()` messages from this script.
- For example, `console.log("Loaded candles:", bars.length)` prints the supplied candle count.
- Thrown source/calculation/drawing/warmup errors appear in the log. Script line numbers appear
  when the browser provides a recognizable stack location. Output-validation errors remain visible
  as the current indicator error.
- **Last calculation** shows the duration of the latest `calculate()` call in milliseconds,
  including logging overhead. It excludes drawing, output validation, and canvas painting.
  Cached repaints do not update this timing or add messages.
- **Clear log** removes messages, not the current error or last timing. Retention is limited to
  200 messages, 2,000 characters per message and 20 arguments per call. Objects are copied into
  bounded text; circular or unreadable values may show `[Unprintable value]`.
- Logs belong to the script source ID within its workspace or standalone chart. Multiple instances
  of that script share the log, including across workspace charts. Different script IDs stay separate.
  Logs are session-only, never included in saved scripts or chart snapshots. They are released when
  the script is deleted or its library is disposed.
- Capture uses a script-local `console`. The page's console is unchanged; `window.console` and
  other console methods still use the browser console. Log text is plain text, never HTML.
- A replacement script can fail during calculation. ChartingPark does not automatically restore the previous source.
- Moving the chart does not retry an unchanged failed calculation. Change the code, settings, or relevant data.

## Executable examples

Every `js` block in this section is a complete script body. Documentation tests compile and run
these exact blocks. They cover multiple outputs, missing data, short history, and existing renderers.

### Rolling average overlay

For close values `[10, 12, 14, 16, 18]` and period 3, `average` is `[null, null, 12, 14, 16]`.

```js
return {
  pane: "main",
  inputs: {
    period: { type: "number", label: "Period", default: 3, min: 1, max: 10000, integer: true },
  },
  plots: { average: { label: "Moving average", kind: "line", color: "indicator" } },
  warmupBars(inputs) { return inputs.period - 1; },
  calculate(bars, inputs, context) {
    let sum = 0;
    const average = bars.map((bar, index) => {
      sum += bar.close;
      if (index >= inputs.period) sum -= bars[index - inputs.period].close;
      return index >= inputs.period - 1 ? sum / inputs.period : null;
    });
    return { average };
  },
};
```

### Candle movement columns

One independent pane, with signed movement from open to close. A flat candle produces zero.

```js
return {
  pane: "separate",
  plots: { movement: { label: "Close minus open", kind: "columns", color: "up", negativeColor: "down" } },
  calculate(bars) {
    return { movement: bars.map(bar => bar.close - bar.open) };
  },
};
```

### High/low fill and shifted close points

The high/low arrays stay aligned with source bars. Only the close points move one position right.

```js
return {
  pane: "main",
  plots: {
    upper: { label: "High", color: "up", fillTo: "lower" },
    lower: { label: "Low", color: "down" },
    shiftedClose: { label: "Close shifted right", kind: "points", color: "indicator", offset: 1 },
  },
  calculate(bars) {
    return {
      upper: bars.map(bar => bar.high),
      lower: bars.map(bar => bar.low),
      shiftedClose: bars.map(bar => bar.close),
    };
  },
};
```

### Optional volume

Absent volume produces a gap. Explicit zero volume remains zero.

```js
return {
  pane: "separate",
  plots: { volume: { kind: "columns", label: "Volume", color: "indicator" } },
  calculate(bars) {
    return { volume: bars.map(bar => bar.volume ?? null) };
  },
};
```


## Unsupported capabilities

The editor adapter does not provide:

- Pine Script, Tea, TypeScript compilation, `ta` helpers, or a third-party indicator API.
- Arbitrary module imports, dependency resolution, or an injected library bundle.
- Asynchronous calculations, workers, timeouts, cancellation, or per-bar execution callbacks.
- A script API for another instrument/interval, network history loading, or viewport/controller access.
- Custom canvas/DOM rendering, candles as indicator outputs, shapes other than lines/boxes/labels, or editable drawing-tool commands.
- Custom line widths/dashes, plot opacity, or custom scale formatting.
- Multiple panes per script, indicator-to-indicator references, alerts, orders, or strategy backtesting.
- Free-text and color inputs in the editor schema.
- A public script marketplace, database implementation, or version-pinned source snapshots.

These are capability boundaries of this adapter, not security restrictions on JavaScript globals.
Do not infer support from another chart library or from properties that are currently ignored.

## Execution privileges and persistence

### Running scripts

- Scripts run directly on the page, **not in a sandbox**. Only run code you trust.
- Scripts can access browser globals. There are no CPU or memory limits, network restrictions, or a way to interrupt an endless loop.
- Code can cause side effects even if compilation fails. Catching an error does not undo those effects.
- The application’s Content Security Policy must allow dynamic function compilation; ChartingPark does not bypass it.
- Direct DOM access or `fetch()` calls are your own unmanaged behavior, not supported ChartingPark integrations.

### Saving and restoring

- Saving depends on the application. Without storage, scripts last only for the current workspace or standalone chart.
- Charts in a workspace share saved scripts, but keep their own settings and results. Applying edits replaces the first matching instance on the active chart only.
- Chart snapshots store definition IDs and settings—not source code or calculated values. Reopening them requires saved sources or definitions supplied by the application.
- Restore uses the latest saved source, not unfinished edits or a version pinned to the snapshot. Updating a saved script can change older snapshots.
- Loading the script library does not run code. A saved script compiles when applied or required for restoration.
