# Arkenwell Quant Studio — AI Script-Writing Guide

Canonical URL: https://www.arkenwell.co/quant-studio-ai.md
Audience: any AI assistant (ChatGPT, Claude, Gemini, Copilot, local models) asked to write a Quant Studio script for an Arkenwell user.
Note: Goal: the user describes an indicator or alert idea in plain English; you reply with ONE script they paste into Quant Studio, press Ctrl+Enter, and see work on the first run.

If you only read one section, read **Hard rules** and **Output checklist**.

---

## What Quant Studio is

Quant Studio is the script editor inside the Arkenwell terminal's chart window. A script is a TypeScript file in a small language called **AQR** (Arkenwell Quant Runtime). It receives the OHLCV bars of the chart's current symbol and timeframe, computes anything from them, and returns lines, histograms, levels, zones, markers, a bullish/bearish verdict and small tables of values. Lines, levels, zones and markers are drawn on the chart; the verdict and tables are listed in the output panel under the editor. The same script can be armed as a server-side alert (Alerts → condition "Custom script"), which keeps evaluating with the browser closed.

Availability: Quant Studio is part of the Professional+ plan.

It is NOT Pine Script, NOT Python, NOT free-form Node. It is plain TypeScript with one importable module, `@arkenwell/quant`, run in a sandbox with no network and no DOM.

---

## Hard rules (a script that breaks any of these fails or is flagged)

1. **Exactly one import source**: `@arkenwell/quant`. Importable names: `defineIndicator`, `input`, `ak`, and the types `CandleData`. Importing anything else is error AQR-001. No `require`, no dynamic `import()`.
2. **Exactly one default export**: `export default defineIndicator({ name, inputs?, calculate(ctx) { ... } });`
3. **`calculate(ctx)` must `return { series: {...}, ... }`** — an object. Returning nothing or an array fails.
4. **A series `data` array is `{ time, value }[]`, ascending by time.** Never a bare `number[]`. Use the candle's own `c.time` unchanged (it is a Unix-seconds number or a `YYYY-MM-DD` string — do not convert it).
5. **`ak.technical.*` functions return TimeSeries (`{time,value}[]`) OR an object of TimeSeries.** Every function whose Returns column below is in braces (`macd`, `bollingerBands`, `keltner`, `donchian`, `adx`, `stochastic`, `ichimoku`, …) returns an OBJECT — pass one member (`.macd`, `.mid`, `.k`, `.adx`) as `data`, never the whole object (AQR-014 in the editor, ARK-005 at run time).
6. **No `NaN`, `Infinity` or `undefined` values in `data`.** Only push finite values. The runtime leaves such points out and prints a warning rather than failing, but a script that produces them is usually wrong (a division by zero, an index before the warm-up). `ak.series` helpers never emit a non-finite point.
7. **Deterministic only.** No `Math.random()`, `Date.now()`, `new Date()` with no argument — the chart and the server alert must compute the same numbers (AQR-051). Derive everything from `ctx.candles`.
8. **No network / DOM / timers / storage**: `fetch`, `XMLHttpRequest`, `window`, `document`, `setTimeout`, `localStorage`, `process`, `eval`, `Function`, `globalThis` do not exist (AQR-050).
9. **Declare every input you read.** `ctx.inputs.x` must have a matching `x: input.…` in `inputs` (AQR-030).
10. **Colours** are `#RRGGBB`, `#RRGGBBAA` or `rgba(r,g,b,a)`.
11. **Limits**: 3,000 ms execution (the script is stopped past it), 200,000 output points in total, 32 series, 2,000 markers, 100 levels, 100 zones, 100 kB of source; server alerts see at most 5,000 candles. Avoid O(n²) loops over all bars; use a rolling window, a single pass, or an `ak.series` helper.
12. **Never invent a function.** If it is not in the `ak.technical` or `ak.series` tables below, write the maths inline (pattern 4). Pine/TA-Lib names (`ta.sma`, `bbands`, `supertrend`, `stoch`) do not exist — see the mapping.
13. **`calculate` is synchronous.** No `async`, no `await`, no Promise — the result must be returned directly (ARK-005).
14. **A period is a whole number of bars ≥ 1.** Passing `undefined`, `0`, a negative number or `NaN` throws a run-time error naming the function ("sma: period must be a number of bars ≥ 1"). The usual cause is reading an input that was never declared.

---

## The script skeleton (copy this shape every time)

