# Custom runtimes (/vela-pro/indicators/runtimes/engines)



If your platform has a proprietary scripting language or a remote calculation backend, you can run it on Vela Pro charts alongside Pine Script®. Register an implementation of the `ScriptingEngine` port from Vela's open-source core under a custom language key, and any script added with that `language` routes to your engine:

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

declare function createAcmeEngine(): ScriptingEngine; // See "Minimal implementation" below

enableVelaPro();
registerDefaultEngine('acme', () => createAcmeEngine()); // Instantiates one engine per chart

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

// Dispatched to your custom engine.
workspace.chart.addIndicator('momentum(close, 14)', { language: 'acme' });
// Omitting `language` uses the chart's default engine (Pine Script®).
workspace.chart.addIndicator('//@version=6\nindicator("EMA 20", overlay=true)\nplot(ta.ema(close, 20))');
```

Indicators produced by a custom engine share the exact same legend controls, settings dialog, and pane management as Pine Script® indicators.

## Engine responsibilities [#engine-responsibilities]

A `ScriptingEngine` translates source code and OHLCV bars into the core's visual output model (series, fills, price lines, and drawings) while the core manages market data, panes, and UI state.

| Engine responsibilities                                                    | Core responsibilities                                                                    |
| -------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- |
| Parse source code and extract title, overlay metadata, and input schema.   | Load historical and live OHLCV bars from the data provider and pass them to the engine.  |
| Compute indicator outputs across the supplied bars.                        | Serve secondary symbol or timeframe requests through `fetchSeries`.                      |
| Emit an `IndicatorModel` with deterministic IDs for each output primitive. | Route outputs to panes, mount initial primitives, and apply in-place patches on updates. |
| Surface compilation errors, runtime failures, warnings, and alert events.  | Render the legend row and settings dialog, and manage active input values.               |

Because an engine receives bars from the chart rather than fetching market data itself, every indicator on a chart evaluates over an identical bar history.

## Engine interface [#engine-interface]

| Member                        | Description                                                                                                                                                                                           |
| ----------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `language`                    | Unique language identifier handled by the engine (such as `'acme'`).                                                                                                                                  |
| `capabilities`                | Static feature flags (`streaming`, `visibleRange`, and `inputs`) that govern how the core drives execution.                                                                                           |
| `prepare(source, instanceId)` | Parses `source` without market data and resolves with metadata (`title`, `overlay`), `inputs` schema, and an opaque `token` passed back into `execute()`. Throw or reject on syntax errors.           |
| `execute(request, handlers)`  | Starts an execution session synchronously and delivers computed models asynchronously via `handlers.onModel(model)`. `request` includes the prepared script, bars, input values, and market metadata. |
| `ExecutionSession`            | Returned by `execute()` so the core can push updates via `update(inputs)`, `notifyBars(reason)`, `setVisibleRange(range)`, and `stop()`.                                                              |

`request.mode` is either `'static'` or `'live'`. The core selects `'live'` only when the chart is streaming live market data, the script does not depend on the visible range, and `capabilities.streaming` is `true`. Otherwise, the core notifies the session via `notifyBars()` on each bar update. Enable `streaming: true` only when your engine maintains incremental per-bar state across ticks.

Historical bars can arrive in progressive chunks. When `request.historyState === 'backfill'`, the initial bars represent a partial history, followed by a single `notifyBars('complete')` call once backfill finishes. Engines whose calculations depend on full bar history should wait for `'complete'` before emitting, as shown in the example below.

For full protocol details including incremental streaming, worker transports, and context snapshots, see [Adding a scripting engine](/vela/contributing/adding-an-engine) in the core documentation.

## Minimal implementation [#minimal-implementation]

The engine below compiles a script and plots a single line series. Because `prepare()` is async and `execute()` pushes models through `handlers.onModel()` whenever results are ready, both in-process interpreters and remote calculation services fit the same interface:

```ts
import { stableSeriesId, type ExecutionHandlers, type ExecutionRequest, type ExecutionSession, type IndicatorModel, type OHLCV, type PreparedScript, type ScriptingEngine } from '@luxalgo/vela/plugin';

interface AcmeProgram {
    title: string;
    evaluate(bars: readonly OHLCV[]): Array<number | null>;
}
declare function compile(source: string): AcmeProgram; // Throws on syntax errors

export class AcmeEngine implements ScriptingEngine {
    readonly language = 'acme';
    readonly capabilities = { streaming: false, visibleRange: false, inputs: false };

    async prepare(source: string, instanceId: string): Promise<PreparedScript> {
        const program = compile(source);
        return { language: this.language, inputs: [], meta: { title: program.title, overlay: false }, reactsToViewport: false, token: { instanceId, program } };
    }

