Skip to content

ChartingPark / CUSTOM INDICATORS

Turn your trading idea into an indicator.

Build custom indicators, plot your calculations, and see your ideas on the chart. Start with a working example or write one with AI.

How custom indicators work

  1. Define your indicator.

    Use ChartingPark’s script format to choose where the indicator appears, its settings, and what to draw.

  2. Calculate the values.

    Write your calculation inside calculate(). It receives the candles and returns the values to draw.

  3. ChartingPark draws your indicator.

    The results appear on the price chart or in a separate panel below it.

moving-average.js
Read-only preview
const period = 20;

return {
  pane: "main",
  plots: { average: { kind: "line" } },
  calculate(bars) {
    const average = bars.map((bar, index) => {
      if (index < period - 1) return null;
      const window = bars.slice(index - period + 1, index + 1);
      return window.reduce((sum, bar) => sum + bar.close, 0) / period;
    });
    return { average };
  },
};

Your first indicator ​

Create a custom indicator using the example code provided in the editor. This example draws a moving average, so you can see how the process works before writing your own code.

  1. Click Indicators, then Create indicator.
  2. The editor opens with the example code already filled in. Leave it unchanged for now and give your indicator a name.
  3. Click Add to chart.

Close the editor to see your indicator on the chart. The moving-average line comes from the code you just added.

Create with AI ​

Describe the indicator you want in your preferred AI chat. Give it ChartingPark’s documentation so it knows how to write code that works with the chart.

Give AI the documentation

Paste the API reference URL into your AI chat and ask it to read the page. If it cannot open links, download the file and attach it instead.

OpenDownload

Describe your indicator

Tell AI what to calculate, where to draw it, and which settings you want to change. Use the example request below, or replace the idea with your own.

Bring the code into ChartingPark

Open Indicators → Create indicator. Replace the example code with the JavaScript from AI, give it a name, and click Add to chart.

Try this request ​

Create a custom indicator for ChartingPark using this API reference:
https://chartingpark.com/docs/custom-indicators/custom-indicator-reference.md

Read it first. If you cannot open it, stop and ask me to attach the file.

Here is the indicator I want to create:

I want two moving averages on my chart, one with a period of 20 and another with 50. Both should use closing prices, have different colors, and let me change their periods in settings.

Return the complete JavaScript code for ChartingPark’s indicator editor. If anything is unsupported, tell me before writing code.

You should see two lines on the chart. The 20-candle average should respond to price changes faster than the 50-candle average. Check that the result matches your request; AI can make mistakes even when the code runs.

Something went wrong? Send AI the error message and the code you used. If the code runs but looks wrong, explain what you expected to see. Paste the corrected code into the same editor and click Apply changes.

Only run code you trust. Custom indicators run directly in your browser.

Examples ​

Choose an example to make your own. Copy its code, open Indicators → Create indicator, and replace the code in the editor. Give it a name and click Add to chart.

Moving average

Draw an average price line over the candles. Choose a simple average (SMA), which weights each candle equally, or an exponential average (EMA), which gives recent prices more weight.

Change the period and price source in settings. You can also turn on extra smoothing.

moving-average-with-settings.js
return {
  pane: 'main',
  inputs: {
    period: { type: 'number', label: 'Period', default: 20, min: 1, max: 10000, integer: true },
    method: { type: 'select', label: 'Method', default: 'SMA', options: ['SMA', 'EMA'] },
    source: { type: 'select', label: 'Source', default: 'close', options: ['open', 'high', 'low', 'close'] },
    smooth: { type: 'boolean', label: 'Smooth over three bars', default: false },
  },
  plots: { average: { label: 'Average', color: 'indicator' } },
  warmupBars(inputs) { return inputs.period - 1 + (inputs.smooth ? 2 : 0); },
  calculate(bars, inputs) {
    const prices = bars.map(bar => bar[inputs.source]);
    let sum = 0, previous = null;
    const average = prices.map((price, i) => {
      sum += price;
      if (i >= inputs.period) sum -= prices[i - inputs.period];
      if (i < inputs.period - 1) return null;
      previous = inputs.method === 'SMA' || previous === null
        ? sum / inputs.period
        : previous + (price - previous) * 2 / (inputs.period + 1);
      return previous;
    });
    return { average: inputs.smooth ? average.map((value, i) =>
      i < 2 || average[i - 2] === null ? null : (value + average[i - 1] + average[i - 2]) / 3
    ) : average };
  },
};

Convert an indicator ​

Bring an indicator you already use into ChartingPark. Choose its platform below, then use AI to rewrite it as JavaScript. Pine Script and MQL files cannot run directly in ChartingPark.

Get the original code

