# 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. - Short version (this file): https://nchartpro.com/ncr-skill.md - Full reference — every lesson, function, example and error: https://nchartpro.com/ncr.txt - Human help page: https://nchartpro.com/help/script ## 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 ```javascript // 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 Script | NCR 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`, `volume` | `ncr.data.close()` … (arrays) — or `ncr.input.source(key)` | | `close[1]` | `close[i - 1]` inside a `for` loop | | `bar_index`, `time` | loop 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.rsi` | `ncr.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.new` | `ncr.draw.trendline` / `ncr.draw.rect` / `ncr.draw.text` / `ncr.plot.label` | | `table.new` | `ncr.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 + 1` | a `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