```ts
import { defineIndicator, input, ak } from "@arkenwell/quant";

export default defineIndicator({
  name: "My Indicator",
  inputs: {
    period: input.number({ default: 20, min: 1, max: 500, label: "Period" }),
  },
  calculate(ctx) {
    const period = ctx.inputs.period as number;
    const sma = ak.technical.sma(ctx.candles, period);
    return {
      series: {
        sma: { type: "line", color: "#60A5FA", title: "SMA", data: sma },
      },
    };
  },
});
```

Only import `input` if you declare inputs, and only import `ak` if you call `ak.…` (unused imports are harmless, but a **missing** import is AQR-002).

---

## The context: `ctx`

| Field | Type | Notes |
|---|---|---|
| `ctx.candles` | `CandleData[]` | Oldest first, newest LAST. `{ time, open, high, low, close, volume? }` |
| `ctx.inputs` | `Record<string, any>` | Values of the inputs you declared. Cast: `ctx.inputs.period as number` |
| `ctx.symbol` | `string` | Chart symbol, e.g. `NIFTY` |
| `ctx.timeframe` | `string` | Chart timeframe, e.g. `5m`, `1D` |

`volume` can be missing or 0 — **index candles (NIFTY, BANKNIFTY) carry no volume.** Any volume-based indicator (VWAP, OBV, MFI, volume profile) must handle that: return `[]` (draws nothing) rather than a fake flat line, and say so in your reply.

The last bar is usually still forming on intraday charts. For verdicts and alerts, use the last bar as it is; do not shift by one unless the user asks for "confirmed close only" (then use `candles.length - 2`).

---

## `input.*` — adjustable parameters (shown under PARAMS and in the indicator's settings card)

```ts
period:  input.number({ default: 14, min: 2, max: 100, step: 1, label: "Period" }),
show:    input.boolean({ default: true, label: "Show signal" }),
source:  input.select({ options: ["close", "open", "high", "low"], default: "close", label: "Source" }),
```

- `input.number` REQUIRES `default` (AQR-031). Keep `default` inside `[min, max]`.
- Read with a cast: `as number`, `as boolean`, `as string`.
- Every period the user may want to tune should be an input, not a literal.
- Inputs are frozen at the moment a script alert is armed.
- The runtime enforces the declaration: a number outside `[min, max]` is held to the nearest bound, a select value that is not in `options` falls back to the default. Do not re-validate inputs in the script.

---

## `ak.technical` — the complete indicator list (43)

First argument is always the candle array (`c` below = `ctx.candles`). Anything not listed here does not exist. Defaults are shown after `=`; an argument without a default is required.

**Moving averages**

| Call | Returns | Notes |
|---|---|---|
| `sma(c, period)` | TimeSeries | SMA of close |
| `ema(c, period)` | TimeSeries | seeded with the SMA of the first `period` bars |
| `wma(c, period)` | TimeSeries | linearly weighted, newest bar heaviest |
| `vwma(c, period=20)` | TimeSeries | volume-weighted; needs volume |
| `hma(c, period=20)` | TimeSeries | Hull |
| `dema(c, period=20)` | TimeSeries | double EMA |
| `tema(c, period=20)` | TimeSeries | triple EMA |
| `kama(c, period=10, fast=2, slow=30)` | TimeSeries | Kaufman adaptive |

**Momentum**

| Call | Returns | Notes |
|---|---|---|
| `rsi(c, period=14)` | TimeSeries 0–100 | Wilder |
| `macd(c, fast=12, slow=26, signal=9)` | `{ macd, signal, histogram }` | OBJECT |
| `stochastic(c, kPeriod=14, dPeriod=3)` | `{ k, d }` | OBJECT, 0–100 |
| `stochRsi(c, rsiPeriod=14, stochPeriod=14, kSmooth=3, dSmooth=3)` | `{ k, d }` | OBJECT, 0–100 |
| `williamsR(c, period=14)` | TimeSeries −100–0 | |
| `cci(c, period=20)` | TimeSeries | |
| `roc(c, period=10)` | TimeSeries % | |
| `ppo(c, fast=12, slow=26, signal=9)` | `{ ppo, signal, histogram }` | OBJECT; MACD in percent |
| `trix(c, period=15, signal=9)` | `{ trix, signal }` | OBJECT |
| `tsi(c, long=25, short=13, signal=13)` | `{ tsi, signal }` | OBJECT, −100–100 |
| `ultimateOscillator(c, short=7, medium=14, long=28)` | TimeSeries 0–100 | |

