> Every Taji docs page as Markdown: https://docs.taji.is/llms.txt

# Porting a Pine script

Only when the user asks. The result is a TypeScript indicator in the desk, written as `references/indicators.md` says; this file is the Pine-to-Taji mapping and the order of work.

## The steps

1. Read the Pine whole, including its `indicator(...)` call and every `input.*`. List each construct it uses.
2. Check the list against § Not ported. A script that needs one cannot be ported: say which construct and why before you write anything, and write nothing.
3. To change a custom already stored, `read read/desk/<id>/catalog/<name>` first: its row carries `source` and `test`. Edit that, never a rewrite from memory.
4. Write the source, and a `test` that pins what the script is for (a flat series, a known cross). Type-check against `references/taji.d.ts` first.
5. `call verb/desk/<id>/indicators/write`. A 422 is the report: read the diagnostic's line or the failed invariant, fix, write again. Do not stop at the first green write; the fixture is not the user's chart.
6. `call verb/desk/<id>/chart/<pane>/add_indicator`, then read it back (`indicators/test`, the user's chart, and `read get/indicators`). A `fault` in the meta is fixed in the source.
7. Report what you did not port, then the last few rows (`GET /get/indicators`; with no shell, the bars to read off the chart) with their times, for the user to set beside their TradingView chart (you read none of TradingView's values). Equal from the first shared bar is a port. A gap at the first bars only is the origin (TradingView starts a series at its loaded history, Taji at the chart's first bar or the binding's `origin`); a gap on every bar is a different formula or different bars, and the values alone do not say which.

## Mapping

| Pine | Taji |
|---|---|
| `indicator(title, overlay=true)` | `name`, `pane: "price"` (`"own"` for no overlay) |
| `input.int/float/bool`, `input.source` | `input.int/float/bool`, `input.source` in `inputs`; read a source in `next`, not `setup` |
| `title`, `tooltip`, `group`, `inline`, `active` on any `input.*` | the same keys in the trailing options object (`input.int(5, { min: 2, title: "Period", group: "Bands" })`); `active` is a `bool` input's name |
| `input.string` with `options` | `input.choice(d, { options: [...] })` |
| `input.string` without `options`, `input.timeframe`, `input.color`, `input.session`, `input.symbol` | `input.text`, `input.interval`, `input.color`, `input.session`, `input.symbol`: each reads as a string in `next` |
| `input.time(defval, confirm=…)` | `input.time(defval?, { confirm })`: UTC milliseconds as Pine's (compare `bar.time * 1000`); with `confirm: true` the default may be left out |
| `input.price(defval, confirm=…)` | `input.price(defval?, { confirm })`; a `time` and `price` sharing `inline` are picked as one point |
| `confirm=true` on any other `input.*` | refused: Taji asks on the chart for `time` and `price` only |
| anchoring at an `input.time` (`time >= t`, Anchored VWAP) | `input.anchor("time", { at: "<time input>" })`: `starts` on the first bar opening at or after it |
| `close[1]`, any `x[k]` | state: `s.prev = x` at the end of `next`, or an array in state for `k` > 1 |
| `var x = 0`, `x := …` | a field of `setup`'s state, `s.x` |
| `ta.sma/ema/rma/rsi/change` | `ta.sma/ema/rma/rsi/change`: a handle made in `setup`, `.next(x)` once per bar. `sma`, `ema`, `rma` and `rsi` are the built-ins' own numbers |
| `ta.crossover(a, b)`, `ta.crossunder` | `ta.crossUp()`, `ta.crossDown()`, `.next(a, b)` |
| any other `ta.*` (`wma stdev highest lowest atr tr valuewhen …`) | by hand in state, from the formula in TradingView's public `ta` library; do not guess one |
| `ta.pivothigh(l, r)`, `ta.pivotlow(l, r)` | by hand: the pivot is strictly above (below) the `r` bars after it and at least level with the `l` bars before it |
| `ta.pivot_point_levels(type, anchor, developing)`, a Pivot Points script | not written in a script: bind the built-in `pivot_point_levels` (`add_indicator`; `type` is its `kind`, `anchor` its `anchor`; params in `read/catalog/pivot_point_levels`), which draws each level as a line and a label |
| `request.security(syminfo.tickerid, tf, close)`, lookahead off | `data: { htf: data.bars({ interval: tf }) }`, then `data.htf.last.close` (on history; live, Pine shows the forming higher bar, Taji the last closed); another symbol `data.bars({ symbol, interval })`; a `tf` from an `input.timeframe` is `data: ({ inputs }) => ({ htf: data.bars({ interval: inputs.tf }) })`. On an extended-hours chart a `D` or coarser read turns at the day's extended close (`references/indicators.md`). With `barmerge.gaps_on`, `data.htf.changed ? data.htf.last.close : NaN`; `close[1]` is `data.htf.at(1).close` with `depth: 2` |
| `request.security` with `lookahead_on`, and `expr[1]` on its result (`request.security(sym, tf, close[1], lookahead=barmerge.lookahead_on)`) | `data.bars({ interval, asof: "open" })`: the higher bar's last close before this bar's open, no future |
| `request.security` with `lookahead_on` and no `[1]` | not ported: it reads the future |
| `request.security_lower_tf(syminfo.tickerid, tf, expr)` | `data: { ltf: data.bars({ interval: tf }) }` with `tf` below the chart's, then `expr` over `data.ltf.intrabars` in `next` (the bars, oldest first, not one value per bar); history is capped at 200,000 intrabars as on TradingView's top plan |
| `request.dividends(syminfo.tickerid, dividends.gross)`, `request.splits(…, splits.numerator)`, `request.earnings(…, earnings.actual)` | `data: { ev: data.events("dividends") }` (`"splits"`, `"earnings"`), then `data.ev.last.amount` (`dividends.gross`), `.ratio_to` and `.ratio_from` (`splits.numerator`, `.denominator`; 4-for-1 is 4 and 1), `.eps_actual`, `.eps_estimate`; NaN before the first event, the value held until the next (`gaps_off`), `data.ev.changed ? data.ev.last.amount : NaN` for `gaps_on`. `dividends.net` and `earnings.standardized` have no field; an earnings report is served only once it is out (`references/indicators.md`) |
| `plot(x)`; `style=plot.style_<s>` | `plot.<kind>` (table in `references/indicators.md` § Plots and colour) and `x` in `next`'s return |
| `plot(x, color=cond ? a : b)` | a plot with `colors: [a, b]` and `colors: { name: slot }` in the return; on a line, each segment takes its end bar's colour |
| `plotchar(cond, char="▲", location=location.belowbar)` | `plot.char("▲", { at: "below" })`, returned as `bar.low` where `cond` holds and NaN elsewhere (`abovebar`: `at: "above"` and `bar.high`; `absolute`: `at: "value"` and the value) |
| `plotarrow(x)` | `plot.arrow()`, `x` in the return |
| `plotcandle(o, h, l, c)`, `plotbar(o, h, l, c)` | `plot.candle()`, `plot.bar()`, `{ open, high, low, close }` in the return |
| `bgcolor(cond ? a : na)` | `plot.bgcolor({ colors: [a] })`, a number where it shades and NaN elsewhere, slot 0 |
| `barcolor(cond ? a : na)` | `plot.barcolor({ colors: [a] })`, the same |
| `fill(p1, p2, color=cond ? a : b)`, `fill(h1, h2)` | `fills: { f: fill("p1", "p2", { colors: [a, b] }) }` and `colors: { f: slot }` in the return; an `hline` side is its level's value, a hidden helper plot of a constant is the constant; `color.new(c, t)` is `alpha: 1 - t / 100` |
| `plotshape(cond, style=shape.triangleup, location=location.belowbar)` | `plot.marker({ shape: "triangle-up", at: "below" })`, returned as a number where `cond` holds and NaN elsewhere |
| `hline(v)` | `plot.levels([v])` |
| `xloc.bar_index` (the default), `xloc.bar_time` | `ctx.index` for `bar_index`; `xloc: "bar_time"` with `bar.time` (seconds); a bar index may be negative or up to 500 bars ahead |
| `line.new(bar_index, y1, bar_index - n, y2, extend=extend.right, style=line.style_arrow_right)` | `line.new({ x1: ctx.index, y1, x2: ctx.index - n, y2, extend: "right", style: "arrow_right" })` |
| `line.set_xy1/xy2/x1/y2/color/width/style/extend`, `line.get_x1/y2/…`, `line.delete` | `set({…})` with the fields named, `get()?.x1`, `delete()` on the handle kept in state |
| `label.new(bar_index, high, "t", style=label.style_label_up, yloc=yloc.abovebar)`, `label.set_xy/text/…`, `label.get_text/…` | `label.new({ x: ctx.index, y: bar.high, text: "t", style: "label_up", yloc: "abovebar" })`, `set({…})`, `get()?.text`; a style is Pine's word without `style_`; `tooltip` is stored and served but not drawn (not built) |
| `box.new(l, t, r, b, extend=extend.right, bgcolor=c)`, `box.set_lefttop/rightbottom/…`, `box.get_top/…` | `box.new({ left, top, right, bottom, extend: "right", bg: c })`, `set({ left, top })`, `get()?.top` |
| `polyline.new(array.from(chart.point.from_index(i, y), …), curved, closed, line_color=c)` | `polyline.new({ points: [{ x: i, y }, …], curved, closed, line_color: c })`; `chart.point.from_time(t, y)` is `{ x: t / 1000, y }` under `"bar_time"`; `curved` draws a smooth curve through the points |
| `line.all`, `label.all`, `box.all`, `polyline.all` | the handles kept in state whose `get()` is not null: an evicted or deleted one's is null |
| `max_lines_count`, `max_labels_count`, `max_boxes_count`, `max_polylines_count` | `max_lines`, `max_labels`, `max_boxes`, `max_polylines` on the definition; a kind holds up to its cap plus 5, then deletes down to the cap (TradingView's lines and polylines; labels and boxes by analogy) |
| `table.new`, `table.cell`, `table.clear`, `table.delete` | `table.new`, `.cell`, `.clear()`, `.delete()` on the handle (positions in `references/indicators.md` § Drawings and tables); fill on `ctx.last`; `text_size` is `size` (`size.tiny` to `size.huge`; no `size.auto` or int size); `border_width` and `frame_width` are pixels, default 0, which draws none |
| `color.new(c, t)`, `color.rgb(r, g, b, t)`, `color.red` | `color.new`, `color.rgb`, each a `#rrggbb[aa]` word; a named colour is its hex (aqua `#00bcd4`, black `#363a45`, blue `#2196f3`, fuchsia `#e040fb`, gray `#787b86`, green `#4caf50`, lime `#00e676`, maroon `#880e4f`, navy `#311b92`, olive `#808000`, orange `#ff9800`, purple `#9c27b0`, red `#f23645`, silver `#b2b5be`, teal `#089981`, white `#ffffff`, yellow `#fdd835`) |
| `plot(x, color=color.from_gradient(v, lo, hi, a, b))`, any colour computed per bar | a plot with `colors: "computed"` and `colors: { name: color.from_gradient(v, lo, hi, a, b) }` in the return; a fill the same |
| `color.r(c)`, `color.g(c)`, `color.b(c)`, `color.t(c)` | `color.r`, `color.g`, `color.b`, `color.t`; `color(na)` is null and reads 0, 0, 0 and 100, as Pine's does; a flat range (`lo == hi`) is `#00000000`, reading the same, for every value |
| `a == b`, `a != b`, `a < b` on floats | `series.eq`, `series.ne`, `series.lt` (`gt ge le`): within 1e-10 is equal, NaN compares false |
| `x != na`, `x == na` | not compiled by Pine v6 ("Cannot compare a value to na directly"): use `na(x)`, here `series.na(x)` |
| `math.round(x, p)`, `str.tostring(x, fmt)`, `str.format(…)` | `series.round`, `series.tostring`, `series.format`. `format.mintick`, `format.percent`, `format.volume` are `"mintick"`, `"percent"`, `"volume"`; the tick is a third argument (default 0.01). `"#.##%"` multiplies by 100, `format.percent` does not; `""` groups thousands and keeps the shortest decimals (`1,234.5`), `"."` rounds to a whole number and keeps the point (`1235.`). `str.format`'s `{n,date,…}` and `{n,time,…}` are UTC, US English, over `time` in milliseconds (`bar.time * 1000`); `MMM EEE hh a D w` work and `{n,date}` is `Oct 23, 2026`, `{n,time}` `11:55:00 PM` |
| `nz(x, y)`, `na(x)`, `fixnan(x)` | `series.nz`, `series.na`, `series.fixnan(x, s.last)` with `s.last = series.fixnan(x, s.last)` kept in state; na is NaN, never `undefined` |
| `a % b` | `a - b * Math.floor(a / b)`: Pine's `%` floors the quotient (`-1 % 100` is 99), JavaScript's follows the dividend (`-1`); `int / int` is fractional in both |
| `math.abs/max/min/sqrt/log/…` | `Math.*` |
| `array.*`, `map.*` | plain arrays and objects in state |
| `bar_index` | `ctx.index` |
| `syminfo.tickerid`, `type`, `currency`, `mintick`, `pointvalue`, `timezone`, `session` | `ctx.syminfo.<same>`; `null` where Taji holds none (an equity's `type`, a future's `timezone`); `session` is the chart's session word, `"regular"` or `"extended"` unless the chart is on another |
| `time` (milliseconds) | `bar.time` (seconds): divide a ported constant by 1000 |
| `barstate.isfirst/isconfirmed/isrealtime/islast` | `ctx.first`, `ctx.closed`, `ctx.live`, `ctx.last` |
| `open high low close volume hl2 hlc3 ohlc4` | the same on `bar` (`hlcc4` through `input.source` only) |
| `alertcondition(cond)` | no equivalent in the script: bind it, then `watches/add` with `of` its plot (`SKILL.md` § Alerts) |

A `ta` handle takes every bar, never inside an `if`: a skipped bar skips its state. Pine's `na` source into `ta.sma/ema/rma` is skipped whole, as here.

## Not ported

Say so and stop; do not approximate.

- `enum` and `input.enum`, `type`, `method`, and importing a library: the module is one file and imports only `@taji/indicators`.
- `varip`, and any logic that depends on the same bar's earlier ticks: a tick restarts from the last close.
- `strategy.*`: a Pine strategy is not ported.
- `request.financial`, `request.economic`, `request.seed`.
- The rest of `syminfo.*` (`ticker`, `prefix`, `basecurrency`, the analyst and share fields).
- Heikin Ashi and other non-standard bars (`ticker.heikinashi`), and the rest of the "Not built" list in `references/indicators.md`.

## Worked port

```pine
//@version=6
indicator("MACD cross")
macd = ta.ema(close, 12) - ta.ema(close, 26)
signal = ta.ema(macd, 9)
plot(macd, "MACD"); plot(signal, "Signal")
plotshape(ta.crossover(macd, signal), style=shape.triangleup, location=location.belowbar)
plotshape(ta.crossunder(macd, signal), style=shape.triangledown, location=location.abovebar)
```

```ts
import { indicator, input, plot, ta } from "@taji/indicators";

export default indicator({
  name: "MACD cross", pane: "own",
  inputs: { fast: input.int(12, { min: 1 }), slow: input.int(26, { min: 1 }), smooth: input.int(9, { min: 1 }) },
  plots: {
    macd: plot.line({ title: "MACD" }),
    signal: plot.line({ title: "Signal" }),
    up: plot.marker({ shape: "triangle-up", at: "below" }),
    down: plot.marker({ shape: "triangle-down", at: "above" }),
  },
  setup: ({ inputs }) => ({
    fast: ta.ema(inputs.fast), slow: ta.ema(inputs.slow), smooth: ta.ema(inputs.smooth),
    up: ta.crossUp(), down: ta.crossDown(),
  }),
  next(bar, s) {
    const macd = s.fast.next(bar.close) - s.slow.next(bar.close);
    const signal = s.smooth.next(macd);
    return {
      macd, signal,
      up: s.up.next(macd, signal) ? macd : NaN,
      down: s.down.next(macd, signal) ? macd : NaN,
    };
  },
});
```

An input never shares a plot's name (`smooth`, not `signal`), and every handle is made in `setup`. Its test:

```ts
import type { T } from "@taji/indicators";

export default {
  "a step up crosses the signal on the step"(t: T) {
    const r = t.run({}, [...Array(40).fill(10), ...Array(20).fill(11)]);
    t.assert(r.up.slice(0, 40).every((v) => v !== v), "flat: no cross");
    t.assert(r.up[40] === r.up[40], "up on the step bar");
  },
};
```
