NChartProNChartProNChartPro

This page is for AI assistants — ChatGPT, Gemini, Claude, Copilot and others — and for members who want one to write an NCR script. The same text as a file: /ncr-skill.md (short) and /ncr.txt (full). Human tutorials: Script Help.

NCR Script — writing indicators and strategies for NChartPro

NChartPro (https://nchartpro.com) is a charting and analysis website for the Nepal Stock Exchange (NEPSE). Members can write their own indicators in NCR Script and run them on the chart. This file teaches an AI assistant to write a correct NCR script for a member and to tell them how to use it in the app.

What NCR is

  • NCR is plain modern JavaScript (ES2020) with one extra global object, ncr. Everything a script can do — read bars, compute indicators, draw, make tables, backtest — goes through ncr.
  • It is NOT Pine Script, not Python, not MQL. There is no study(), plot(), ta., close[1] series syntax, //@version, var series or :=. Translate those ideas into JavaScript arrays (table below).
  • It runs in the member's browser in a sandbox (QuickJS in a worker). No network, no storage, no DOM, no account access, no order placing.
  • The app calls main() once after the bars are loaded. Series are ordinary arrays: index 0 is the OLDEST bar, index n-1 is the newest.

How to answer a request

  1. If the request is clear, write the script straight away. Ask a question only if something essential is missing (for example "buy when what crosses what?"). Default to the daily chart and sensible standard settings.
  2. Give ONE complete script in a single javascript code block — never a fragment, never several files. It must run when pasted into an empty editor.
  3. Put every number the member may want to change in ncr.input.* settings.
  4. Prefer the built-in ncr.ta.* indicators over hand-written maths — they are faster and match the chart's own indicators exactly.
  5. After the code, explain in 2–4 short sentences what it draws, then give the "How to use it in NChartPro" steps below. Many members read English as a second language: short sentences, common words.
  6. Never promise profit. A signal is "could have", never "will". NEPSE has no short selling, so a sell signal means exit / stay out.

The shape of every script

// 1. Declare what the script is — at the TOP LEVEL, first line.
//    overlay: true draws on the candles; false needs its own pane (see main).
ncr.study({ name: 'My indicator', overlay: true });

// 2. Settings — at the TOP LEVEL, never inside main(). Key must be unique.
const length = ncr.input.int('length', { label: 'Length', def: 20, min: 2, max: 500, step: 1 });
const src    = ncr.input.source('source');   // close by default; member can pick open/high/low/hl2…

// 3. main() — the app calls it once. Must be exported.
export function main() {
  const n = ncr.data.length();
  if (n < length) { ncr.warn('Need at least ' + length + ' bars.'); return; }

  const avg = ncr.ta.sma(src, length);       // bar-aligned array, NaN during warm-up

  ncr.plot.line('avg', avg, { color: ncr.chart.color('--accent', '#f5a623'), width: 2 });
}

For an oscillator in its own pane: ncr.study({ name, overlay: false }) and call ncr.plot.pane('new') at the start of main(). For a strategy, use ncr.strategy({ name, initialCash: 100000 }) instead of ncr.study.

Hard rules (a script that breaks one will not run or will be wrong)

  • ncr.study(...) or ncr.strategy(...) exactly once, at the top level.
  • export function main() { ... } must exist.
  • ncr.input.* calls at the top level, each with a unique key string.
  • Every plot needs a unique id string (first argument). Same id twice = replaced.
  • Series from ncr.data.* and ncr.ta.* are arrays the same length as the bars. Build your own with new Array(n).fill(NaN) and fill by index.
  • Indicator output starts with NaN during warm-up. Check isFinite(x) before comparing. Use NaN (not 0, not null) for "no value" in a plotted line.
  • "Previous bar" is arr[i - 1] inside a loop — guard i >= 1.
  • ncr.data.time() is epoch seconds. ncr.plot.marker / label and ncr.strategy.entry/exit take time in the same seconds.
  • Never write `await` / `async` — every ncr.* call already returns its value directly (error NCR2401).
  • Not available (error NCR2004 or "not defined"): fetch, XMLHttpRequest, WebSocket, window, document, localStorage, indexedDB, require, process, setTimeout, setInterval, crypto, performance, Intl, URL, TextEncoder, structuredClone. eval and new Function are refused.
  • import/export between the member's own saved scripts is allowed, but for an AI answer always write ONE self-contained file.
  • console.log works (same as ncr.log). Use ncr.warn / ncr.error for problems.
  • Budget: about 3 seconds and 64 MB per run. Fetched calls (ncr.ta.*, ncr.marks, ncr.fundamental, ncr.floorsheet, ncr.filter) are slow — call them once before the loop, never inside a loop over bars.
  • while loops must have a clear exit (error NCR2005).
  • A script has at most TWO panes: the price pane and ONE own pane. Every ncr.plot.pane('new') call goes to that SAME own pane — a second call does not make a third. Never put two different scales there (an RSI 0–100 and a ±1 signal flatten each other). If the user wants several things on different scales, write the main study, and tell them to make the other part a second script.
  • A Trading Horizon signal (below) should be its OWN script whose only own-pane plot is 'signal' — do not mix it into an indicator script.
  • Strategies: the signal is known at the close of bar i, so fill at the next bar's open (open[i + 1], time[i + 1]) and loop to n - 1. Use the same id in entry and exit. Long only for NEPSE.
  • Colours: ncr.chart.color('--accent', '#f5a623') follows the member's theme; useful tokens --accent, --color-up, --color-down, --color-info, --text-muted. A plain CSS colour string also works.
  • Some namespaces may need a higher plan (ncr.fundamental, ncr.floorsheet, ncr.filter, ncr.live, deep history). If a call is locked the editor says so before running. Data, indicators, plots, drawings and tables are the core.

Coming from Pine Script (TradingView)? Translate, never copy

Pine ScriptNCR Script
//@version=5 + indicator('X', overlay=true)ncr.study({ name: 'X', overlay: true });
strategy('X')ncr.strategy({ name: 'X', initialCash: 100000 });
close, open, high, low, volumencr.data.close() … (arrays) — or ncr.input.source(key)
close[1]close[i - 1] inside a for loop
bar_index, timeloop index i, ncr.data.time()[i] (seconds)
input.int(14, 'Length')ncr.input.int('length', { label: 'Length', def: 14 })
ta.sma(close, 20) / ta.ema / ta.rsincr.ta.sma(close, 20) / ncr.ta.ema / ncr.ta.rsi
ta.macd(close, 12, 26, 9)const m = ncr.ta.macd(close, 12, 26, 9); m.macd, m.signal, m.hist
ta.bb(close, 20, 2)const b = ncr.ta.bb(close, 20, 2); b.upper, b.middle, b.lower
ta.atr(14), ta.stoch(...)ncr.ta.atr(14), ncr.ta.stoch(14, 3) → { k, d }
ta.crossover(a, b)ncr.util.crossover(a, b) → boolean array (b may be a number)
ta.highest(high, 20)ncr.util.highest(high, 20)
plot(x, color=color.orange)ncr.plot.line('x', x, { color: '#f5a623', width: 2 })
plot(x, style=plot.style_histogram)ncr.plot.histogram('x', x, { color })
hline(70)ncr.plot.hline('ob', 70, { style: 'dashed' })
fill(p1, p2)ncr.plot.band('band', upper, lower, { opacity: 0.15 })
plotshape(cond, location.belowbar)loop + ncr.plot.marker('buys', { time, price, shape: 'arrowUp', text: 'BUY' })
line.new / box.new / label.newncr.draw.trendline / ncr.draw.rect / ncr.draw.text / ncr.plot.label
table.newncr.table.show('id', { title, columns, rows })
strategy.entry('L', strategy.long)ncr.strategy.entry('L', { side: 'long', qty, price: open[i+1], time: time[i+1] })
strategy.close('L')ncr.strategy.exit('L', { price: open[i+1], time: time[i+1] })
na, nz(x)NaN, isFinite(x) ? x : 0
var float x = 0 / x := x + 1a let outside the loop, updated inside it

Buy/sell signals for Trading Horizon (the backtester)

A study that plots ONE line with id 'signal' — 1 on a buy day, -1 on a sell day, 0 otherwise — can be tested in Trading Horizon. Once saved, it appears there under the member's own scripts, and the rules Buy when <script>.signal ≥ 1 and Sell when <script>.signal ≤ -1 test it. Use ncr.study({ name, overlay: false }) and ncr.plot.histogram('signal', signal, ...). Example "bt-rsi-bounce" below.

Every ncr.* function

Signature → what comes back. Anything not listed here does not exist — never invent a function.

Lifecycle

Declaring what a script is, and cleaning up after it.

  • ncr.study({ name, overlay?, pane? }) → Nothing.
  • ncr.strategy({ name, initialCash?, ... }) → Nothing.
  • ncr.version → A number. 1 today.
  • ncr.onStop(fn) → Nothing.

ncr.input

The script’s own settings form. Each call returns a value AND registers a control.

  • ncr.input.number(key, { label, def, min, max, step }) → The number the user has set, or def.
  • ncr.input.int(key, { label, def, min, max, step }) → An integer.
  • ncr.input.bool(key, { label, def }) → true or false.
  • ncr.input.string(key, { label, def }) → A string.
  • ncr.input.select(key, { label, def, options }) → The value of the chosen option, as a string.
  • ncr.input.source(key) → A ready-made series, one number per bar, aligned to the chart’s bars.
  • ncr.input.color(key, { label, def }) → A CSS colour string.

ncr.chart

The chart the script is running against. All instant — no fetching.

  • ncr.chart.symbol() → A string, e.g. NABIL.
  • ncr.chart.timeframe() → A string: 1m, 5m, 15m, 1h, d, w, m.
  • ncr.chart.chartType() → A string.
  • ncr.chart.barCount() → A number.
  • ncr.chart.visibleRange() → { logicalFrom, logicalTo, timeFrom, timeTo }, or null if the chart has not settled yet.
  • ncr.chart.theme() → The string dark or light.
  • ncr.chart.color(token, fallback) → A CSS colour string. The fallback if the token does not exist.

ncr.data

The bars. Copied into the sandbox before your first line runs, so every read here is instant.

  • ncr.data.close() → A numeric series, one value per bar.
  • ncr.data.open() → A numeric series.
  • ncr.data.high() → A numeric series.
  • ncr.data.low() → A numeric series.
  • ncr.data.volume() → A numeric series.
  • ncr.data.time() → A numeric series of epoch SECONDS.
  • ncr.data.bar(i) → { time, open, high, low, close, volume }, or undefined for an index outside the data.
  • ncr.data.bars() → A frozen array of bar objects.
  • ncr.data.length() → A number.
  • ncr.data.history({ bars, symbol, timeframe }) → A series of bar objects, oldest first.

ncr.ta

The app’s own 220-indicator C++ catalog. Prefer these over hand-written maths — they are faster and they cannot disagree with the chart.

  • ncr.ta.list() → An array of catalog entries.
  • ncr.ta.params(id) → An array of parameter descriptors.
  • ncr.ta.compute(id, params) → An object keyed by the indicator’s plot ids, each holding an array of { time, value } points.
  • ncr.ta.computeWithSource(id, params, source) → The same shape as ncr.ta.compute.
  • ncr.ta.sma(source, length) → A bar-aligned series, NaN through the warm-up.
  • ncr.ta.ema(source, length) → A bar-aligned series.
  • ncr.ta.rsi(source, length) → A bar-aligned series between 0 and 100.
  • ncr.ta.macd(source, fast, slow, signal) → { macd, signal, hist } — three bar-aligned series.
  • ncr.ta.atr(length) → A bar-aligned series in price units.
  • ncr.ta.bb(source, length, mult) → { upper, middle, lower } — three bar-aligned series.
  • ncr.ta.stoch(kLength, dLength) → { k, d } — two bar-aligned series between 0 and 100.
  • ncr.ta.obv() → A bar-aligned series.
  • ncr.ta.vwap() → A bar-aligned series.

ncr.plot

Everything a script draws. All of it belongs to the run and disappears when the script stops.

  • ncr.plot.line(id, values, { color, width, style }) → Nothing.
  • ncr.plot.histogram(id, values, { color }) → Nothing.
  • ncr.plot.band(id, upper, lower, { fill, opacity }) → Nothing.
  • ncr.plot.hline(id, price, { color, style }) → Nothing.
  • ncr.plot.marker(id, { time, price, shape, text, color }) → Nothing.
  • ncr.plot.label(id, { time, price, text, color }) → Nothing.
  • ncr.plot.fill(idA, idB, { color, opacity }) → Nothing.
  • ncr.plot.pane('price' | 'new') → Nothing.
  • ncr.plot.clear(id?) → Nothing.

ncr.draw

Geometry rather than series — trendlines, boxes and levels between two points in time. Removed when the script stops.

  • ncr.draw.trendline(id, p1, p2, style) → Nothing.
  • ncr.draw.rect(id, p1, p2, style) → Nothing.
  • ncr.draw.hline(id, price, style) → Nothing.
  • ncr.draw.vline(id, time, style) → Nothing.
  • ncr.draw.text(id, point, text, style) → Nothing.
  • ncr.draw.fib(id, p1, p2, style) → Nothing.
  • ncr.draw.remove(id) → Nothing.
  • ncr.draw.clear() → Nothing.

ncr.table

Rows and columns — screener results, broker lists, scoreboards. For anything that is a LIST rather than a series. Tables land in the editor’s Output rail, and also in the SCRIPT OUTPUT tab beside the Script tab on the chart pages, which shows them at the full width of the panel.

  • ncr.table.from(id, rows, opts) → Nothing.
  • ncr.table.show(id, { title, columns, rows, note }) → Nothing.
  • ncr.table.row(id, values) → Nothing.
  • ncr.table.clear(id) → Nothing.

ncr.marks

The ~130 C++ pattern detectors behind the chart’s mark rail — candle patterns, chart patterns, SMC, liquidity, trade levels.

  • ncr.marks.list() → An array of detector descriptors.
  • ncr.marks.params(detectorId) → An array of parameter descriptors.
  • ncr.marks.run(detectorId, params) → A result object holding arrays of points, rectangles, lines and shapes — whichever that detector produces.

ncr.ew

Elliott wave. Two engines: EWX, a grammar engine, and EW1, an ATR-zigzag engine. They disagree, on purpose.

  • ncr.ew.waves(engine) → An array of wave nodes, each with its time, price, degree and label.
  • ncr.ew.ewx(options) → The EWX result — waves plus the pattern grammar it matched.
  • ncr.ew.ew1(options) → The EW1 result.
  • ncr.ew.scene(options) → A scene object holding the shapes.
  • ncr.ew.targets() → An array of targets, each with a price and the wave relationship it comes from.

ncr.fundamental

Company figures from the fundamental screener. Every metric is a number or null — null means the company has not published it.

  • ncr.fundamental.get(symbol) → An object of metrics, or null if the symbol is unknown.
  • ncr.fundamental.field(symbol, key) → A number, or null if it is not published.
  • ncr.fundamental.list(filter?) → An array of rows, one per company.
  • ncr.fundamental.metrics() → An array of metric descriptors.

ncr.floorsheet

The trade-by-trade record: which broker bought from which, in what size, on which day.

  • ncr.floorsheet.dates() → An array of date strings, newest first.
  • ncr.floorsheet.daily(date, symbol?) → An array of trade rows.
  • ncr.floorsheet.brokers(date, side) → An array of broker rows with their volume and value.
  • ncr.floorsheet.matchingVolume(date) → An array of rows.
  • ncr.floorsheet.bigTrades() → An array of trade rows.

ncr.filter

Two things under one name: the twelve LIVE groups (gainers, spikes, breakouts) that describe right now, and every screen of the Filter section by name — Daily Filter, MKT, OTM, Bulk Trade, Broker Holding — which are stored per trading day and can be asked about the past.

  • ncr.filter.groups() → An array of group names.
  • ncr.filter.group(name, tf) → An array of rows, the shape depending on the group.
  • ncr.filter.filters() → An array of { id, label, section, page, span, keys, fields, blurb }.
  • ncr.filter.fields(id) → An array of column names.
  • ncr.filter.dates(limit?) → An array of YYYY-MM-DD strings.
  • ncr.filter.dailyFilter(query) → Every row, or the columns you named, or one value when you pass field.
  • ncr.filter.matchingVolume(query) → Every row, or the columns you named, or one value when you pass field.
  • ncr.filter.accumDist(query) → Every row, or the columns you named, or one value when you pass field.
  • ncr.filter.accumDistTotals(query) → Every row, or the columns you named, or one value when you pass field.
  • ncr.filter.accumDistHistory(query) → Every row, or the columns you named, or one value when you pass field.
  • ncr.filter.stocks(query) → Every row, or the columns you named, or one value when you pass field.
  • ncr.filter.liquid(query) → Every row, or the columns you named, or one value when you pass field.
  • ncr.filter.bulkTrade(query) → Every row, or the columns you named, or one value when you pass field.
  • ncr.filter.bulkTradeSum(query) → Every row, or the columns you named, or one value when you pass field.
  • ncr.filter.normalVolume(query) → Every row, or the columns you named, or one value when you pass field.
  • ncr.filter.normalVolumeAvg(query) → Every row, or the columns you named, or one value when you pass field.
  • ncr.filter.otm(query) → Every row, or the columns you named, or one value when you pass field.
  • ncr.filter.otmSummary(query) → Every row, or the columns you named, or one value when you pass field.
  • ncr.filter.mkt(query) → Every row, or the columns you named, or one value when you pass field.
  • ncr.filter.mktTotal(query) → Every row, or the columns you named, or one value when you pass field.
  • ncr.filter.pumpDump(query) → Every row, or the columns you named, or one value when you pass field.
  • ncr.filter.pumpDumpBrokers(query) → Every row, or the columns you named, or one value when you pass field.
  • ncr.filter.volatile(query) → Every row, or the columns you named, or one value when you pass field.
  • ncr.filter.bsVolume(query) → Every row, or the columns you named, or one value when you pass field.
  • ncr.filter.tickVolume(query) → Every row, or the columns you named, or one value when you pass field.
  • ncr.filter.sectorInvest(query) → Every row, or the columns you named, or one value when you pass field.
  • ncr.filter.brokerInvest(query) → Every row, or the columns you named, or one value when you pass field.
  • ncr.filter.brokerSectorInvest(query) → Every row, or the columns you named, or one value when you pass field.
  • ncr.filter.brokerHolding(query) → Every row, or the columns you named, or one value when you pass field.
  • ncr.filter.brokerGraph(query) → Every row, or the columns you named, or one value when you pass field.
  • ncr.filter.brokerFloat(query) → Every row, or the columns you named, or one value when you pass field.
  • ncr.filter.brokerBelowLtp(query) → Every row, or the columns you named, or one value when you pass field.
  • ncr.filter.brokerBelowLtpSum(query) → Every row, or the columns you named, or one value when you pass field.
  • ncr.filter.brokerActivity(query) → Every row, or the columns you named, or one value when you pass field.
  • ncr.filter.brokerActivitySum(query) → Every row, or the columns you named, or one value when you pass field.
  • ncr.filter.brokerTopHolding(query) → Every row, or the columns you named, or one value when you pass field.
  • ncr.filter.brokerProbFloat(query) → Every row, or the columns you named, or one value when you pass field.

ncr.live

Real-time streams. The only part of the API that keeps a script alive after main() returns — and the highest tier.

  • ncr.live.status() → A status object.
  • ncr.live.lastBar(symbol) → { symbol, time, open, high, low, close, volume }, or null if nothing has arrived.
  • ncr.live.onTick(symbol, callback) → An unsubscribe function.
  • ncr.live.onAnalysis(key, callback) → An unsubscribe function.
  • ncr.live.onAdvanceDecline(callback) → An unsubscribe function.

ncr.strategy.*

Entry, exit and the book. SIGNALS ONLY — there is no order function anywhere in this API.

  • ncr.strategy.entry(id, { side, qty, price, time }) → Nothing.
  • ncr.strategy.exit(id, { price, time }) → Nothing.
  • ncr.strategy.position() → The position object, or null when flat.
  • ncr.strategy.equity() → A number.
  • ncr.strategy.trades() → An array of { id, side, qty, entryTime, entryPrice, exitTime?, exitPrice?, pnl? }.

ncr.util

Small helpers that would otherwise be written from scratch in every script.

  • ncr.util.round(value, decimals) → A number.
  • ncr.util.fmtNumber(value) → A string.
  • ncr.util.fmtPct(fraction) → A string like 12.3%.
  • ncr.util.crossover(a, b) → A boolean per bar.
  • ncr.util.crossunder(a, b) → A boolean per bar.
  • ncr.util.highest(series, length) → A series, NaN through the warm-up.
  • ncr.util.lowest(series, length) → A series.

ncr.time

The clock, the market session and the Nepali calendar.

  • ncr.time.now() → A number in milliseconds.
  • ncr.time.marketOpen() → true or false.
  • ncr.time.toNepali(timestamp) → A string.

ncr.log and friends

The debug panel. console.log works too — it is an alias for ncr.log, so ordinary code you paste in behaves.

  • ncr.log(...values) → Nothing.
  • ncr.warn(...values) → Nothing.
  • ncr.error(...values) → Nothing.
  • ncr.assert(condition, message) → Nothing when the condition holds.

Three complete examples

Relative Strength Index (indicator, id ind-rsi)

Gains against losses, 0 to 100, in its own pane — with the Wilder smoothing spelled out.

// ── Relative Strength Index (RSI) ──────────────────────────────────────────
//
// RSI compares the size of recent gains with the size of recent losses and
// states the answer between 0 and 100. It is the first script here that needs
// its OWN PANE: a reading that lives between 0 and 100 cannot share a vertical
// axis with a share price of Rs 500 — it would flatten against the bottom.
//
// ⚠ THE THING PEOPLE GET WRONG IS THE SMOOTHING. RSI does not use an ordinary
//   average of gains. It uses WILDER SMOOTHING, which is an EMA with
//   k = 1 / period rather than 2 / (period + 1). A 14 period Wilder average
//   behaves like a 27 period EMA. Use the wrong one and your RSI turns several
//   bars early on every swing.

ncr.study({ name: 'RSI', overlay: false });

const period    = ncr.input.int('period', { label: 'Period', def: 14, min: 2, max: 200, step: 1 });
const upper     = ncr.input.number('upper', { label: 'Overbought', def: 70, min: 50, max: 100, step: 1 });
const lower     = ncr.input.number('lower', { label: 'Oversold',   def: 30, min: 0,  max: 50,  step: 1 });
const showBands = ncr.input.bool('showBands', { label: 'Show the 70 / 30 lines', def: true });
const src       = ncr.input.source('source');

export function main() {
  const n = ncr.data.length();
  // period + 1 because the first bar has no previous bar to compare against, so
  // 'period' price CHANGES need 'period + 1' prices.
  if (n < period + 1) { ncr.warn('Need at least ' + (period + 1) + ' bars.'); return; }

  // Ask for a pane of our own, under the price chart. Everything plotted after
  // this line lands there.
  ncr.plot.pane('new');

  const rsi = new Array(n).fill(NaN);

  // ── The seed: a plain average of the first 'period' changes ───────────────
  let gainSum = 0;
  let lossSum = 0;
  for (let i = 1; i <= period; i++) {
    const change = src[i] - src[i - 1];
    if (change > 0) gainSum = gainSum + change;     // an up bar
    else            lossSum = lossSum - change;     // a down bar; losses are kept POSITIVE
  }
  let avgGain = gainSum / period;
  let avgLoss = lossSum / period;

  // The first RSI value sits at index 'period'.
  rsi[period] = rsiFrom(avgGain, avgLoss);

  // ── Wilder smoothing, bar by bar ─────────────────────────────────────────
  for (let i = period + 1; i < n; i++) {
    const change = src[i] - src[i - 1];
    const gain = change > 0 ?  change : 0;
    const loss = change < 0 ? -change : 0;

    // ⚠ THIS IS THE WILDER STEP, and it is the whole difference between a
    //   correct RSI and a plausible-looking wrong one:
    //     new average = (old average x (period - 1) + today) / period
    //   which is an EMA with k = 1 / period.
    avgGain = (avgGain * (period - 1) + gain) / period;
    avgLoss = (avgLoss * (period - 1) + loss) / period;

    rsi[i] = rsiFrom(avgGain, avgLoss);
  }

  // ⚠ IN PRACTICE, CALL THIS. Same maths, in C++, and it cannot drift out of
  //   step with the chart's own RSI pane.
  const fromCatalog = ncr.ta.rsi(src, period);

  ncr.plot.line('rsi', rsi, {
    color: ncr.chart.color('--accent', '#f5a623'), width: 2, style: 'solid',
  });
  ncr.plot.line('rsi-catalog', fromCatalog, {
    color: ncr.chart.color('--color-info', '#4a9eff'), width: 1, style: 'dotted',
  });

  // Horizontal reference levels. hline takes a PRICE (here an RSI value, since
  // we are in the RSI pane), not a bar index.
  if (showBands) {
    ncr.plot.hline('ob', upper,      { color: ncr.chart.color('--color-down', '#ef5350'), style: 'dashed' });
    ncr.plot.hline('os', lower,      { color: ncr.chart.color('--color-up',   '#26a69a'), style: 'dashed' });
    ncr.plot.hline('mid', 50,        { color: ncr.chart.color('--text-muted', '#888888'), style: 'dotted' });
  }
}

// ── A named helper ──────────────────────────────────────────────────────────
// A script is an ordinary ES module, so you can define as many functions as you
// like. Anything you want ANOTHER script to import must be marked 'export'.
export function rsiFrom(avgGain, avgLoss) {
  // ⚠ THE DIVIDE-BY-ZERO CASE IS REAL, not theoretical: a run of bars that never
  //   closes lower makes avgLoss exactly 0, and 100 - 100 / (1 + x / 0) is NaN.
  //   The correct answer there is 100 — nothing but gains.
  if (avgLoss === 0) return avgGain === 0 ? 50 : 100;
  const rs = avgGain / avgLoss;
  return 100 - 100 / (1 + rs);
}

MA crossover (strategy, id strat-ma-cross)

Fast EMA over slow EMA, filled at the next bar open. The skeleton every other strategy is a variation of.

// ── Strategy: moving average crossover ─────────────────────────────────────
//
// The oldest trend-following rule there is. Buy when a fast average crosses
// above a slow one, sell when it crosses back. It is here first because its
// shape — one condition in, the mirror condition out — is the skeleton every
// other strategy on this list hangs off.

// ncr.strategy replaces ncr.study. initialCash is the starting balance the
// equity curve is measured from; it does not limit position size in this
// example, which sizes in fixed quantity.
ncr.strategy({ name: 'MA crossover', initialCash: 100000 });

const fastLen = ncr.input.int('fastLen', { label: 'Fast EMA', def: 20,  min: 2, max: 200, step: 1 });
const slowLen = ncr.input.int('slowLen', { label: 'Slow EMA', def: 50,  min: 3, max: 400, step: 1 });
const qty     = ncr.input.int('qty',     { label: 'Shares per trade', def: 100, min: 1, max: 100000, step: 1 });

export function main() {
  const n = ncr.data.length();
  if (n < slowLen + 2) { ncr.warn('Need at least ' + (slowLen + 2) + ' bars.'); return; }
  if (fastLen >= slowLen) { ncr.warn('Fast must be shorter than slow.'); return; }

  const close = ncr.data.close();
  const open  = ncr.data.open();
  const time  = ncr.data.time();

  // Both averages from the C++ catalog, so they match the ones you would put on
  // the chart by hand.
  const fast = ncr.ta.ema(close, fastLen);
  const slow = ncr.ta.ema(close, slowLen);

  // ncr.util.crossover returns one boolean per bar: true on the bar where the
  // first series finishes above the second having been below it on the bar
  // before. crossunder is the mirror. Computing them once up front is both
  // faster and easier to read than writing the two-bar test inline.
  const goldenCross = ncr.util.crossover(fast, slow);
  const deathCross  = ncr.util.crossunder(fast, slow);

  // Draw the averages so the signals can be checked by eye against the chart.
  ncr.plot.line('fast', fast, { color: ncr.chart.color('--accent', '#f5a623'), width: 2 });
  ncr.plot.line('slow', slow, { color: ncr.chart.color('--color-info', '#4a9eff'), width: 2 });

  // Our own record of whether a position is open. ncr.strategy.position() would
  // answer the same question; a local flag is used here because it makes the
  // control flow visible to someone reading their first strategy.
  let long = false;

  // ⚠ STOP THE LOOP ONE BAR EARLY. The fill happens on bar i + 1, so the last
  //   bar has no bar to be filled on. Running to n - 1 would read past the end
  //   of the array and produce an entry at price undefined.
  for (let i = 1; i < n - 1; i++) {
    // Skip bars where either average is still warming up.
    if (!isFinite(fast[i]) || !isFinite(slow[i])) continue;

    // ⚠ THE FILL IS THE NEXT BAR'S OPEN, not this bar's close. The signal is
    //   only known once bar i has finished, and the first price anyone could
    //   actually trade after that is the open of bar i + 1.
    const fillPrice = open[i + 1];
    const fillTime  = time[i + 1];

    if (!long && goldenCross[i]) {
      // The first argument is an id you choose. Use the same id on the exit so
      // the runtime can pair them into one trade.
      ncr.strategy.entry('ma', { side: 'long', qty: qty, price: fillPrice, time: fillTime });
      long = true;
      mark(fillTime, fillPrice, true, 'BUY');
    } else if (long && deathCross[i]) {
      ncr.strategy.exit('ma', { price: fillPrice, time: fillTime });
      long = false;
      mark(fillTime, fillPrice, false, 'SELL');
    }
  }

  report();
}

// ── Two helpers reused by most of these examples ────────────────────────────
// They are exported so that ANOTHER of your scripts can import them:
//   import { mark, report } from './ma-crossover';
export function mark(t, price, isBuy, text) {
  ncr.plot.marker(isBuy ? 'entries' : 'exits', {
    time: t,
    price: price,
    shape: isBuy ? 'arrowUp' : 'arrowDown',
    text: text,
    color: isBuy
      ? ncr.chart.color('--color-up', '#26a69a')
      : ncr.chart.color('--color-down', '#ef5350'),
  });
}

export function report() {
  // trades() hands back every closed trade the run recorded.
  const trades = ncr.strategy.trades();
  const closed = trades.filter(function (t) { return t.exitPrice !== undefined; });

  if (closed.length === 0) { ncr.log('No completed trades in the loaded history.'); return; }

  let wins = 0;
  let sum  = 0;
  for (let i = 0; i < closed.length; i++) {
    if (closed[i].pnl > 0) wins = wins + 1;
    sum = sum + closed[i].pnl;
  }

  ncr.log(closed.length + ' trades, ' +
          ncr.util.fmtPct(wins / closed.length) + ' of them profitable');
  ncr.log('Total P&L (before any commission): ' + ncr.util.fmtNumber(sum));
  ncr.log('Equity: ' + ncr.util.fmtNumber(ncr.strategy.equity()));
  // ⚠ NO COSTS ARE MODELLED. Broker commission, SEBON fee and DP charge would
  //   each take a bite out of the number above, and on many trades all of it.
}

Signal: RSI bounce (indicator, id bt-rsi-bounce)

Mean reversion: +1 as RSI climbs back above 30, −1 above 70. Crossing a fixed number.

// ── Signal 3: RSI leaves oversold ─────────────────────────────────────────
//
// Mean reversion: buy when RSI climbs back above 30, sell when it climbs above
// 70. Crossing a FIXED number works exactly like crossing a line — pass the
// number instead of a series.

ncr.study({ name: 'Signal: RSI bounce', overlay: false });

// ── Settings ──────────────────────────────────────────────────────────────
// Each ncr.input line adds a box to this script's settings, so the numbers
// can be changed without editing code. 'def' is the starting value.
const length = ncr.input.int('length', { label: 'RSI length', def: 14, min: 2, max: 100, step: 1 });
const low = ncr.input.number('low', { label: 'Oversold', def: 30, min: 1, max: 50, step: 1 });
const high = ncr.input.number('high', { label: 'Overbought', def: 70, min: 50, max: 99, step: 1 });

// ── main() ────────────────────────────────────────────────────────────────
// The app calls main() once, after the bars are loaded. All the work is in here.
export function main() {
  // Read the bars: one number per day, oldest first. n = how many days.
  const close = ncr.data.close();
  const n = ncr.data.length();
  const r = ncr.ta.rsi(close, length);
  const buy = ncr.util.crossover(r, low);    // RSI moves up through 30
  const sell = ncr.util.crossover(r, high);  // RSI moves up through 70

  // The answer: one number per day. It starts as 0 (do nothing) everywhere,
  // and the loop below writes 1 on a buy day and -1 on a sell day.
  const signal = new Array(n).fill(0);
  // Walk the days from oldest to newest and decide each one.
  for (let i = 0; i < n; i++) {
    if (buy[i]) signal[i] = 1;
    else if (sell[i]) signal[i] = -1;
  }

  // ── Plot ──────────────────────────────────────────────────────────────────
  // A histogram reads best for a signal: a bar up on a buy day, a bar down on a
  // sell day, nothing in between. The plot's id is 'signal' — that is the line
  // name Trading Horizon shows for this script.
  ncr.plot.histogram('signal', signal, { color: ncr.chart.color('--accent', '#4a9eff') });
  ncr.plot.hline('buy-level', 1, { color: ncr.chart.color('--color-up', '#26a69a') });
  ncr.plot.hline('sell-level', -1, { color: ncr.chart.color('--color-down', '#ef5350') });
}

Error codes the editor shows

CodeMeaningFix
NCR1001The script is emptyWrite a script, or press New to start from the worked example.
NCR1002Could not save to the serverNothing is lost: the editor always writes your text to this browser first, so it survives a refresh. Sign in and press Save again to publish it.
NCR1003That file is not a scriptChoose a .ncrs, .js or .txt source file, or a .ncr compiled by this app.
NCR2001Syntax errorGo to the line and column in the message. The cause is usually one line ABOVE it — a missing closing bracket, quote or comma on the previous line is only noticed here.
NCR2002The script is too largeMove shared code into a second script and import it — imported modules are counted separately. The current ceiling is shown in Settings.
NCR2003The script does not declare itselfAdd ncr.study({ name: "…" }) as the first statement. This is a warning, not a refusal.
NCR2004That global is not available inside a scriptThere is no replacement, and that is the point: a script cannot reach the network, your account or the page. Everything a script is allowed to read comes through ncr.*. For data, use ncr.data, ncr.ta, ncr.fundamental or ncr.floorsheet.
NCR2005This loop has no way outGive the loop an exit, or a condition that becomes false. This is a warning, not a refusal — the script still runs, and the sandbox stops it at the time limit and reports NCR3001. The warning exists so you find out before the wait rather than after it.
NCR2101Cannot find the imported scriptSave the other script first and give it exactly the path you are importing (Save ▸ the name field). Then re-run.
NCR2102Circular importMove the code they both need into a third script and import that from both. The message names the whole chain.
NCR2103Too many imported scriptsCombine small helper scripts. The current ceiling is shown in Settings.
NCR2104That import path is not allowedImport only your own saved scripts, by their path — for example ./lib/helpers.
NCR2401Remove the await — ncr.* calls are already synchronousDelete the await. It is not a style preference: awaiting resumes the rest of your script inside the engine's internal job queue, and an ncr.* call cannot be made from there. In practice the script prints its first result, stops part-way through without an error, plots nothing, and the engine has to be restarted before anything else will run. Nothing inside a script is ever asynchronous — there are no timers, no network and no dynamic imports in the sandbox — so await never buys anything.
NCR3001The script ran too long and was stoppedCheck every while and for: the counter must change, and the condition must eventually become false. Raise the limit in Settings only after the loop is correct — a runaway loop will use whatever it is given.
NCR3002The script ran out of memoryBuild one value per bar, not per bar per bar. If you have a loop inside a loop over the whole series, that is bars × bars values and it will not fit.
NCR3003Something is not definedCheck the spelling, and check that the declaration is ABOVE the use. If you pressed “Run line”, remember a fragment runs on its own: names from the rest of the file are not there.
NCR3004Reading a property of undefined or nullCheck the length before indexing, and use ?. when a value may legitimately be missing: row?.close gives undefined instead of throwing.
NCR3005The plot drew nothingThat is not always an error: the warm-up bars SHOULD be NaN. If the whole line is missing, check the period is smaller than the number of bars loaded, and that the values are numbers rather than strings.
NCR3006A number came out as NaNSkip the warm-up bars rather than computing over them, and guard divisions. Note NaN === NaN is false — test with Number.isNaN(x), never x === NaN.
NCR4001That function needs a higher planUpgrade, or write the script so it works without that data. The error can be caught like any other, which is how a shared script degrades instead of dying.
NCR4002That capability is not releasedNothing a user can do — it is not for sale, it is not finished. Report it if you believe it should be available.
NCR4003This script needs a higher plan than yoursRun it anyway to see how far it gets, upgrade, or open the source and adapt it.
NCR5001The script engine failed to startReload the page. If it persists, report it: this is not something a script can cause.
NCR5002The script engine stopped unexpectedlyPress Run again — the next run gets a fresh engine. Report it if it repeats.
NCR5003This file was made by a newer versionReload to pick up the current build. If it still refuses, ask the author to re-export.
NCR5004This file is damagedDownload it again. A file that fails this check is refused rather than run.

How to use it in NChartPro — give the member these steps

  1. Sign in at https://nchartpro.com and open the chart: https://nchartpro.com/main/chart.
  2. Pick the stock and the timeframe (for example 1D) at the top of the chart.
  3. At the bottom of the chart, open the Script tab. (The full-page editor is at https://nchartpro.com/experimental/script.)
  4. Press New, delete the sample text, and paste the script.
  5. Press Run (or Ctrl + Enter). The lines appear on the chart; messages and errors appear in the Debug panel. Tables appear in Script Output.
  6. Change the numbers in the Inputs rail on the right — no code editing needed.
  7. Press Save and give it a name. It is kept on the member's account under Open / My scripts.
  8. Press Add to chart to keep it on the chart as a normal indicator, with its own row and settings in the legend. It stays after a reload.
  9. For a buy/sell signal script: save it, then open Trading Horizon and pick it from the indicator list to backtest it.
  10. If it shows an error (a code like NCR2001), copy the error text and the script back to the AI and ask it to fix it.

Scripts need a signed-in account and a plan that includes the Script editor — see https://nchartpro.com/help/features. A script can only draw and calculate; it can never place an order or touch the member's account.

More: every function with its own runnable example, all 41 example scripts and every lesson are in https://nchartpro.com/ncr.txt