Copy the full source from the Pine Editor, including its version line. Paste it into your AI chat or attach it as a text file.

You need accessible source code. A screenshot or a link to a protected indicator is not enough.

Give AI the documentation

Paste the API reference URL into your AI chat and ask it to read the page. If it cannot open links, download the file and attach it instead.

OpenDownload

Add it and compare

Open Indicators → Create indicator. Paste the converted JavaScript, name it, and click Add to chart.

Compare candle values with the original using the same instrument, interval, and settings. Check the latest, unfinished candle too.

Ask AI to convert it

Send this request with your source code. The ChartingPark reference URL is already included.

Convert the Pine Script indicator source I provide into JavaScript for ChartingPark.

Read the ChartingPark API reference first:
https://chartingpark.com/docs/custom-indicators/custom-indicator-reference.md
If you cannot open it, stop and ask me to attach the file. If I have not supplied the source code, ask for it before continuing.

Preserve the calculations, settings, and plotted results. Check historical references and unfinished-candle behavior. If something is unsupported or a dependency is missing, explain it and ask me how to proceed. Do not silently remove or approximate features.

Return complete JavaScript for ChartingPark’s indicator editor, explain any differences, and tell me what to compare with the original.
See a conversion example

Both versions draw the closing price minus the opening price in a separate panel.

candle-movement.pine
//@version=6
indicator("Candle movement", overlay = false)
plot(close - open, title = "Movement")
candle-movement.js
return {
  pane: "separate",
  plots: { movement: { kind: "line" } },
  calculate(bars) {
    return {
      movement: bars.map(bar => bar.close - bar.open)
    };
  }
};

Some features need a different approach. Extra symbols or intervals, alerts, and strategy orders are not available through ChartingPark’s indicator API.

Ask AI to explain unsupported parts before changing them. If results differ, send a specific candle’s expected and actual values. Price feeds can differ between platforms.

Only run code you trust.

API reference ​

Everything you can use in your indicator code: supported settings, candle data, calculations, and drawing options.

Script format ​

Your script returns an object that tells ChartingPark where to draw, which settings to show, and how to calculate the indicator.

FieldWhat it doesRequired?
paneChooses the price chart or a separate panel.Yes
inputsAdds settings the user can change.No
plotsDescribes the lines, columns, points, or markers to draw.Yes
calculate()Calculates the values for each candle.Yes
levelsAdds horizontal reference lines.No
warmupBars()Requests earlier candles for the calculation.No
draw()Adds lines, boxes, or text labels.No

This example shows the complete script format. It uses every field in the table: a separate panel, a period setting, a line, a zero level, earlier candles, and a label on the latest value.

script.js
Read-only preview
return {
  pane: "separate",
  inputs: {
    period: {
      type: "number", label: "Period",
      default: 5, min: 1, integer: true
    }
  },
  plots: { change: { kind: "line" } },
  calculate(bars, inputs) {
    const change = bars.map((bar, i) =>
      i < inputs.period ? null
        : bar.close - bars[i - inputs.period].close
    );
    return { change };
  },
  levels: [0],
  warmupBars(inputs) { return inputs.period; },
  draw(bars, inputs, values) {
    const last = bars.at(-1);
    const value = values.change.at(-1);
    if (!last || value == null) return [];
    return [{
      type: "label",
      at: { time: last.time, value },
      text: "Latest change"
    }];
  }
};

pane ​

Choose where the indicator appears. Everything your script draws appears in that area.

Example ​

pane.js
Read-only preview
pane: "separate"

Options ​

Required. There is no default.

ValueMeaning
"main"On the price chart.
"separate"In a panel below the price chart.

inputs ​

Add settings people can change without editing the code.

Example ​

inputs.js
Read-only preview
inputs: {
  period: {
    type: "number",
    label: "Period",
    default: 20,
    min: 1,
    integer: true
  }
}

Options ​

Optional. Each setting needs a type, label, and default.

In the example, period is the setting’s name in code. label is the name shown in the settings window. Read its current value with inputs.period inside calculate().

Set type to one of these values:

ValueMeaning
"number"A number field.
"boolean"An on/off setting.
"select"A dropdown list.

For numbers, min and max set optional limits. Set integer: true to allow only whole numbers; otherwise decimals are allowed.

For a dropdown, provide unique text choices in options. The default must match one of those choices.

Detailed rules

Setting fields ​

FieldRequiredMeaning
typeYes"number", "boolean", or "select".
labelYesDisplayed name; a string containing nonblank text.
defaultYesInitial value, valid for the chosen type.
min, maxNoNumber settings: finite, inclusive bounds. Unbounded when omitted.
integerNoNumber settings: boolean; defaults to false.
optionsFor "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 ​

