# Indicator templates (/vela-pro/persistence/stores/indicator-templates)



An indicator template saves a chart's active indicators and their parameter values under a user-chosen name, optionally including the chart's symbol and timeframe. Users can apply saved templates to any chart in a single click. Because templates are user-scoped rather than tied to an individual layout, they persist in a dedicated store backed by `localStorage` by default or by your backend via a custom storage adapter.

```ts
import { enableVelaPro, type IndicatorTemplate, type IndicatorTemplatesStorage } from '@luxalgo/vela-pro';

const base = '/api/users/me/indicator-templates';

const storage: IndicatorTemplatesStorage = {
    async list() {
        const res = await fetch(base);
        if (!res.ok) throw new Error(`Templates could not be read (${res.status})`);
        return (await res.json()) as IndicatorTemplate[];
    },
    async save(template) {
        const res = await fetch(`${base}/${encodeURIComponent(template.id)}`, {
            method: 'PUT',
            headers: { 'content-type': 'application/json' },
            body: JSON.stringify(template),
        });
        if (!res.ok) throw new Error(`Template could not be saved (${res.status})`);
    },
    async remove(id) {
        await fetch(`${base}/${encodeURIComponent(id)}`, { method: 'DELETE' });
    },
};

enableVelaPro({ indicatorTemplates: { storage } });
```

## User interface [#user-interface]

Calling `enableVelaPro()` adds an **Indicator templates** button to the topbar beside the indicator menu. On mobile viewports, the entry appears inside the three-dots overflow menu.

* **Templates dropdown**: Displays the most recently updated templates along with summary metadata (such as `BTC-USD · 1h · 3 indicators`), followed by &#x2A;*Save indicators as a template…** and &#x2A;*Manage templates…** actions. Clicking a template applies it immediately.
* **Save dialog**: Prompts for a template name and provides optional **Symbol** and **Timeframe** switches. When enabled, those switches record the chart's active symbol or timeframe and apply them alongside the indicators. Entering an existing template name prompts for confirmation before overwriting it.
* **Manage dialog**: Lists all saved templates with actions to apply, rename, delete, or expand a row to inspect its constituent indicators.
* **Multi-chart layouts**: Applying a template in a multi-chart workspace asks whether to target the active chart or all charts. Selecting all charts applies the indicators across every chart while applying any saved symbol and timeframe exclusively to the active chart.

Applying a template **replaces** the target chart's existing indicators rather than appending to them.

## Options [#options]

Pass options under `indicatorTemplates` in `enableVelaPro()`, or directly to `enableIndicatorTemplates()` when enabling features individually. Pass `indicatorTemplates: false` to disable the feature.

| Option      | Default                                       | Description                                                                                 |
| ----------- | --------------------------------------------- | ------------------------------------------------------------------------------------------- |
| `storage`   | `localStorage` (`velapro.indicatorTemplates`) | Custom `IndicatorTemplatesStorage` implementation used to load, save, and delete templates. |
| `canCreate` | `() => true`                                  | Guard invoked before opening the save dialog. Return `false` to prevent opening the dialog. |
| `recent`    | `5`                                           | Maximum number of recent templates displayed directly in the topbar dropdown.               |

## Custom storage adapter [#custom-storage-adapter]

```typescript
interface IndicatorTemplatesStorage {
    list(): IndicatorTemplate[] | Promise<IndicatorTemplate[]>;
    /** Create a new template, or overwrite an existing template with the same id. */
    save(template: IndicatorTemplate): void | Promise<void>;
    remove(id: string): void | Promise<void>;
}
```

* `list()` runs once when Vela Pro is enabled, caching the returned templates in memory ordered newest first. Vela Pro does not validate the returned array, so return stored `IndicatorTemplate` objects unchanged. If `list()` throws or rejects, the error is logged and the list initializes empty.
* `save(template)` runs when creating, overwriting, or renaming a template. The save dialog awaits `save()` and displays an inline error while remaining open if the returned promise rejects, so throw on failed HTTP responses.
* `remove(id)` runs when the user deletes a template.

Templates created in another browser tab or on another device are not polled automatically. Call `indicatorTemplatesController()?.reload()` to re-fetch the list from `storage`.

## Restricting template creation [#restricting-template-creation]

Use `canCreate` to enforce plan-based template limits. Vela Pro calls `canCreate()` whenever the user clicks &#x2A;*Save indicators as a template…**, before opening the dialog. Returning `false` cancels opening the dialog without displaying built-in UI, allowing you to show your application's upgrade prompt.