**Trend**

| Call | Returns | Notes |
|---|---|---|
| `adx(c, period=14)` | `{ adx, plusDI, minusDI }` | OBJECT, each 0–100; ADX is strength, not direction |
| `superTrend(c, period=10, multiplier=3)` | `{time,value,trend:"UP"\|"DOWN",color}[]` | map to `{time,value}` for a line, or keep `color` per point |
| `psar(c, start=0.02, step=0.02, max=0.2)` | `{ long, short }` | OBJECT; draw each with `dots: true` |
| `ichimoku(c, conversion=9, base=26, spanB=52, displacement=26)` | `{ tenkan, kijun, spanA, spanB, chikou }` | OBJECT; spans end at the last bar |
| `regressionChannel(c, period=100, width=2)` | `{ mid, upper, lower }` | OBJECT; covers the last `period` bars only |
| `choppiness(c, period=14)` | TimeSeries 0–100 | above ~62 sideways, below ~38 trending |

**Volatility and bands**

| Call | Returns | Notes |
|---|---|---|
| `atr(c, period=14)` | TimeSeries | Wilder, price units |
| `stddev(c, period=20)` | TimeSeries | population std-dev of close |
| `bollingerBands(c, period=20, stdDev=2)` | `{ upper, mid, lower }` | OBJECT; `basis` = `mid`; population std-dev |
| `bbWidth(c, period=20, stdDev=2)` | TimeSeries % | (upper − lower) ÷ mid × 100 |
| `keltner(c, period=20, multiplier=2, atrPeriod=10)` | `{ upper, mid, lower }` | OBJECT; EMA ± multiplier × ATR |
| `donchian(c, period=20)` | `{ upper, mid, lower }` | OBJECT; window INCLUDES the current bar |
| `chandelier(c, period=22, multiplier=3)` | `{ long, short }` | OBJECT; ATR trailing stops |
| `zscore(c, period=20)` | TimeSeries σ | close vs its rolling mean |

**Volume** (all need volume except where noted)

| Call | Returns | Notes |
|---|---|---|
| `vwap(c)` | TimeSeries | cumulative from the FIRST candle passed |
| `vwapBands(c)` | `{ vwap, upper, lower }` | OBJECT; ±1 volume-weighted σ |
| `obv(c)` | TimeSeries | on-balance volume |
| `mfi(c, period=14)` | TimeSeries 0–100 | money flow index |
| `cmf(c, period=20)` | TimeSeries −1–1 | Chaikin money flow |
| `adLine(c)` | TimeSeries | accumulation/distribution |
| `forceIndex(c, period=13)` | TimeSeries | Elder |
| `rvol(c, period=20)` | TimeSeries × | relative volume, 1.0 = normal |

**Levels and transforms**

| Call | Returns | Notes |
|---|---|---|
| `pivotPoints(c)` | `{pp,r1,r2,r3,s1,s2,s3}` or `null` | plain numbers from the PREVIOUS bar, not a series |
| `heikinAshi(c)` | `CandleData[]` | feed into other functions: `ak.technical.ema(ak.technical.heikinAshi(c), 20)` |

All functions that take a period omit bars until enough history exists, so output arrays are SHORTER than `ctx.candles`. Combine series with `ak.series` (below), which matches points by `time` — never by index.

**Not in the library — write the maths inline:** volume profile, anchored VWAP, session opening range, any custom oscillator or pattern detector. Pattern 4 shows the shape.

---

## `ak.series` — maths on any series (18)

These take a **series** (`{time,value}[]`): the result of an `ak.technical` call, one member of an object result, the result of another `ak.series` call, or an array you built. `b` may be a series or a plain number wherever shown as `b`.

| Call | Returns | Notes |
|---|---|---|
| `source(c, field="close")` | TimeSeries | field: `open` `high` `low` `close` `volume` `hl2` `hlc3` `ohlc4` |
| `sma(s, period)` · `ema(s, period)` · `wma(s, period)` | TimeSeries | moving average OF a series, e.g. EMA of RSI |
| `rma(s, period)` | TimeSeries | Wilder smoothing, α = 1/period |
| `stddev(s, period)` | TimeSeries | rolling population σ |
| `highest(s, period)` · `lowest(s, period)` | TimeSeries | rolling max / min |
| `sum(s, period)` | TimeSeries | rolling sum |
| `change(s, period=1)` | TimeSeries | value − value `period` points earlier |
| `zscore(s, period)` | TimeSeries σ | empty where σ = 0 |
| `add(a, b)` · `sub(a, b)` · `mul(a, b)` · `div(a, b)` | TimeSeries | matched by time; `div` omits points where the divisor is 0 |
| `crossover(a, b)` | TimeSeries | the points where `a` rises above `b` — map them to markers |
| `crossunder(a, b)` | TimeSeries | the points where `a` falls below `b` |
| `last(s)` | `number \| null` | newest value; `null` when the series is empty — always handle `null` |

