# Pine Script® with PineTS (/vela-pro/indicators/pine/runtime)



Vela Pro executes Pine Script® v5 and v6 source code directly without a pre-compilation step. Calling `enableVelaPro()` registers `@luxalgo/vela-pinets` (powered by the PineTS runtime) as the default scripting engine for every chart constructed afterward, so you can pass raw Pine Script® source strings straight to `chart.addIndicator()`:

```ts
import { VelaWorkspace } from '@luxalgo/vela/workspace';
import { BinanceProvider } from '@luxalgo/vela/providers/binance';
import { enableVelaPro, pineLibraryResolver } from '@luxalgo/vela-pro';

enableVelaPro({
    pineEngine: {
        defaultProps: { initial_capital: 50_000 },
        importResolver: pineLibraryResolver({ url: '/pine-libraries/{user}/{name}/{version}.pine' }),
    },
});

const workspace = new VelaWorkspace('#chart', {
    layout: false,
    symbol: 'BTCUSDT',
    timeframe: '60',
    live: true,
    providers: { binance: () => new BinanceProvider() },
});

const rsi = workspace.chart.addIndicator(`//@version=6
indicator("RSI")
length = input.int(14, "Length", minval=1)
plot(ta.rsi(close, length), "RSI", color=color.purple)
hline(70)
hline(30)`);

rsi.on('ready', () => console.log(rsi.inputs.map((input) => input.key)));
rsi.on('error', ({ error }) => console.error(error.message));
```

Every chart receives a dedicated engine instance. The engine never fetches market data directly; instead, the chart supplies the loaded OHLCV bars, and any `request.security()` calls for secondary symbols or timeframes route through the chart's registered data providers.

Scripts declared with `strategy()` run on the same engine and render simulated order fills as trade markers on the price pane; see [Strategies](/vela-pro/indicators/backtesting/strategies).

For details on PineTS execution semantics and supported built-ins, see the [PineTS documentation](/developers/pinets) and [language coverage](/developers/pinets/lang-coverage). For using `@luxalgo/vela-pinets` directly with Vela's open-source core, see [Scripting engines](/vela/user/scripting-engines).

## Options [#options]

Configure the engine via `enableVelaPro({ pineEngine: { ... } })`, or pass the same options to `enablePineEngine()` when enabling features individually. Passing `pineEngine: false` skips registering the default Pine engine.