```ts
import { enableVelaPro, indicatorTemplatesController } from '@luxalgo/vela-pro';

declare function showUpgradeDialog(reason: string): void; // application upgrade UI

const MAX_TEMPLATES = 10;

enableVelaPro({
    indicatorTemplates: {
        canCreate: () => {
            const count = indicatorTemplatesController()?.list().length ?? 0;
            if (count < MAX_TEMPLATES) return true;
            showUpgradeDialog(`Your plan includes ${MAX_TEMPLATES} templates.`);
            return false;
        },
    },
});
```

Because `canCreate` gates opening the save dialog, reaching the cap also blocks overwriting an existing template through the UI. Programmatic calls to `controller.save()` bypass `canCreate`, so enforce quota limits on your backend as well.

## Controller API [#controller-api]

`indicatorTemplatesController()` returns the page-level controller instance (or `null` before indicator templates are enabled). All workspaces on the page share this controller.

| Member               | Description                                                                               |
| -------------------- | ----------------------------------------------------------------------------------------- |
| `ready`              | Promise that resolves once the initial `storage.list()` call finishes.                    |
| `list()`             | Returns the cached `IndicatorTemplate[]` array synchronously, ordered newest first.       |
| `onChange(listener)` | Subscribes to template additions, updates, and removals. Returns an unsubscribe function. |
| `reload()`           | Re-reads templates from `storage.list()`.                                                 |
| `save(template)`     | Creates a template or overwrites an existing template with the same `id`.                 |
| `rename(id, name)`   | Updates a template's `name` and persists the change. Empty names are ignored.             |
| `remove(id)`         | Deletes the template with the given `id`.                                                 |
| `canCreate`          | Reference to the configured `canCreate` guard function.                                   |

## Programmatic capture and application [#programmatic-capture-and-application]

Use `captureIndicators(chart)` to snapshot a chart's active indicators as `TemplateIndicator[]` entries, and `applyTemplate(target, template)` to apply an `IndicatorTemplate` to a target:

* `shellTarget(ctx)` targets the workspace's active chart, applies any saved `symbol` and `timeframe`, and routes indicator changes through the workspace so the user can undo the operation.
* `chartTarget(chart)` targets an individual chart instance and applies only the template's indicators while leaving the chart's active symbol and timeframe unchanged.

```ts
import type { VelaWorkspace } from '@luxalgo/vela/workspace';
import { applyTemplate, captureIndicators, chartTarget, indicatorTemplatesController, shellTarget } from '@luxalgo/vela-pro';

declare const workspace: VelaWorkspace;

const templates = indicatorTemplatesController();

// Save the active chart's indicators without binding a symbol or timeframe.
await templates?.save({
    id: crypto.randomUUID(),
    name: 'Trend setup',
    symbol: null,
    timeframe: null,
    indicators: captureIndicators(workspace.chart),
    updatedAt: Date.now(),
});

// Apply the newest template to the active chart, plus its indicators to all other charts.
const [latest] = templates?.list() ?? [];
if (latest) {
    applyTemplate(shellTarget(workspace.context()), latest);
    for (const cell of workspace.cells()) {
        if (cell.chart !== workspace.chart) applyTemplate(chartTarget(cell.chart), latest);
    }
}
```

## Template schema [#template-schema]

```typescript
interface IndicatorTemplate {
    id: string;
    name: string;
    symbol: string | null; // null keeps the target chart's current symbol
    timeframe: string | null;
    indicators: TemplateIndicator[];
    updatedAt: number;
}

type TemplateIndicator =
    | { kind: 'script'; name: string; script: string; inputs?: Record<string, unknown>; props?: Record<string, unknown> }
    | { kind: 'native'; name: string; type: string; inputs?: Record<string, unknown> };
```

* Script indicators store their complete `script` source code and declared indicator title as `name`. Built-in indicators store their registered `type`.
* Parameter values are snapshotted in full. Unlike the [workspace state document](/vela-pro/persistence/stores/indicators#inputs-properties-and-visibility), which records only modified deltas, `inputs` and `props` in a template store every parameter value at the moment the template was saved, so subsequent changes to script defaults do not alter existing templates.
* Templates omit three runtime fields: script `language` (every script in a template executes as Pine Script®), indicator visibility (all template indicators mount visible), and runtime indicator IDs.
* Vela Pro's internal order and alert chart layers (`vela-pro.trading` and `vela-pro.alerts`) are excluded during capture and preserved undisturbed when applying a template.

On subsequent page reloads, built-in indicators applied from a template persist in the workspace state document like any other built-in study. Script indicators applied from a template follow the [non-persisted scripts](/vela-pro/persistence/stores/indicators#non-persisted-scripts) rule and are included in the workspace state document only if that exact script source was also added from the indicator menu or restored from a state document during the session.

## Related [#related]

* [Indicator persistence](/vela-pro/persistence/stores/indicators)
* [Server-side storage](/vela-pro/persistence/backend)
* [Indicator menu](/vela-pro/indicators/library)