Rules: results contain a point only where every input has one; a non-finite result is omitted, never emitted as 0; periods follow rule 14.

### Name mapping from other languages

| You might write | AQR |
|---|---|
| `ta.sma(close, n)` / `SMA(close, n)` / pandas-ta `sma` | `ak.technical.sma(ctx.candles, n)` |
| `ta.ema` / `EMA` | `ak.technical.ema(ctx.candles, n)` |
| `ta.rsi` / `RSI` | `ak.technical.rsi(ctx.candles, n)` |
| `ta.macd` / `MACD` | `ak.technical.macd(ctx.candles, f, s, sig)` → `.macd/.signal/.histogram` |
| `ta.bb` / `BBANDS` | `ak.technical.bollingerBands(ctx.candles, n, k)` → `.upper/.mid/.lower` |
| `ta.supertrend` / `supertrend` | `ak.technical.superTrend(...)` (capital T) |
| `ta.stoch` / `STOCH` | `ak.technical.stochastic(...)` → `.k/.d` |
| `ta.atr` / `ATR` | `ak.technical.atr(...)` |
| `ta.vwap` | `ak.technical.vwap(ctx.candles)` |
| `ta.wma` / `ta.hma` / `ta.vwma` | `ak.technical.wma / hma / vwma(ctx.candles, n)` |
| `ta.dmi` / `ADX` | `ak.technical.adx(ctx.candles, n)` → `.adx/.plusDI/.minusDI` |
| `ta.sar` / `SAR` | `ak.technical.psar(ctx.candles)` → `.long/.short`, draw with `dots: true` |
| `ta.kc` / `ta.donchian` | `ak.technical.keltner(...)` / `ak.technical.donchian(...)` → `.upper/.mid/.lower` |
| `ta.crossover(a, b)` / `ta.crossunder` | `ak.series.crossover(a, b)` / `ak.series.crossunder(a, b)` — returns the cross POINTS, not a boolean |
| `ta.highest(x, n)` / `ta.lowest` | `ak.series.highest(series, n)` / `ak.series.lowest(series, n)` |
| `ta.change(x)` / `x - x[1]` | `ak.series.change(series, 1)` |
| `ta.rma` | `ak.series.rma(series, n)` |
| `ta.sma(ta.rsi(close, 14), 9)` (indicator of indicator) | `ak.series.sma(ak.technical.rsi(ctx.candles, 14), 9)` |
| `hl2`, `hlc3`, `ohlc4` | `ak.series.source(ctx.candles, "hl2")` |
| `plot(x)` | an entry in `series` |
| `hline(y)` | an entry in `levels` |
| `plotshape(cond)` | an entry in `markers` |
| `alertcondition` | a `signals` entry and/or a `marker` on the last bar (then arm the alert) |
| `input.int / input.float` | `input.number` |
| `var`/series history (`x[1]`) | index into your own array: `arr[i - 1]` |
| `close, high, low` (implicit per-bar) | `ctx.candles[i].close` — AQR receives ALL bars at once; loop or `.map` |

---

## The output: what `calculate` returns

```ts
return {
  series:  { name: { type, data, color?, lineWidth?, lineStyle?, title?, pane?, paneGroup?, dots? } },
  levels:  [{ price, color, label? }],
  zones:   [{ priceTop, priceBottom, color, label? }],
  markers: [{ time, position, shape, color, text? }],
  signals: [{ type, strength, reason }],
  tables:  [{ rows: [{ label, value }] }],
};
```

All keys are optional; return at least one with something in it. Including `series` (an empty `{}` is fine) keeps the shape obvious.

