Appearance
Appearance
ChartingPark / CUSTOM INDICATORS
Build custom indicators, plot your calculations, and see your ideas on the chart. Start with a working example or write one with AI.
Use ChartingPark’s script format to choose where the indicator appears, its settings, and what to draw.
Write your calculation inside calculate(). It receives the candles and returns the values to draw.
The results appear on the price chart or in a separate panel below it.
1const period = 20;
2
3return {
4 pane: "main",
5 plots: { average: { kind: "line" } },
6 calculate(bars) {
7 const average = bars.map((bar, index) => {
8 if (index < period - 1) return null;
9 const window = bars.slice(index - period + 1, index + 1);
10 return window.reduce((sum, bar) => sum + bar.close, 0) / period;
11 });
12 return { average };
13 },
14};
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.
Close the editor to see your indicator on the chart. The moving-average line comes from the code you just added.
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.
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.
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.
Open Indicators → Create indicator. Replace the example code with the JavaScript from AI, give it a name, and click Add to chart.
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.
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.
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.
1return {
2 pane: 'main',
3 inputs: {
4 period: { type: 'number', label: 'Period', default: 20, min: 1, max: 10000, integer: true },
5 method: { type: 'select', label: 'Method', default: 'SMA', options: ['SMA', 'EMA'] },
6 source: { type: 'select', label: 'Source', default: 'close', options: ['open', 'high', 'low', 'close'] },
7 smooth: { type: 'boolean', label: 'Smooth over three bars', default: false },
8 },
9 plots: { average: { label: 'Average', color: 'indicator' } },
10 warmupBars(inputs) { return inputs.period - 1 + (inputs.smooth ? 2 : 0); },
11 calculate(bars, inputs) {
12 const prices = bars.map(bar => bar[inputs.source]);
13 let sum = 0, previous = null;
14 const average = prices.map((price, i) => {
15 sum += price;
16 if (i >= inputs.period) sum -= prices[i - inputs.period];
17 if (i < inputs.period - 1) return null;
18 previous = inputs.method === 'SMA' || previous === null
19 ? sum / inputs.period
20 : previous + (price - previous) * 2 / (inputs.period + 1);
21 return previous;
22 });
23 return { average: inputs.smooth ? average.map((value, i) =>
24 i < 2 || average[i - 2] === null ? null : (value + average[i - 1] + average[i - 2]) / 3
25 ) : average };
26 },
27};
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.
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.
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.
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.
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.Both versions draw the closing price minus the opening price in a separate panel.
1//@version=6
2indicator("Candle movement", overlay = false)
3plot(close - open, title = "Movement")
1return {
2 pane: "separate",
3 plots: { movement: { kind: "line" } },
4 calculate(bars) {
5 return {
6 movement: bars.map(bar => bar.close - bar.open)
7 };
8 }
9};
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.
Everything you can use in your indicator code: supported settings, candle data, calculations, and drawing options.
Your script returns an object that tells ChartingPark where to draw, which settings to show, and how to calculate the indicator.
| Field | What it does | Required? |
|---|---|---|
pane | Chooses the price chart or a separate panel. | Yes |
inputs | Adds settings the user can change. | No |
plots | Describes the lines, columns, points, or markers to draw. | Yes |
calculate() | Calculates the values for each candle. | Yes |
levels | Adds 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.
1return {
2 pane: "separate",
3 inputs: {
4 period: {
5 type: "number", label: "Period",
6 default: 5, min: 1, integer: true
7 }
8 },
9 plots: { change: { kind: "line" } },
10 calculate(bars, inputs) {
11 const change = bars.map((bar, i) =>
12 i < inputs.period ? null
13 : bar.close - bars[i - inputs.period].close
14 );
15 return { change };
16 },
17 levels: [0],
18 warmupBars(inputs) { return inputs.period; },
19 draw(bars, inputs, values) {
20 const last = bars.at(-1);
21 const value = values.change.at(-1);
22 if (!last || value == null) return [];
23 return [{
24 type: "label",
25 at: { time: last.time, value },
26 text: "Latest change"
27 }];
28 }
29};
Choose where the indicator appears. Everything your script draws appears in that area.
1pane: "separate"
Required. There is no default.
| Value | Meaning |
|---|---|
"main" | On the price chart. |
"separate" | In a panel below the price chart. |
Add settings people can change without editing the code.
1inputs: {
2 period: {
3 type: "number",
4 label: "Period",
5 default: 20,
6 min: 1,
7 integer: true
8 }
9}
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:
| Value | Meaning |
|---|---|
"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.
| 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. |
These rules apply to defaults and current values:
"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.true or false only. Example: { type: 'boolean', label: 'Show signals', default: true }.{ type: 'select', label: 'Method', default: 'SMA', options: ['SMA', 'EMA'] }.Undeclared settings are rejected. Free-text and color input types are not supported.
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.
Choose how your indicator’s calculated values appear on the chart.
1plots: {
2 average: { kind: "line", label: "Moving average" }
3}
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".
| Value | Meaning |
|---|---|
"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: {}.
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. |
Accepted theme color names:
background, grid, text, up, down, line, indicator, drawing,
orderEntry, orderStopLoss, orderTakeProfitThe 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.
null leaves a gap. negativeColor does not recolor negative line segments.negativeColor when supplied.negativeColor when supplied. Crossings can split the color.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.
{ values, colors }, with one color entry per candle.null for the normal color, including negativeColor where applicable.null keeps the normal above/below coloring.null for none.position to "above" or "below"."above" and "below" add a fixed gap; "at" centers the arrow on its value.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.
Calculate the values ChartingPark will draw for each candle.
1calculate(bars) {
2 return {
3 movement: bars.map(bar => bar.close - bar.open)
4 };
5}
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.
| 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. |
plots.{ values, colors } for colors per candle.bars.length entries. Values must be finite numbers or null.null where a value cannot be calculated. Never remove those entries with filter().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.
Add horizontal reference lines at fixed values in the indicator’s pane.
1levels: [0]
This adds a zero line, useful for an indicator that shows positive and negative values.
Optional. Omit levels or use [] for no reference lines.
| Value | Meaning |
|---|---|
| An array of finite numbers | One horizontal line at each value, such as [30, 70]. |
Request the earlier candles your calculation needs. A 20-candle moving average needs 19 candles before the first visible result.
1warmupBars(inputs) {
2 return inputs.period - 1;
3}
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.
inputs. No candles are passed to this function.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.
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.
Add lines, boxes, or text labels to your indicator.
1draw(bars) {
2 const last = bars.at(-1);
3 if (!last) return [];
4 return [{
5 type: "label",
6 at: { time: last.time, value: last.high },
7 text: "Latest candle"
8 }];
9}
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:
| Value | Meaning |
|---|---|
"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.
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().
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. |
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.
ChartingPark passes candles to calculate() as bars, ordered from oldest to newest. These include loaded candles outside the visible chart.
1const closingPrices = bars.map(bar => bar.close);
| Candle field | Meaning |
|---|---|
open, high, low, close | Opening, highest, lowest, and closing prices. |
time | Opening time in UTC milliseconds. |
volume | Trading 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.
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. |
null when your calculation needs volume that is unavailable.closeTime, endTime, symbol, interval, timezone, session object, or chart controller. Instrument and interval information comes from context.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.
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.
ChartingPark runs your calculation when candle data, settings, or the script changes. Moving around the chart reuses the calculated results.
| Action | What happens |
|---|---|
| Add an indicator | ChartingPark calculates its values and draws it. |
| Receive new or updated candles | ChartingPark recalculates using the supplied candles. |
| Change settings | ChartingPark calculates with the new input values. |
| Pan or zoom | ChartingPark 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.
| 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. |
pane moves the indicator. Removing its old panel can also remove manual drawings on that panel.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.
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:
calculate() match a key in plots?null?A calculation error hides that indicator’s output. Other indicators keep working. Fix the code and apply the change to run it again.
| 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.
console.log(), console.info(), console.warn(), console.error(), and console.debug() messages from this script.console.log("Loaded candles:", bars.length) prints the supplied candle count.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.[Unprintable value].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.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.
The editor adapter does not provide:
ta helpers, or a third-party indicator API.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.
fetch() calls are your own unmanaged behavior, not supported ChartingPark integrations.Start with the editor's execution status. “No syntax errors” means the text parses; it does not prove the calculation is correct.
| Symptom | Check |
|---|---|
| A declared output is missing | Return an object with the same keys as plots. |
| Wrong number of values | Return exactly bars.length entries for every output. Use null for gaps; do not filter them out. |
| Invalid numeric results | Check division by zero and missing volume. Return null, not NaN, infinity, or undefined. |
| No line at the start | The formula may need more candles. Check its period and warmupBars. |
| Changing a source default has no effect | Existing valid settings survive source edits. Change the value in indicator Settings. |
| Code edits do not appear | Click Apply changes. Typing does not run code. |
| A color is rejected | Script plots use theme tokens such as "up", "down", or "indicator", not hex colors. |
| A script from another platform fails | ChartingPark accepts its own JavaScript contract, not Pine Script or another library's API. |
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.