Choose how your indicator’s calculated values appear on the chart.

Example ​

plots.js
Read-only preview
plots: {
  average: { kind: "line", label: "Moving average" }
}

Options ​

Required. Name each plot to match the values returned by calculate(). In the example, the plot is named average, so the calculation returns { average: [...] }.

Set kind to one of these values. If omitted, ChartingPark uses "line".

ValueMeaning
"line"A line connecting the values.
"columns"A column for each value.
"points"A point for each value.
"markers"An upward or downward arrow at each value.

Set color to a theme color such as "indicator", "up", or "down". The default is "indicator". Raw CSS colors are not supported.

Other plot fields let you fill between lines, shift a plot by candles, or place arrows above and below their values. See Detailed rules for every option.

For an indicator that only uses draw(), use plots: {}.

Detailed rules

Plot fields ​

All fields below are optional.

FieldDefaultMeaning
labelPlot nameDisplayed 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.
offset0Safe integer from -10000 to 10000; shifts the plot by candles.
colorChart's indicator colorA theme color name listed below.
negativeColorSame as colorColor for negative columns/points and the lower side of a fill.
fillToNo fillAnother 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.

calculate() ​

Calculate the values ChartingPark will draw for each candle.

Example ​

calculation.js
Read-only preview
calculate(bars) {
  return {
    movement: bars.map(bar => bar.close - bar.open)
  };
}

Options ​

Required. ChartingPark calls calculate(bars, inputs, context) with the candles, current settings, and instrument and interval information. You can omit arguments your calculation does not use.

Return an object with the same names as your plots. The example returns movement, so it needs a plot named movement.

Return one array per plot, with one entry per supplied candle. For 300 candles, each array must contain 300 entries. Each entry must be a finite number or null. Use null to leave a gap; do not remove entries.

Calculate from the supplied data each time. Do not rely on values saved by an earlier call.

During replay, ChartingPark supplies only revealed candles. For each candle’s result, use that candle and earlier candles only.

Detailed rules

Arguments ​

ArgumentMeaning
barsAvailable candles, oldest first, including loaded candles outside the visible chart.
inputsCurrent values of your settings.
contextInstrument 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.

levels ​

Add horizontal reference lines at fixed values in the indicator’s pane.

Example ​

levels.js
Read-only preview
levels: [0]

This adds a zero line, useful for an indicator that shows positive and negative values.

Options ​

Optional. Omit levels or use [] for no reference lines.

ValueMeaning
An array of finite numbersOne horizontal line at each value, such as [30, 70].

warmupBars() ​

Request the earlier candles your calculation needs. A 20-candle moving average needs 19 candles before the first visible result.

Example ​

warmup.js
Read-only preview
warmupBars(inputs) {
  return inputs.period - 1;
}

Options ​

Optional. Without warmupBars(), the requested count is zero.

Return a nonnegative safe integer: a whole number from 0 to Number.MAX_SAFE_INTEGER. The example assumes a positive, whole-number period setting.

ChartingPark handles the data loading. Earlier candles may not exist, so return null from your calculation wherever there is not enough history.

Detailed rules

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:

LimitMaximum
Earlier candles100,000
History pages8
Consecutive empty pages2

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.

draw() ​

Add lines, boxes, or text labels to your indicator.

Example ​

draw.js
Read-only preview
draw(bars) {
  const last = bars.at(-1);
  if (!last) return [];
  return [{
    type: "label",
    at: { time: last.time, value: last.high },
    text: "Latest candle"
  }];
}

Options ​

Optional. ChartingPark calls draw(bars, inputs, values, context) after a successful calculation. values contains the results returned by calculate().

Set each drawing’s type to one of these values:

ValueMeaning
"line"A line between from and to.
"box"A box with opposite corners at from and to.
"label"A text label positioned at at. Provide its text in text.

Positions use { time, value }. Use a candle’s UTC timestamp for time and a price or indicator value for value.

Return an array of up to 500 drawings, or [] for none. Each calculation replaces the previous drawings. Users cannot drag or edit these with the chart’s manual drawing tools.

Detailed rules

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:

ValueMeaning
"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 ​

ChartingPark passes candles to calculate() as bars, ordered from oldest to newest. These include loaded candles outside the visible chart.

data.js
Read-only preview
const closingPrices = bars.map(bar => bar.close);
Candle fieldMeaning
open, high, low, closeOpening, highest, lowest, and closing prices.
timeOpening time in UTC milliseconds.
volumeTrading volume, when the data source supplies it.
status"final" or "provisional".

The last candle can still be changing. Missing volume is not zero. Treat candles as read-only.

The optional third argument, context, tells your calculation which instrument and interval it is using. It contains metadata, not extra candle data.