### `series`
| Field | Values |
|---|---|
| `type` | `"line"` \| `"histogram"` \| `"area"` (anything else = AQR-040 / ARK-005) |
| `data` | `{ time, value, color? }[]`, one point per bar, oldest first; per-point `color` colours that bar/segment. Out-of-order points are sorted and a repeated bar keeps its last value, each with a warning |
| `pane` | `"overlay"` (default, on the price chart) or `"new"` (own pane below) |
| `paneGroup` | any string; series sharing it share one new pane |
| `color` | `#RRGGBB` / `#RRGGBBAA` / `rgba()` |
| `lineWidth` | 1–4 (line/area) |
| `lineStyle` | 0 solid · 1 dotted · 2 dashed · 3 large dashed · 4 sparse dotted |
| `title` | legend + axis label |
| `dots` | `true` (line only) draws each point as a dot, no connecting line (e.g. Parabolic SAR) |

**Scale rule:** an overlay series shares the price axis. Anything that is not in price units — RSI (0–100), MACD, ATR, %B, z-score, volume — MUST use `pane: "new"` or it flattens the chart. Prices/averages/bands/channels stay on overlay.

### `levels`, `zones`
Horizontal price lines / shaded bands **on the price chart only**. They cannot be placed inside an oscillator pane. To draw RSI 70/30 guides, add constant-value series in the same `paneGroup` (pattern below). Keep `label` stable between runs — alerts bind to labels.

### `markers`
`position`: `"above"` | `"below"`. `shape`: `"circle"` | `"arrowUp"` | `"arrowDown"` only (not `"square"`, `"triangleUp"`, …). `time` must be the `time` of an actual candle. An alert fires when a marker is printed on the **latest bar**, so build signal markers from conditions evaluated per bar.

### `signals`
`type`: `"bullish"` | `"bearish"` | `"neutral"` (NOT `"buy"`/`"sell"` — AQR-043). `strength` 0–1. The **last entry** is the script's current verdict; server alerts fire when it flips. Push one entry describing the latest state.

### `tables`
`[{ rows: [{ label: string, value: string | number }] }]` — up to 8 tables of 40 rows. Each row is listed in the output panel under the editor as `label: value` after a run. Use it for current readings ("RSI now: 57.3"). It is not drawn on the chart and cannot drive an alert. A non-finite number is shown as "—".

### Debugging
`console.log(...)` prints to the same output panel (up to 200 lines per run; objects as JSON). It does nothing in a server alert. Remove logging from a finished script unless the user asked for it.

---

## Patterns (all verified to lint clean and execute)

### 1. Combining two series by time
Output arrays of different indicators start on different bars. `ak.series` matches by `time`:
```ts
const spread = ak.series.sub(fast, slow);            // fast − slow, only where both exist
const pct = ak.series.mul(ak.series.div(spread, slow), 100);
```
For logic the helpers do not cover, look up by `time` yourself:
```ts
const slowByTime = new Map(slow.map(p => [p.time, p.value]));
const above = fast.filter(p => slowByTime.has(p.time) && p.value > (slowByTime.get(p.time) as number));
```

### 2. Crossover markers + verdict (EMA cross)
```ts
import { defineIndicator, input, ak } from "@arkenwell/quant";

export default defineIndicator({
  name: "EMA Cross Signals",
  inputs: {
    fast: input.number({ default: 9, min: 2, max: 100, label: "Fast" }),
    slow: input.number({ default: 21, min: 3, max: 300, label: "Slow" }),
  },
  calculate(ctx) {
    const fast = ak.technical.ema(ctx.candles, ctx.inputs.fast as number);
    const slow = ak.technical.ema(ctx.candles, ctx.inputs.slow as number);
    const up = ak.series.crossover(fast, slow);
    const down = ak.series.crossunder(fast, slow);
    const spread = ak.series.last(ak.series.sub(fast, slow));
    return {
      series: {
        fast: { type: "line", color: "#34D399", title: "EMA fast", data: fast },
        slow: { type: "line", color: "#F59E0B", title: "EMA slow", data: slow },
      },
      markers: [
        ...up.map(p => ({ time: p.time, position: "below" as const, shape: "arrowUp" as const, color: "#10B981", text: "Cross up" })),
        ...down.map(p => ({ time: p.time, position: "above" as const, shape: "arrowDown" as const, color: "#EF4444", text: "Cross down" })),
      ],
      signals: spread === null ? [] : [{
        type: spread > 0 ? "bullish" as const : "bearish" as const,
        strength: 0.6,
        reason: spread > 0 ? "Fast EMA above slow EMA" : "Fast EMA below slow EMA",
      }],
    };
  },
});
```
(`as const` keeps the literal types TypeScript needs for `position`, `shape` and `type`. Markers may be returned in any order; the runtime sorts them.)

