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

# Build a feature plugin

You turn the scaffold `taji plugin new --feature` writes into a plugin that serves a product of its own from Taji's option chains, draws it as a chart layer, reads it in a script and passes `taji plugin check` with no `FAIL`. You need Rust 1.100 (`taji-sdk`'s minimum) and `taji` on your `PATH`: from a checkout, after `pnpm --filter @taji/ui build` (the kernel embeds the page), `cargo install --locked --path engine/crates/taji-open` installs its `taji` binary into `~/.cargo/bin`. The `draw` step also needs `bun` and Chrome, inside a Taji checkout; step 9 also needs `jq` and the checkout's `.python`. Every file below is what the scaffold writes, with `toy` as the id, and `docs/plugins/examples/feature/toy` is that scaffold built, checked and run: the page's fences are its files.

A feature plugin is a process plugin that computes a product from data Taji already holds; [the plugins overview](https://docs.taji.is/plugins.md#which-kind-do-i-need) says when you want one.

## 1. Scaffold and build

```sh
taji plugin new toy --feature
cd toy
cargo build
```

`new` makes `toy` here (`--dir <d>` makes `<d>/toy`), refuses an existing one and writes `rust-toolchain.toml`, pinning Taji's Rust. An id is a lowercase letter, then up to 63 lowercase letters, digits or hyphens. `cargo build` makes `target/debug/toy`.

`taji-sdk` comes from crates.io; commit the `Cargo.lock` the build writes. `check` does not build: build first and after each change to `src/` or `taji-plugin.toml`, which the binary holds. With `CARGO_TARGET_DIR` set, `check` looks there for the binary.

## 2. Set the product in the manifest

`taji-plugin.toml` is the one contract: the SDK refuses to start when what `src/main.rs` registers differs from it, and `check` reads it first. The scaffold's:

<!-- scaffold: taji-plugin.toml.tmpl -->
```toml file="examples/feature/toy/taji-plugin.toml" title="taji-plugin.toml"
id = "toy"
name = "toy"
version = "0.1.0"
taji = ">=0.7, <0.8"
skill = ["SKILL.md"]

[process]
run = ["toy"]

[grants]
reads = ["chains"]

[[sources]]
id = "toy"
reads = [
  { class = "index", product = "toy.levels", span = "live", delay_s = 0 },
  { class = "equity", product = "toy.levels", span = "live", delay_s = 0 },
]

[[products]]
name = "levels"
description = "Call and put open-interest peak strikes and put/call OI ratio from option chains."
shape = "values"
store = true
model = "From each chain snapshot's contracts with open interest at least min_oi: call_peak and put_peak are the strikes holding the most call and put open interest; put_call is total put open interest divided by total call open interest."
words = [
  { name = "min_oi", type = "int", default = 0, min = 0, doc = "Minimum contract open interest to include." },
]
columns = [
  { name = "ts_utc", type = "int" },
  { name = "spot", type = "decimal", unit = "price" },
  { name = "call_peak", type = "decimal", unit = "price", nullable = true, doc = "Strike holding the most call open interest." },
  { name = "put_peak", type = "decimal", unit = "price", nullable = true, doc = "Strike holding the most put open interest." },
  { name = "put_call", type = "float", unit = "ratio", nullable = true, doc = "Total put open interest divided by total call open interest." },
]

[[ui.layers]]
id = "toy.peaks"
label = "OI peaks"
product = "toy.levels"
renderer = "taji.levels"
slot = "above"
style = [
  { name = "columns", type = "string", default = "call_peak,put_peak", doc = "Which price columns draw, comma-separated." },
  { name = "emphasis", type = "string", default = "call_peak", doc = "The column drawn solid in the accent." },
]

[[kernel.indicators]]
name = "toy_ratio"
source = "indicators/toy_ratio.ts"
test = "indicators/toy_ratio.test.ts"
```

| Table | What it says |
|---|---|
| `[process] run` | the binary; `taji = ">=0.7, <0.8"` is the contract versions the plugin speaks |
| `[grants] reads` | the hub products the plugin may `get` and `stream`; anything else is refused `403 not_granted` |
| `[[sources]] reads` | what the hub may ask of it, a row per class, product and span; the scaffold serves `live` only, so a read answers from pushed rows |
| `[[products]]` | the product `toy.levels`: `shape = "values"` makes a row one instant, `ts_utc` first; `store = true` has the kernel record each row; `words` are its query words, typed with defaults; `columns` are `nullable` where a row may hold none |
| `[[ui.layers]]` | draws the product on the chart: [Draw a chart layer](https://docs.taji.is/plugins/layer.md) |
| `[[kernel.indicators]]` | adds a script to the catalog, with its test |

A figure the plugin estimates declares a `model`, which a read serves as `computed_by` and `estimated`. Every field is in [the manifest reference](https://docs.taji.is/plugins/manifest.md).

## 3. Compute the row

`build.rs` runs `taji_sdk::build::products()`, which reads the manifest; `taji_sdk::products!()` then declares `Levels` and `LevelsWords` from it. The scaffold's `src/main.rs`:

<!-- scaffold: main.rs.tmpl -->
```rust file="examples/feature/toy/src/main.rs" title="src/main.rs"
use std::collections::BTreeMap;
use std::time::Duration;

use taji_sdk::hub::{Batch, Chains};
use taji_sdk::{Decimal, serve};

taji_sdk::products!();

fn main() {
    serve(include_str!("../taji-plugin.toml"), |p| {
        p.product::<Levels>().live(|cx, sub| {
            for batch in cx.stream(Chains::of(sub.item()).every(Duration::from_secs(60)))? {
                if let Some(level) = row(sub.words(), &batch)
                    && sub.push(level).is_err()
                {
                    break;
                }
            }
            Ok(())
        });
    });
}

fn row(words: &LevelsWords, batch: &Batch<Chains>) -> Option<Levels> {
    let spot = batch.rows.iter().find_map(|c| c.spot).or(batch.spot)?;
    let min_oi = Decimal::from(words.min_oi);
    let (mut calls, mut puts) = (BTreeMap::new(), BTreeMap::new());
    for c in &batch.rows {
        let Some(oi) = c
            .open_interest
            .filter(|&oi| oi > Decimal::ZERO && oi >= min_oi)
        else {
            continue;
        };
        match c.right.to_ascii_lowercase().as_str() {
            "call" => *calls.entry(c.strike).or_default() += oi,
            "put" => *puts.entry(c.strike).or_default() += oi,
            _ => {}
        }
    }
    let peak = |side: &BTreeMap<Decimal, Decimal>| {
        side.iter()
            .max_by_key(|&(_, oi)| oi)
            .map(|(&strike, _)| strike)
    };
    let call_oi: Decimal = calls.values().copied().sum();
    let put_oi: Decimal = puts.values().copied().sum();
    let put_call = (call_oi > Decimal::ZERO)
        .then(|| f64::try_from(put_oi).ok().zip(f64::try_from(call_oi).ok()))
        .flatten()
        .map(|(p, c)| p / c);
    Some(Levels {
        ts_utc: batch.knowable_utc,
        spot,
        call_peak: peak(&calls),
        put_peak: peak(&puts),
        put_call,
    })
}
```

`live` runs once a subscription. `Chains::of(sub.item()).every(Duration::from_secs(60))` is the hub's `chains` for the item, its newest snapshot at most once a minute; `cx.stream` yields each as a `Batch`. A failed push means the subscriber left, so the loop ends; returning `Ok(())` ends the subscription.

To follow a book instead, stream `Depth::of(sub.item()).every(Duration::from_millis(250)).ticks(5)`: a `Batch` is one `symbol`'s book at `knowable_ms`, its `DepthLevel` rows carrying `peak` and `step`. A batch with `shut: Some(reason)` and no rows says that book lapsed and the feed goes on: push nothing and call `sub.shut(reason)`; the next `sub.push` resumes. `Trades::of(sub.item())` takes no `every`: a lossless product sends every row, and rows the feed dropped are counted on the next batch's `gap`. On an equity it reads the whole tape (`24h`) unless the query names a `session` (`.word("session", "regular")`).

`row` holds what `check` tests: no clock, no randomness, nothing kept between calls. A row is one instant, `ts_utc`, the batch's `knowable_utc`. A `cells` row is stamped at the start of the interval it measures and pushed when the interval closes; `check` stamps it knowable at the newest batch handed before the push, as the `prefix` step holds. The SDK has no calendar: for a New York day or session use `jiff` with its bundled time zones, as GEX's `ny_date` does.

The SDK's row types and fields are in `taji_sdk::hub` (`Trade`, `DepthLevel`, `Chain`, `Bar`, `Quote`, `Batch`, `Query`): `cargo doc -p taji-sdk --open` in the plugin lists them. A product named like a hub product (`depth`, `trades`) generates a type of the hub's name: import the hub's under another, `use taji_sdk::hub::{Depth as Books}`.

## 4. Plot it in a script

`indicators/toy_ratio.ts` plots `put_call` from `data.product("toy.levels", ...)`, with `toy_ratio.test.ts` its test. [Indicators](https://docs.taji.is/indicators.md) teaches the language.

<!-- scaffold: ratio.ts.tmpl -->
```ts file="examples/feature/toy/indicators/toy_ratio.ts" title="indicators/toy_ratio.ts"
import { data, indicator, input, plot } from "@taji/indicators";

export default indicator({
  name: "toy put/call",
  pane: "own",
  inputs: {
    min_oi: input.int(0, { min: 0 }),
  },
  data: ({ inputs }) => ({
    levels: data.product("toy.levels", { min_oi: inputs.min_oi }),
  }),
  plots: {
    put_call: plot.line({ title: "Put/call", unit: "ratio" }),
    even: plot.levels([1]),
  },
  setup: () => ({}),
  next(_bar, _s, { data: feed }) {
    return { put_call: feed.levels.last.put_call };
  },
});
```

<!-- scaffold: ratio.test.ts.tmpl -->
```ts file="examples/feature/toy/indicators/toy_ratio.test.ts" title="indicators/toy_ratio.test.ts"
// The test fixture holds no product rows, so these check the no-row end of the script.
import type { T } from "@taji/indicators";

export default {
  "put_call is NaN on every bar while no row is knowable"(t: T) {
    const r = t.run();
    t.assert(r.put_call.length === r.time.length && r.put_call.length > 0, "one row per bar");
    t.assert(r.put_call.every((x: number) => Number.isNaN(x)), "no put_call before a row");
  },
  "min_oi word is accepted"(t: T) {
    const r = t.run({ min_oi: 100 });
    t.assert(r.put_call.length === r.time.length, "one row per bar");
  },
};
```

`indicators/products.d.ts` types the product's columns for the script; `check` fails when it differs from the manifest's `[[products]]`, and `check . --bless` rewrites it.

`SKILL.md` is what an agent reads: how to read the product and set an alert on it.

<!-- scaffold: SKILL.md.tmpl -->
```md file="examples/feature/toy/SKILL.md" title="SKILL.md"
---
name: toy
description: "Option open-interest peaks and put/call ratio from recorded chain snapshots, and alerts when put/call crosses 1."
---

## toy

Option open-interest peaks and put/call ratio: `read get/toy.levels?symbols=index:$SPX&min_oi=0` gives `spot`, `call_peak`, `put_peak` and `put_call` from recorded snapshots. Word: `min_oi` (minimum contract open interest, default 0).

Alert when put/call crosses 1: `commit {route: "verb/desk/<id>/watches/add", body: {symbol: "index:$SPX", when: "crosses", of: {indicator: {name: "toy_ratio", params: {min_oi: 0}, plot: "put_call"}}, price: 1}}`.
```

A script is optional: without one `scripts` skips.

## 5. Write the fixture

`fixtures/<product>.jsonl` is the only data `check` serves; the scaffold writes `chains.jsonl`. A plugin serving other products rewrites or deletes everything the scaffold wrote for `toy.levels`: `fixtures/chains.jsonl`, `indicators/` (the script, its test, `products.d.ts`) and its `[[kernel.indicators]]` row, `SKILL.md`, and the product lines of `AGENTS.md` and `README.md`. A fixture for a product `[grants] reads` omits fails `rows`: delete the scaffold's when you read other products.

A feature plugin declares no `about`, the line atop a vendor's Connections page: its `README.md`'s first paragraph says what it is. The README's H1 is the manifest's `name`, then a line saying what the plugin is and `## Use`. `AGENTS.md` is the page your own agent reads: the files, `cargo build`, `taji plugin check .`, the rules above, and `taji plugin dev . --headless` with how to read its output.

Each fixture line is one JSON object of the fields below, and any other field is refused:

| Line | Holds |
|---|---|
| 1 | `{"item": "<class>:<symbol>"}` |
| a batch | `knowable_utc` (seconds, never descending; batches may share an instant, as live ones do) and `rows` (the product's rows as `live` receives them); optional `spot` (a decimal string) |
| `scope` | on a `depth` batch: `{"levels", "venues"}`, as `GET /get/depth` states it |
| `shut` | on a batch with `"rows": []`: a reason the book lapsed, framed as a live shut is |
| `{"lost": n}` | `trades` only: the feed dropped `n` rows before the next batch, which carries a `gap`; `plugin dev` does not play it |

`knowable_ms` is not a field: `check` hands the plugin `knowable_utc` times 1,000. A `depth` row holds `symbol`, `ts_event`, `ts_init`, `level` and optional `side`, `price`, `size`, `count`, `peak`, `step`; a `trades` row `symbol`, `ts_init`, `price`, `conditions` (`[]` for none) and optional `ts_event`, `size`, `exchange`, `delayed`, `aggressor` (`"buy"` or `"sell"`) and `off_exchange`. `side` (1, −1 or null) and `side_by` (`stated`, `quote` or `tick`) are the kernel's; `plugin dev` drops them and classes the rows as the kernel does live. The scaffold's four batches are a minute apart.

Stamps have units: `ts_event` and `ts_init` are epoch nanoseconds, a hub `Timestamp` column (`Bar.start_dt`, `Quote.ts`, `Chain.snapshot_dt`) epoch microseconds, `knowable_ms` and `ts_ms` epoch milliseconds, `knowable_utc` and `ts_utc` seconds.

Draw a fixture's sizes from the spread real ones have, a log-normal about a decade wide, not a narrow uniform band: a heatmap colours by percentiles of the sizes in view, so a book of uniform 20 to 90 lots beside a few walls draws in two colours whatever the ramp, and its golden proves nothing about the ramp.

A Rust test of your own reads the same files: [`plugins/taji-orderflow/tests/flow.rs`](https://github.com/TajiAI/Taji/blob/main/plugins/taji-orderflow/tests/flow.rs)'s `fixture::<P>(name)` parses `fixtures/<name>.jsonl` from `CARGO_MANIFEST_DIR` into `Batch<P>`s, folding each `lost` line into the next batch's `gap`.

## 6. Check

```sh
taji plugin check .
```

`check` prints one line a step: `PASS <step>`, `FAIL <step>: <why> — <fix>` or `SKIP <step>: <why>`, then `not proven:` and the skipped steps. The exit code is the `FAIL` count. No kernel, key or network runs: the fixture is every answer.

| Step | Passes when |
|---|---|
| `manifest` | `taji-plugin.toml` parses, validates and has `[process]` |
| `shader` | each layer's `shader` compiles; skips where none is declared |
| `hello` | the process starts and says `taji-plugin/1` |
| `rows` | `live` plays the fixture and every row pushed fits its columns by name, type and `nullable` |
| `determinism` | a second run pushes the same rows |
| `prefix` | a run on each fixture's first half pushes the full run's first rows in order |
| `read` | a product with a `history` source, read twice over the span it pushed, answers the same both times and equals the rows the kernel keeps; skips here, [GEX](https://docs.taji.is/catalog/taji-gex.md) has a `history` |
| `scripts` | each script compiles, passes its test and its invariants, and draws something different with your rows than without |
| `draw` | each layer renders alone in headless Chrome and matches `golden/<layer>.png` |
| `budget` | a layer with a `shader` is redrawn 100 times in a 2560×1440 page at scale 2, the largest chart the window draws, and its median GPU time a frame stays under the window's 2 ms; a heatmap, bubbles or footprint layer prints `pan p95`, unjudged |

`prefix` cuts each fixture at its first half's end, takes the earliest such instant, and holds the run to the full run's rows through at least the last one knowable by then, stamped as the kernel stamps a pushed row: the later of its instant and the newest batch handed to the plugin before it.

`draw` builds 1-minute candles from the first fixture's batches, so they need a `spot`; a heatmap must change 2% of the plot, bubbles must draw a circle, and a footprint must change 2% of the plot and draw a number. It runs where a Taji source tree is above the plugin or your working directory, and skips elsewhere. [Draw a chart layer](https://docs.taji.is/plugins/layer.md) covers `shader` and `budget`.

A new layer has no golden, so its first `check` FAILs `draw` until the next step.

## 7. Bless the golden

```sh
taji plugin check . --bless
```

`golden/<layer>.png` is written for each layer, and `indicators/products.d.ts` is rewritten. Open each golden, look, then commit it. A later `draw` `FAIL` after an intended layer change is answered the same way; an unintended one is a bug to fix. Never edit a golden by hand.

Run `taji plugin check .` once more: it ends with no `FAIL`, and the exit code is 0.

## 8. Run it on a kernel

```sh
taji plugin dev . --headless &
```

A throwaway kernel under `target/dev/` plays `fixtures/` live, every other data source off, with the layers and scripts bound to one chart. Wait for `target/dev/dev.json` and read its `error` first; its `log` is `target/dev/state/taji.log`. `target/dev/rows.json` holds `{"toy.levels": [rows]}` as `check` writes them, now `recorded: true`, refreshed every 5 s; a refused product reads `{"refused": "<status> <error>: <reason>"}`. Fixtures loop on the wall clock, so a row can take one `period` (`dev.json`). After a change, stop it with Ctrl-C, build and rerun.

| Fixture | Plays live as |
|---|---|
| `chains.jsonl` | the same chains, expiries re-dated to today |
| `trades.jsonl`, `depth.jsonl` | the rows, with no `scope` and no `lost` |
| any other | not played |

One item serves every product. An `index` or `equity` plays live trades and candles in its session only: a fixture that must play at any hour names a future or a coin (`crypto:`).

## 9. Read the product

With the kernel from step 8 running, ask the wire for `toy.levels` like any product. The answer is Arrow IPC, so decode it with `pyarrow` (a Taji checkout's `make setup` lays one at `.python`); `dev.json` names the URL and the token file:

```sh
URL=$(jq -r .url target/dev/dev.json)
TOKEN=$(cat "$(jq -r .token_file target/dev/dev.json)")
curl -sf -H "x-taji-token: $TOKEN" "$URL/get/toy.levels?symbols=index:\$TOY" \
  | .python/python -c "import sys, pyarrow as pa; t = pa.ipc.open_stream(sys.stdin.buffer).read_all(); print(t.schema.metadata, t.to_pylist())"
```

You see the newest row, with the schema's metadata beside it:

```json file="examples/feature/levels.json" title="levels.json"
{
  "metadata": {
    "computed_by": "{\"plugin\":\"toy\",\"version\":\"0.1.0\"}",
    "model": "From each chain snapshot's contracts with open interest at least min_oi: call_peak and put_peak are the strikes holding the most call and put open interest; put_call is total put open interest divided by total call open interest.",
    "provider": "{\"index:$TOY\":\"toy\"}",
    "source": "{\"index:$TOY\":\"vendor\"}"
  },
  "rows": [
    {
      "ts_utc": 1796333048,
      "spot": 100,
      "call_peak": 102,
      "put_peak": 95,
      "put_call": 0.5,
      "knowable_utc": 1796333048,
      "recorded": true,
      "version": "0.1.0"
    }
  ]
}
```

*Captured 2026-12-03 on `taji plugin dev` with `toy` playing its scaffolded fixture, on a keyless headless kernel.*

- `spot`, `call_peak`, `put_peak` and `put_call` are `row`'s answer for the fixture batch playing at the read, with `min_oi` at its default of 0; the batches differ in these, so another read can show another row.
- `ts_utc` and `knowable_utc` are the second `plugin dev` played the batch, not the fixture's own: it loops the fixture on the wall clock.
- `recorded` is true because `store = true` has the kernel keep each row; `version` is the plugin's.
- `computed_by` and `model` come from the manifest, and `provider` maps the item to `toy`.

Stop the kernel with Ctrl-C.

## If it fails

- **`FAIL hello`:** `[process] run` names no built binary, because `check` builds nothing. Run `cargo build`.
- **`FAIL rows` naming a product, row and column:** a pushed row does not fit the manifest's column. It also fires on an ask refused `403 not_granted` (the product is not in `[grants] reads`), a `live` that ends refused, and a shaped product that pushes no row.
- **`FAIL determinism`:** a clock, randomness or state kept across runs. Compute each row from its batch alone.
- **`FAIL prefix`:** a row depends on a later batch. A `SKIP prefix` means nothing was compared: widen the fixture.
- **`FAIL scripts`:** the script does not compile, fails its test or an invariant, or draws the same with your rows as without. When `products.d.ts` differs from the manifest, run `check . --bless`.
- **`FAIL draw` on a new layer:** it has no golden: bless it (step 7).
- **A row refused from a source you did not expect, under `plugin dev`:** read `target/dev/state/plugins/<id>/log`, then `target/dev/state/taji.log`. A plugin that failed to start makes the hub fall through to another source.

## Next

- [Draw a chart layer](https://docs.taji.is/plugins/layer.md): the stock renderers, shaders and custom builders.
- [GEX](https://docs.taji.is/catalog/taji-gex.md) is this plugin grown: its `src/main.rs` registers four products from one function, each with a `history`, so `check` runs `read`; its manifest adds `profile` products and scripts that draw a card.
- [The manifest reference](https://docs.taji.is/plugins/manifest.md) and [the process protocol](https://docs.taji.is/plugins/protocol.md).
- [Pack and install a plugin](https://docs.taji.is/plugins/publish.md).