| Option           | Default      | Description                                                                                                                           |
| ---------------- | ------------ | ------------------------------------------------------------------------------------------------------------------------------------- |
| `engine`         | `'worker'`   | Execution context (`'worker'` runs scripts in a Web Worker, while `'inprocess'` runs on the main thread).                             |
| `props`          | `'strategy'` | Controls which scripts expose a Properties tab in their settings dialog.                                                              |
| `defaultProps`   | `undefined`  | Fallback values for declaration properties that a script does not specify explicitly.                                                 |
| `importResolver` | `undefined`  | Resolver used to load Pine Script® libraries referenced by `import` statements.                                                       |
| `footprints`     | `undefined`  | Data callback supplying volume-at-price slices to `request.footprint()`; see [Footprint data in scripts](#footprint-data-in-scripts). |

### Execution mode [#execution-mode]

When `engine` is `'worker'`, script transpilation and bar-by-bar execution run off the main thread so compute-heavy scripts do not block chart rendering or UI interactions. Both `'worker'` and `'inprocess'` run identical runtime logic and produce identical outputs.

Because `PineWorkerEngine` spawns its worker from an inlined Blob URL, pages enforcing a Content-Security-Policy must permit `worker-src blob:`. If your policy cannot allow Blob workers, set `engine: 'inprocess'`.

### Properties tab [#properties-tab]

Declaration arguments passed to `indicator()` or `strategy()` (such as `initial_capital`, `commission_value`, and `precision`) can be edited by users in a Properties tab inside the indicator settings dialog. The `props` option controls when that tab is shown:

| Value        | Behavior                                                                                                    |
| ------------ | ----------------------------------------------------------------------------------------------------------- |
| `'strategy'` | Shows the Properties tab for `strategy()` scripts only; `indicator()` scripts show only their Inputs tab.   |
| `'all'`      | Shows the Properties tab for every script.                                                                  |
| `'none'`     | Hides the Properties tab for all scripts.                                                                   |
| `string[]`   | Shows the Properties tab for scripts exposing at least one listed property key, ordered to match the array. |

`props` affects only the settings dialog UI. Hidden declaration properties still retain the values declared in the script, and programmatic updates via `handle.setProps()` still take effect.

`defaultProps` provides fallback values underneath the script's own declaration arguments. For example, `{ initial_capital: 50_000 }` initializes strategies that omit `initial_capital` to 50,000 while preserving any `initial_capital` explicitly declared in a script.

### Library imports [#library-imports]

Scripts can import external Pine Script® libraries using `import user/library/version as alias`. The engine does not fetch libraries from an external network by default; instead, it delegates every `import` statement to your configured `importResolver`. Without an `importResolver`, any script containing an `import` fails during preparation.

`pineLibraryResolver({ url })` resolves libraries over HTTP from a URL template with three placeholders populated from the `import` path:

| Placeholder | Value for `import acme/Levels/2 as lv` |
| ----------- | -------------------------------------- |
| `{user}`    | `acme`                                 |
| `{name}`    | `Levels`                               |
| `{version}` | `2`                                    |

With `/pine-libraries/{user}/{name}/{version}.pine`, importing `acme/Levels/2` sends a `GET` request to `/pine-libraries/acme/Levels/2.pine`, expecting the library's Pine Script® source as plain text.

An HTTP **404** response indicates an unknown library and fails script preparation with an error naming the missing import. Any other non-2xx status or network failure surfaces as a library load error. Successfully loaded libraries are cached in memory for the lifetime of the resolver, whereas failed requests are retried the next time a script imports that library.

When a URL template is not sufficient, `url` also accepts a callback receiving `{ path, user, name, version }`. You can pass custom request headers (such as authorization tokens) via `headers` or supply a custom `fetch` implementation via `fetch`. Library resolution runs on the main thread during `prepare()` (even when `engine: 'worker'`) and resolves transitive imports recursively.

### Footprint data in scripts [#footprint-data-in-scripts]

`request.footprint()` reads per-bar volume-at-price levels that are not present in standard OHLCV candles. Pass a `FootprintSource` callback in `footprints` to supply order-flow slices from your data backend:

```ts
import { enableVelaPro } from '@luxalgo/vela-pro';
import type { FootprintSource } from '@luxalgo/vela-pinets';

interface AcmeFootprintBar {
    time: number;
    levels: Array<{ price: number; buy: number; sell: number }>;
}
declare function loadFootprints(symbol: string, timeframe: string, from?: number, to?: number): Promise<AcmeFootprintBar[]>;

const footprints: FootprintSource = async (symbol, timeframe, range) => {
    const bars = await loadFootprints(symbol, timeframe, range.from, range.to);
    return bars.map((bar) => ({
        openTime: bar.time, // Open time of the corresponding chart bar
        levels: bar.levels.map((level) => ({ price: level.price, buyVolume: level.buy, sellVolume: level.sell })),
    }));
};

enableVelaPro({ pineEngine: { footprints } });
```

The engine invokes `footprints` once across the loaded bar history, and again from the forming bar onward whenever chart bars update. Each level's `price` represents the lower edge of its price bucket at your feed's native tick resolution, and PineTS aggregates those buckets into the row size requested by the script. Any bar you omit from the returned array evaluates to `na` in the script. When `footprints` is unset, `false`, or returns no data for the symbol, `request.footprint()` returns `na`.

## Adding scripts from code [#adding-scripts-from-code]

`chart.addIndicator(source, options?)` returns an `IndicatorHandle` synchronously and runs preparation and calculation asynchronously. Common options include:

| Option   | Description                                                                                                                            |
| -------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| `inputs` | Initial input overrides keyed by input variable key or title.                                                                          |
| `props`  | Initial declaration property overrides, such as `{ initial_capital: 25_000 }`.                                                         |
| `id`     | Explicit instance ID on the chart, allowing later lookup without storing the handle. Throws if the ID is already in use on that chart. |
| `pane`   | `'price'` or `'new'`, overriding the script's declared overlay placement.                                                              |
| `title`  | Custom display title overriding the script's declared title.                                                                           |

Once mounted, the returned `IndicatorHandle` controls the running instance via `setInput(key, value)`, `setProps(values)`, `setVisible(visible)`, `moveTo(target)`, `updateCode(source)`, and `remove()`. See the core [API reference](/vela/user/api-reference#indicatorhandle) for the complete method signatures.

<Note>
  Scripts added imperatively with `chart.addIndicator()` are not saved in the workspace state document. Re-add them during initialization on reload, or declare them in the workspace `indicators` manifest instead. See [Indicator persistence](/vela-pro/persistence/stores/indicators) for details on persistence behavior by indicator source.
</Note>

## Indicator manifest [#indicator-manifest]

The `indicators` option on `VelaWorkspace` accepts an array of manifest entries (or a URL returning that JSON array). Entries are added automatically to every new chart unless configured with `enabled: false`:

```ts
import { VelaWorkspace } from '@luxalgo/vela/workspace';
import { BinanceProvider } from '@luxalgo/vela/providers/binance';
import { enableVelaPro } from '@luxalgo/vela-pro';

enableVelaPro();

const workspace = new VelaWorkspace('#chart', {
    layout: false,
    symbol: 'BTCUSDT',
    providers: { binance: () => new BinanceProvider() },
    indicators: [
        { name: 'EMA 20', script: '//@version=6\nindicator("EMA 20", overlay=true)\nplot(ta.ema(close, 20))' },
        { name: 'House trend', url: '/scripts/house-trend.pine' },
    ],
});
```

If an individual entry fails to fetch or compile, Vela logs a console warning and skips that entry without blocking chart initialization. See [Custom indicators](/vela-pro/indicators/custom-indicators#indicator-manifest) for the full manifest schema.

## Error handling [#error-handling]

Scripts can fail either at compile time (`prepare`) or at run time (`execute`). Error delivery depends on which method started or updated the script:

| Method                       | Behavior on failure                                                                                                                                                                                                                 |
| ---------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `chart.addIndicator(source)` | Emits `error` on the `IndicatorHandle` and `indicator:error` (with the indicator `id`) on the chart. Does not auto-remove the indicator, keeping its legend row visible if execution had already started so the user can remove it. |
| `chart.runIndicator(source)` | Resolves to `{ ok: false, error }` without rejecting, and automatically removes the failed instance so no broken legend row remains on the chart.                                                                                   |
| `handle.updateCode(source)`  | Resolves to `{ ok: false, error }` without rejecting, rolling back so the previous working script continues running.                                                                                                                |

Prefer `chart.runIndicator(source)` when executing untrusted or user-edited scripts (this is the method used internally by the Pine code editor):

```ts
import type { Vela } from '@luxalgo/vela';

export async function runUserScript(chart: Vela, source: string): Promise<string | null> {
    const result = await chart.runIndicator(source);
    if (!result.ok) return result.error?.message ?? 'The script failed to run.';
    // Subsequent re-runs (for example after an input change) report runtime errors on the handle.
    result.handle?.on('error', ({ error }) => console.warn(error.message));
    return null;
}
```

## Related [#related]

* [Pine code editor](/vela-pro/indicators/pine/code-editor)
* [Custom indicators](/vela-pro/indicators/custom-indicators)
* [Using PineTS within charts](/developers/pinets/using-within-charts)