### 3. Oscillator in its own pane with guide lines (RSI 70/30)
```ts
import { defineIndicator, input, ak } from "@arkenwell/quant";

export default defineIndicator({
  name: "RSI with Bands",
  inputs: {
    period: input.number({ default: 14, min: 2, max: 100, label: "Period" }),
    upper: input.number({ default: 70, min: 50, max: 95, label: "Overbought" }),
    lower: input.number({ default: 30, min: 5, max: 50, label: "Oversold" }),
  },
  calculate(ctx) {
    const rsi = ak.technical.rsi(ctx.candles, ctx.inputs.period as number);
    const flat = (v: number) => rsi.map(p => ({ time: p.time, value: v }));
    return {
      series: {
        rsi: { type: "line", color: "#A78BFA", title: "RSI", pane: "new", paneGroup: "rsi", data: rsi },
        ob: { type: "line", color: "#EF4444", lineStyle: 2, lineWidth: 1, title: "Overbought", pane: "new", paneGroup: "rsi", data: flat(ctx.inputs.upper as number) },
        os: { type: "line", color: "#10B981", lineStyle: 2, lineWidth: 1, title: "Oversold", pane: "new", paneGroup: "rsi", data: flat(ctx.inputs.lower as number) },
      },
    };
  },
});
```

### 4. Inline maths when the library has no function: prior-N-bar channel + breakout marker
`ak.technical.donchian` includes the current bar in its window, so a breakout test against it can never fire. This version uses the PREVIOUS `n` bars — the shape to copy for any custom rolling calculation:
```ts
import { defineIndicator, input } from "@arkenwell/quant";

export default defineIndicator({
  name: "Donchian Breakout",
  inputs: {
    period: input.number({ default: 20, min: 2, max: 200, label: "Lookback" }),
  },
  calculate(ctx) {
    const n = ctx.inputs.period as number;
    const c = ctx.candles;
    const upper: { time: number | string; value: number }[] = [];
    const lower: { time: number | string; value: number }[] = [];
    const markers: { time: number | string; position: "above" | "below"; shape: "arrowUp" | "arrowDown"; color: string; text: string }[] = [];
    for (let i = n; i < c.length; i++) {
      let hi = -Infinity, lo = Infinity;
      for (let j = i - n; j < i; j++) { hi = Math.max(hi, c[j].high); lo = Math.min(lo, c[j].low); }
      upper.push({ time: c[i].time, value: hi });
      lower.push({ time: c[i].time, value: lo });
      if (c[i].close > hi) markers.push({ time: c[i].time, position: "below", shape: "arrowUp", color: "#10B981", text: "Break up" });
      if (c[i].close < lo) markers.push({ time: c[i].time, position: "above", shape: "arrowDown", color: "#EF4444", text: "Break down" });
    }
    return {
      series: {
        upper: { type: "line", color: "#60A5FA", title: "Donchian high", data: upper },
        lower: { type: "line", color: "#60A5FA", title: "Donchian low", data: lower },
      },
      markers,
    };
  },
});
```
(The window is the previous `n` bars, so a breakout compares against levels that exclude the current bar — the usual definition. The inner loop is O(n·period); keep `period` modest.)

### 5. Z-score in its own pane, with the current reading in a table
```ts
import { defineIndicator, input, ak } from "@arkenwell/quant";

export default defineIndicator({
  name: "Close Z-Score",
  inputs: {
    period: input.number({ default: 20, min: 5, max: 200, label: "Period" }),
  },
  calculate(ctx) {
    const z = ak.technical.zscore(ctx.candles, ctx.inputs.period as number);
    const now = ak.series.last(z);
    return {
      series: {
        z: { type: "histogram", color: "#38BDF8", title: "Z-score", pane: "new", paneGroup: "z", data: z },
      },
      tables: [{ rows: [{ label: "Z-score now", value: now === null ? "not enough bars" : now.toFixed(2) }] }],
    };
  },
});
```