    execute(request: ExecutionRequest, handlers: ExecutionHandlers): ExecutionSession {
        const { instanceId, program } = request.prepared.token as { instanceId: string; program: AcmeProgram };
        let complete = request.historyState !== 'backfill';
        let stopped = false;
        const run = (): void => {
            if (stopped || !complete) return;
            const bars = request.getBars?.() ?? request.bars;
            const values = program.evaluate(bars);
            const points = bars.map((bar, i) => ({ time: bar.time, value: values[i] ?? null }));
            const id = stableSeriesId({ instanceId, kind: 'line', title: 'Value', ordinal: 0 });
            const model: IndicatorModel = {
                id: instanceId, title: program.title, overlay: false, paneHint: 'new',
                series: [{ id, title: 'Value', paneId: '', kind: 'line', points, style: { color: '#f59e0b', width: 2, lineStyle: 'solid' } }],
                fills: [], backgrounds: [], priceLines: [], inputs: [], inputValues: {},
            };
            handlers.onModel(model);
            handlers.onDone?.();
        };
        run();
        return {
            stop: () => { stopped = true; },
            update: () => run(),
            setVisibleRange: () => {},
            notifyBars: (reason) => {
                if (reason === 'complete') complete = true;
                if (reason !== 'backfill') run();
            },
        };
    }
}
```

Three requirements in `execute()` are enforced by the core contract:

* `model.id` must equal the `instanceId` passed to `prepare()`.
* Every series ID must be generated deterministically with `stableSeriesId` using a zero-based `ordinal` on each run so subsequent runs patch existing plots in place rather than remounting them; see [Charting adapters](/vela-pro/indicators/runtimes/charting-adapters#stable-ids).
* Every `handlers.onModel(model)` call must emit the complete `IndicatorModel`, both on initial execution and on subsequent updates.

To support user-configurable inputs, return an `inputs` schema array from `prepare()`, set `capabilities.inputs` to `true`, and read active values from `request.inputs` and `session.update(inputs)`.

## Registering an engine [#registering-an-engine]

| Scope            | Registration API                                                                 | Behavior                                                                                                                       |
| ---------------- | -------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
| Global default   | `registerDefaultEngine('acme', () => new AcmeEngine())` (`@luxalgo/vela/plugin`) | Applies to every workspace constructed afterward, creating one engine instance per chart. Call before constructing workspaces. |
| Single workspace | Workspace option `engines: { acme: () => new AcmeEngine() }`                     | Applies to all charts in that workspace, overriding any global default registered for the same language key.                   |
| Single chart     | `workspace.chart.registerEngine('acme', new AcmeEngine())`                       | Registers an instance on that chart alone without affecting already running indicators.                                        |

Both `registerDefaultEngine` and the workspace `engines` option accept a factory function rather than a singleton instance so stateful or worker-backed engines allocate and dispose one instance per chart.

## Language resolution [#language-resolution]

When mounting a script indicator, the core resolves its engine language in order:

1. The explicit `language` specified on `addIndicator(source, { language })`, on a workspace manifest entry, or on a custom `sections` tab in the indicator menu.
2. The chart's `defaultLanguage` option.

`defaultLanguage` defaults to `'pine'` and does not change automatically when you register additional engines. Consequently, calls to `addIndicator(source)` that omit `language` continue routing to the Pine engine unless you pass `defaultLanguage: 'acme'` in the workspace options.

If no engine is registered for the resolved language key, `addIndicator()` does not throw synchronously; instead, it reports a missing-engine error through the handle's `error` event and the chart's `indicator:error` event.

## Running alongside Pine Script® [#running-alongside-pine-script]

Multiple engines coexist without conflict because each indicator tracks its own language key. The Vela Pro indicator menu, favorites store, and Pine code editor explicitly tag scripts they add with `'pine'`, so they continue working even if you change `defaultLanguage`.

To expose custom-language scripts in the UI alongside Pine Script® studies:

* Add a custom catalog tab to the indicator menu with `language: 'acme'`; see [Indicator menu](/vela-pro/indicators/library#custom-catalog-sections).
* Preload default scripts in the workspace `indicators` manifest with `language: 'acme'` on each entry.

If your application disables Pine Script® completely via `pineEngine: false`, also disable the Pine code editor and Vela Pro indicator menu (`codeEditor: false`, `indicatorLibrary: false`), since both features add `'pine'` scripts that require a registered Pine engine.

## Code editor and strategy tester [#code-editor-and-strategy-tester]

The built-in code editor is dedicated to Pine Script®. Its Run action always submits scripts under `'pine'`, legend rows display **Edit code** and the favorites star only for `'pine'` scripts, and `editor.bind(id)` returns `false` for indicators running on another engine. To provide an in-app code editor for a custom language, mount a custom side panel as described in [Custom panels and widgets](/vela-pro/modules/extending/custom-widgets).

By contrast, the strategy tester works with any `ScriptingEngine`. It listens to script execution updates across all engines and populates its report whenever an engine's `ExecutionSession` implements `getContext()` returning two fields:

* `strategy`: Summary metrics at the last evaluated bar (open position, equity, open and net profit, winning and losing trade counts). Returning `strategy` marks the indicator instance as a backtested strategy.
* `trades`: Completed round-trip trades with side, quantity, entry details, and exit details.

Risk-adjusted and benchmark metrics on `strategy` (`sharpe`, `sortino`, `buyHoldPnl`, `buyHoldPct`, and `outperformance`) are optional and display `-` in the report when omitted; see [Strategy tester](/vela-pro/indicators/backtesting/strategy-tester).

## Related [#related]

* [Charting adapters](/vela-pro/indicators/runtimes/charting-adapters)
* [Adding a scripting engine](/vela/contributing/adding-an-engine) in the core documentation
* [Pine Script® with PineTS](/vela-pro/indicators/pine/runtime)