Detailed rules

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

FieldTypeMeaning
timeNumberBar opening time as UTC epoch milliseconds, not seconds. Safe integer in the supported JavaScript date range.
openFinite numberOpening price.
highFinite numberHighest price; at least open and close.
lowFinite numberLowest price; at most open and close.
closeFinite numberClosing price or current evolving close.
statusString"final" or "provisional", as admitted from the data source.
volumeOptional finite numberNonnegative 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.

FieldMeaning
context.instrument.keyInstrument identifier supplied by the host.
context.instrument.symbol, nameDisplay symbol and name, normalized by the chart.
context.instrument.pricePrecisionNumber of decimal places for prices, from 0 to 15.
context.instrument.tickSizeOptional positive minimum price increment. Missing means unknown.
context.instrument.category, exchange, logoUrlOptional host-supplied classification and display metadata. Category is "forex", "crypto", "stocks", "commodities", or "indices".
context.instrument.sessionOptional normalized trading schedule; see the schedule fields below.
context.resolution.keyHost interval identifier, such as "5m".
context.resolution.kind"fixed" or "calendar".
context.resolution.unitFixed: "second", "minute", "hour". Calendar: "day", "week", "month".
context.resolution.multiplierPositive 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.

Execution lifecycle ​

ChartingPark runs your calculation when candle data, settings, or the script changes. Moving around the chart reuses the calculated results.

ActionWhat happens
Add an indicatorChartingPark calculates its values and draws it.
Receive new or updated candlesChartingPark recalculates using the supplied candles.
Change settingsChartingPark calculates with the new input values.
Pan or zoomChartingPark draws the relevant part of the existing results.

Do not use the number of calls as a clock. A candle can change without the number of candles changing.

Detailed rules

When code runs ​

ActionBehavior
Open or type a draftDoes not run the script.
Add or apply a scriptRuns the script body, checks settings, then calculates for the chart.
Receive new or changed candles, including earlier historyRecalculates with all available candles.
Change input settingsRecalculates and requests earlier history if needed.
Change instrument or intervalKeeps settings and recalculates for the new data.
Pan, zoom, or move the crosshairReuses existing results when data and settings are unchanged.
Change colorsKeeps calculated values.
Hide an indicatorStops its calculations and excludes it from automatic scaling. Showing it recalculates if data changed.
Remove an indicatorRemoves 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 ​

The editor reports problems with your code and with the values it returns. A script can have valid JavaScript syntax and still return values ChartingPark cannot draw.

Check these first:

  • Does each key returned by calculate() match a key in plots?
  • Does every output contain exactly one entry per candle?
  • Is each entry a finite number or null?
  • Can the calculation handle empty data and missing volume?

A calculation error hides that indicator’s output. Other indicators keep working. Fix the code and apply the change to run it again.

Detailed rules

What failed? ​

ProblemWhat happens
Invalid JavaScript or script fieldsThe editor reports the error; the new script is not added.
Invalid settings or warmup countThe change is rejected; existing settings stay in place.
Calculation throws or returns invalid valuesThat 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.

Limits and persistence ​

Custom indicators run JavaScript directly in your browser. They are not sandboxed. Only run code you trust; a slow or endless calculation can freeze the page.

ChartingPark supplies the chart’s candles, input settings, and instrument metadata. It does not supply Pine Script, a technical-analysis helper library, or extra symbol and interval data to your script.

Saving depends on the application hosting ChartingPark. Do not assume closing the chart will preserve your code. Keep a copy unless the application confirms it has saved your indicator.

Detailed rules

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.

Troubleshooting ​

Start with the editor's execution status. “No syntax errors” means the text parses; it does not prove the calculation is correct.

SymptomCheck
A declared output is missingReturn an object with the same keys as plots.
Wrong number of valuesReturn exactly bars.length entries for every output. Use null for gaps; do not filter them out.
Invalid numeric resultsCheck division by zero and missing volume. Return null, not NaN, infinity, or undefined.
No line at the startThe formula may need more candles. Check its period and warmupBars.
Changing a source default has no effectExisting valid settings survive source edits. Change the value in indicator Settings.
Code edits do not appearClick Apply changes. Typing does not run code.
A color is rejectedScript plots use theme tokens such as "up", "down", or "indicator", not hex colors.
A script from another platform failsChartingPark accepts its own JavaScript contract, not Pine Script or another library's API.

Check the numbers ​

Test a small input whose expected result you can calculate by hand. Then check short history, missing data, and live updates.

A script can run without errors and still implement the wrong formula. The complete examples include expected behavior you can compare against.

See error behavior for validation phases and supported capabilities before adding an unfamiliar API.

ChartingPark · Custom indicator documentation