### 6. Levels and a zone from the data (previous-day-style high/low)
```ts
import { defineIndicator } from "@arkenwell/quant";

export default defineIndicator({
  name: "Range Levels",
  calculate(ctx) {
    const c = ctx.candles.slice(-100);
    if (c.length < 2) return { series: {} };
    const hi = Math.max(...c.map(x => x.high));
    const lo = Math.min(...c.map(x => x.low));
    const mid = (hi + lo) / 2;
    return {
      series: {},
      levels: [
        { price: hi, color: "#EF4444", label: "Range high" },
        { price: lo, color: "#10B981", label: "Range low" },
      ],
      zones: [{ priceTop: mid * 1.002, priceBottom: mid * 0.998, color: "#38BDF8", label: "Mid zone" }],
    };
  },
});
```

### 7. ADX / DMI from the library (object result, three lines in one pane)
```ts
import { defineIndicator, input, ak } from "@arkenwell/quant";

export default defineIndicator({
  name: "ADX / DMI",
  inputs: {
    period: input.number({ default: 14, min: 2, max: 100, label: "Period" }),
  },
  calculate(ctx) {
    const r = ak.technical.adx(ctx.candles, ctx.inputs.period as number);
    return {
      series: {
        adx: { type: "line", color: "#F59E0B", title: "ADX", lineWidth: 2, pane: "new", paneGroup: "adx", data: r.adx },
        plusDI: { type: "line", color: "#10B981", title: "+DI", pane: "new", paneGroup: "adx", data: r.plusDI },
        minusDI: { type: "line", color: "#EF4444", title: "-DI", pane: "new", paneGroup: "adx", data: r.minusDI },
      },
    };
  },
});
```

### 8. Per-point colour (colour bars by trend)
```ts
const st = ak.technical.superTrend(ctx.candles, 10, 3);
// keep the colour that superTrend already supplies on each point:
series: { st: { type: "line", title: "SuperTrend", color: "#94A3B8", data: st.map(p => ({ time: p.time, value: p.value, color: p.color })) } }
```

### 9. Indicator of an indicator (RSI with an EMA signal line)
```ts
import { defineIndicator, input, ak } from "@arkenwell/quant";

export default defineIndicator({
  name: "RSI + Signal",
  inputs: {
    period: input.number({ default: 14, min: 2, max: 100, label: "RSI period" }),
    smooth: input.number({ default: 9, min: 2, max: 50, label: "Signal EMA" }),
  },
  calculate(ctx) {
    const rsi = ak.technical.rsi(ctx.candles, ctx.inputs.period as number);
    const signal = ak.series.ema(rsi, ctx.inputs.smooth as number);
    return {
      series: {
        rsi: { type: "line", color: "#38BDF8", title: "RSI", pane: "new", paneGroup: "rsi", data: rsi },
        signal: { type: "line", color: "#F59E0B", title: "Signal", pane: "new", paneGroup: "rsi", data: signal },
      },
    };
  },
});
```

---

## Using a script as an alert

Alerts → condition **Custom script** → pick the saved script. Alerts bind to the script's OUTPUT, not its internals:
- **series** — a named series crosses a fixed level, or crosses another series
- **signals** — the verdict flips to bullish/bearish (optionally above a minimum strength)
- **markers** — a marker is printed on the most recent bar
- **levels / zones** — price reaches a level (by `label`) or enters/exits a zone (by `label`)

Rules that matter when you write for alerts: keep series names, level labels and zone labels **stable** between versions of the script; do not depend on `Date`/random; inputs and script version are frozen when the alert is armed; evaluation fails closed (a script error never produces a false alert). Quant Studio and script alerts require the Professional+ plan (₹3,000/month or ₹21,600/year); on other plans the editor and the Custom script condition are locked.

---

## Output checklist (run this before you answer)

- [ ] One code block, language `ts`, containing the **entire** file, nothing else inside it.
- [ ] Imports only from `"@arkenwell/quant"`, and every name used (`defineIndicator`, `input`, `ak`) is imported.
- [ ] `export default defineIndicator({ name: "…", … })` with a human name.
- [ ] Every `ctx.inputs.x` is declared; every `input.number` has `default` within `min`/`max`.
- [ ] Every `ak.technical.*` and `ak.series.*` call is in the tables above, with the exact spelling (`bollingerBands`, `superTrend`, `stochRsi`, `williamsR`, `crossover`) and its arguments in the listed order.
- [ ] `ak.technical` gets candles; `ak.series` gets a series. `ak.series.last(...)` is checked for `null`.
- [ ] Object results unpacked (`.macd`, `.mid`, `.k`, `.vwap`…).
- [ ] Non-price indicators have `pane: "new"`.
- [ ] No NaN/Infinity/undefined in `data`; all `data` arrays are `{time,value}` ascending.
- [ ] Markers use `arrowUp`/`arrowDown`/`circle` and `above`/`below`; signals use `bullish`/`bearish`/`neutral`.
- [ ] `calculate` is not `async` and returns an object.
- [ ] No `Math.random`, `Date.now`, `fetch`, `window`, timers.
- [ ] Volume-dependent logic degrades to empty output when `volume` is missing/0.

## How to reply to the user

1. Give the script in one copyable code block.
2. Under it, three short lines: **How to use** (open any chart → **QUANT STUDIO** → paste → **Ctrl+Enter** → **ADD TO CHART**; Save with Ctrl+S), **What it draws** (one sentence), **Tunable** (the inputs).
3. If the idea needs something the runtime cannot do (live option-chain data, GEX, other symbols, news, network, order placement) say so plainly and offer the closest honest version built from the symbol's own candles. **Scripts only see the chart symbol's OHLCV bars.** They cannot read the option chain, GEX/DEX, other instruments, fundamentals, or place trades. Never fake those values.
4. If the user pastes an error: `AQR-0xx` codes are linter findings (the editor underlines them; **Ctrl+.** or AUTOCORRECT ALL fixes many); `ARK-0xx` are run-time errors. Common ones: `AQR-014` object passed as data (unpack it), `AQR-010` unknown function name, `AQR-030` undeclared input, `AQR-016` unknown `ak.series` helper, `AQR-017` function called on `ak` directly (`ak.sma` → `ak.technical.sma`), `ARK-003` stopped after 3 s (O(n²) loop), `ARK-005` unusable result (the message names the series), `ARK-008` with "period must be a number of bars" (an undeclared or misspelt input), `ARK-010` more than 200,000 points or 32 series. `[WARN]` lines in the output panel are not errors: they say which points or inputs the runtime adjusted.
5. Do not give trading advice or claim a script is profitable. Indicators describe price history; they do not predict it.

## Error code quick reference

| Code | Meaning |
|---|---|
| AQR-001 | import from something other than `@arkenwell/quant` |
| AQR-002 | `defineIndicator`/`input`/`ak` used but not imported |
| AQR-003/004 | no `defineIndicator(...)` / not `export default` |
| AQR-005/006 | no `calculate(ctx)` / it never returns |
| AQR-010 | unknown `ak.technical` function |
| AQR-011/012/013 | a bar-count argument <1 / fractional / a required period missing |
| AQR-014 | object result passed as series data |
| AQR-016/017 | unknown `ak.series` helper / function called on `ak` without `technical.` or `series.` |
| AQR-020/021/022 | wrong ctx access (`ctx.close`, `ctx.candle`, `ctx.candles.close`) — use `ctx.candles.map(c => c.close)` |
| AQR-030/031/032 | undeclared input / `input.number` without default / default outside min–max |
| AQR-040…045 | invalid series type, pane, colour, signal type, marker shape or position |
| AQR-050/051 | browser/network API used / non-deterministic code |
| ARK-001 | import not allowed |
| ARK-002 | syntax error (line and column are marked) |
| ARK-003 | ran longer than 3 s and was stopped |
| ARK-004 / ARK-006 | no default export / no `calculate` |
| ARK-005 | result unusable: nothing returned, a Promise, `data` not an array, unknown series `type` |
| ARK-007 | no bars loaded (or more than 100,000) |
| ARK-008 | exception in the script, including a library call with a bad argument |
| ARK-010 | more than 200,000 points or 32 series |

## Terminal context an AI may be asked about

The terminal (https://terminal.arkenwell.co) is a live NSE derivatives terminal: option chain and Greeks, dealer GEX/DEX and gamma flip, dealer hedging flow, unusual activity, institutional flow, volatility, macro, news, alerts, and the chart with Quant Studio. Product overview for AI: https://www.arkenwell.co/llms-full.txt. In-terminal reference: https://terminal.arkenwell.co/aqr-docs.html.

Chart indicators that exist as built-ins can be converted to editable scripts with the **code button on their legend row** ("Edit in Quant Studio"); the generated script reproduces the chart's values exactly. This is the fastest way for a user to start from any standard indicator and then modify its formula; for ADX, Ichimoku, Keltner, Donchian, Parabolic SAR, OBV, MFI and CVD (estimated) the generated script writes the maths out in full.
