Script Execution
The ScriptProvider interface connects Altrady Charts to a backend that can compile and execute trading scripts. When provided, a script editor button (fx) appears in the period bar toolbar and opens the editor.
Altrady Charts does not bundle an editor UI. The provider supplies it through the optional EditorComponent (see Editor slot); without one, the fx button renders nothing. Scripts can also draw on the chart — see Script-drawn primitives.
Scripts executed via ScriptProvider return an IndicatorSubscription — the same type used by IndicatorProvider. This means compiled scripts flow through the exact same calc-bridge rendering pipeline as backend indicators.
ScriptProvider Interface
export interface ScriptProvider {
/**
* Compile/validate script source without executing it.
* Returns diagnostics (errors, warnings) and optional metadata
* about what the script will plot.
* `modules` are additional module sources keyed by import path — pass the
* same set given to `executeAsIndicator`/`executeAsBot`, or diagnostics
* will reference files the compiler never saw.
*/
compile(code: string, language: string, modules?: Record<string, string>): Promise<ScriptCompileResult>
/**
* Execute a script as a chart indicator.
* Returns an IndicatorSubscription — data flows through the calc bridge
* the same way as backend indicators.
*/
executeAsIndicator(params: ScriptExecuteParams): Promise<IndicatorSubscription>
/**
* Optional. Execute a script as a trading bot.
* Returns a BotSubscription that emits trading signals.
*/
executeAsBot?(params: ScriptExecuteParams): Promise<BotSubscription>
/**
* Stop a running script. Cleans up server-side resources.
*/
stop(scriptId: string): Promise<void>
/**
* Optional. Re-run a script with new settings, keeping the same scriptId.
* Data re-flows through the existing onData/onTick/onPrimitives handlers.
* Implement this: without it, `updateScriptIndicator` falls back to an
* internal stop + re-execute, which is heavier and re-registers the
* script's klinecharts templates under new names.
*/
updateSettings?(scriptId: string, settings: Record<string, SettingValue>): Promise<void>
/** Optional. List saved scripts for the current user. */
listScripts?(): Promise<ScriptInfo[]>
/** Optional. Save a script to the backend. */
saveScript?(script: ScriptSaveParams): Promise<ScriptInfo>
/** Optional. Delete a saved script. */
deleteScript?(scriptId: string): Promise<void>
/** Optional. Clean up all connections when the chart is disposed. */
dispose?(): void
}
Script Execution Types
ScriptExecuteParams
export interface ScriptExecuteParams {
/** Script source code */
code: string
/** Language identifier matching ScriptLanguageDefinition.name */
language: string
/** Symbol context for execution */
symbol: SymbolInfo
/** Period context for execution */
period: Period
/** User-configured settings from the indicator settings modal */
settings?: Record<string, SettingValue>
/**
* Additional module sources keyed by import path (e.g. `"./helper"`), for
* multi-file scripts. Pass the same set to `compile` — otherwise
* diagnostics reference files the compiler never saw.
*/
modules?: Record<string, string>
}
ScriptIndicatorParams (the argument to addScriptIndicator) derives from this type, so it carries modules too.
ScriptCompileResult
export interface ScriptCompileResult {
success: boolean
errors?: ScriptDiagnostic[]
warnings?: ScriptDiagnostic[]
/**
* Metadata about what the script will plot.
* Reuses IndicatorMetadata — same plots, settings, and axes system
* as backend indicators.
*/
metadata?: IndicatorMetadata
}
ScriptDiagnostic
Used by both ScriptCompileResult and the diagnostics prop passed to the provider's EditorComponent.
export interface ScriptDiagnostic {
line: number // 1-based line number
column: number // 1-based column number
endLine?: number
endColumn?: number
message: string
severity: 'error' | 'warning' | 'info'
file?: string // which module this points at, for multi-file scripts
}
Bot Subscription
When executeAsBot is implemented, it returns a BotSubscription that emits trading signals.
export interface BotSubscription {
botId: string
onSignal(handler: (signal: BotSignal) => void): void
onError?(handler: (error: Error) => void): void
dispose(): void
}
export interface BotSignal {
type: 'buy' | 'sell' | 'close' | 'modify'
timestamp: number
price?: number
quantity?: number
stopLoss?: number
takeProfit?: number
metadata?: Record<string, unknown>
}
Script Management
export interface ScriptInfo {
id: string
name: string
code: string
language: string
createdAt: number // Unix ms
updatedAt: number // Unix ms
description?: string
}
export interface ScriptSaveParams {
name: string
code: string
language: string
description?: string
}
ScriptLanguageDefinition
Declarative description of a scripting language (keywords, built-in functions and variables). Set it as ScriptProvider.language: the chart passes it to the provider's EditorComponent for highlighting/autocomplete and uses language.name as the language of executeAsIndicator calls (falls back to 'pine' when unset). Altrady Charts no longer ships a built-in language definition.
export interface ScriptLanguageDefinition {
/** Language identifier matched against ScriptExecuteParams.language */
name: string
/** File extension hint (e.g. '.pine') */
extension?: string
/** Keywords to highlight as control-flow tokens */
keywords: string[]
/** Type qualifiers highlighted differently from keywords */
typeKeywords?: string[]
/** Functions for highlighting and autocomplete */
builtinFunctions: ScriptBuiltinFunction[]
/** Variables (including namespaces and constants) for autocomplete */
builtinVariables?: ScriptBuiltinVariable[]
comments: {
line?: string // e.g. '//'
blockStart?: string // e.g. '/*'
blockEnd?: string // e.g. '*/'
}
operators?: string[]
stringDelimiters?: string[]
}
ScriptBuiltinFunction
export interface ScriptBuiltinFunction {
name: string
description?: string
parameters?: ScriptFunctionParameter[]
returnType?: string
}
export interface ScriptFunctionParameter {
name: string
type: string
description?: string
optional?: boolean
}
ScriptBuiltinVariable
export interface ScriptBuiltinVariable {
name: string
description?: string
type?: string
}
Editor slot
The base library owns only the fx button and the open/close lifecycle of the editor panel. The editor UI itself is supplied by the provider:
import type { ScriptProvider, ScriptEditorComponentProps } from '@altrady/charts'
const provider: ScriptProvider = {
// ...compile / executeAsIndicator / stop...
language: myLanguageDefinition, // optional — forwarded to the editor
defaultScript: '// starter code', // optional — initial buffer when opened empty
EditorComponent: MyEditor, // React component receiving ScriptEditorComponentProps
}
ScriptEditorComponentProps carries everything the editor needs — theme, locale, language, initialCode, readOnly, diagnostics, and the callbacks onClose, onAddToChart(code), onSave(code, name), onChange, onCloneAndEdit(code) — so the editor never imports the chart runtime. The @coinrayio/superchart-script package ships a CodeMirror-based implementation.
When the provider has no EditorComponent, nothing renders: the fx button toggles internal state only, and the read-only "view preset code" path (indicator tooltip code icon → getIndicatorCode) shows nothing either.
Script-drawn primitives
Scripts can draw markers, lines, boxes and labels directly on the chart. The subscription returned by executeAsIndicator may implement onPrimitives(handler); the chart calls the handler's PrimitiveSnapshot through an idempotent reconciler that creates, replaces and removes locked, non-persisted overlays (scriptMarker, scriptLine, scriptBox, scriptLabel). Send the full current snapshot on every run — initial, history recompute and each live tick — and the chart diffs it. Primitives are torn down when the script indicator is removed.
subscription.onPrimitives?.((snapshot: PrimitiveSnapshot) => { /* chart handles this */ })
interface PrimitiveSnapshot { primitives: { key: string; primitive: ScriptPrimitive }[] }
// ScriptPrimitive = marker | line | box | label — see src/lib/types/primitive.ts
Script logs
IndicatorSubscription has an optional onLog(handler) for log.* calls made from a script. Altrady Charts only defines the type and the callback slot — it registers no handler of its own; consuming logs (displaying them, filtering by level, deduping) is entirely up to the host's provider wrapper.
interface ScriptLogEntry {
level: 'debug' | 'info' | 'warn' | 'error' // wasm host LogEvent levels 0–3, mapped 1:1
message: string
timestamp: number // bar time, ms epoch — not wall-clock arrival
}
subscription.onLog?.((entry: ScriptLogEntry) => { /* host decides what to do */ })
Gating log entries to confirmed bars and deduping repeated messages are the emitter's (the ScriptProvider's) responsibility, not Altrady Charts'.
Script API
Scripts are run, removed and observed via the AltradyCharts class API — no React required. The editor is one way in; hosts with their own IDE use addScriptIndicator directly.
addScriptIndicator(params)
Executes params.code through the configured scriptProvider and renders it exactly as the editor's "Add to chart" does — same plots, same plotPane sub-panes, same script-drawn primitives. Resolves an opaque, stable scriptId. Symbol and period are the chart's current ones.
const scriptId = await chart.addScriptIndicator({
code: '//@version=5\nindicator("My Script")\nplot(close)',
language: 'pine', // optional — defaults to scriptProvider.language?.name ?? 'pine'
settings: { length: 14 }, // optional — forwarded to executeAsIndicator
})
- Waits for the chart to mount if called right after construction.
- Rejects when no
scriptProvideris configured, when execution fails, whenremoveScriptIndicatorwas called for the id before execution finished ('removed before start'), or whendispose()ran while execution was still in flight ('AltradyCharts disposed'). - A resolved
scriptIdmeans the script is running, not that it necessarily rendered any plots — ifmetadata.plotsproduced no templates (and the script drew no primitives either), aconsole.warnis logged instead of anything appearing on the chart. - To change settings on a running script in place, use
updateScriptIndicatorinstead of remove + add.
updateScriptIndicator(scriptId, settings)
Updates a running script indicator's settings. The scriptId returned by addScriptIndicator stays stable across the update — no re-subscribe needed on the host side.
await chart.updateScriptIndicator(scriptId, { length: 21 })
- No-op for an unknown id.
- When the configured
scriptProviderimplementsupdateSettings, that's used directly: the existing subscription'sonData/onTick/onPrimitiveshandlers just receive new data, unchanged. - When it doesn't, Altrady Charts falls back internally to a stop + re-execute: the running script is stopped and a fresh
executeAsIndicatorcall is made with the new settings, re-rendering its plots and primitives — all under the samescriptId, so nothing on the host side needs to change. The provider's own subscription id may change behind the scenes; onlyscriptIdis ever host-facing. - Normally never fires the
scriptIndicatorRemoveevent — from a host's perspective the script never left the chart, only its settings changed. - One exception, on that fallback path: if the internal re-execute fails (a settings dialog is exactly where a user supplies a value the script rejects), the script really is off the chart. Altrady Charts drops its record, fires the
scriptIndicatorRemoveevent withscriptIdso the host can release its handle, and then propagates the rejection — so anawait updateScriptIndicator(...)that throws means the script is gone, not merely unchanged.
removeScriptIndicator(scriptId)
Complete teardown — the same path as the ✕ on the indicator's pane legend: every pane the script rendered to and its primitives come off the chart synchronously (this is also the point the scriptIndicatorRemove event fires), then scriptProvider.stop(scriptId) is called. The returned promise additionally awaits that stop() call. A no-op for an unknown or already-removed id, so a host can always call it from cleanup without checking.
await chart.removeScriptIndicator(scriptId)
on('scriptIndicatorRemove', callback)
Fires once a script indicator is off the chart, by any removal path — legend ✕, removeScriptIndicator, or dispose() — so a host can drop a handle the user closed. This fires before scriptProvider.stop() has necessarily settled; removeScriptIndicator's own promise additionally awaits stop(). Returns an unsubscribe function.
const unsub = chart.on('scriptIndicatorRemove', (id) => {
if (id === heldId) heldId = null
})
Read-Only Code Viewer for Server Presets
When IndicatorProvider.getIndicatorCode is configured, clicking the {} code icon on any backend indicator tooltip automatically opens the read-only viewer with that indicator's source. This is handled internally by Altrady Charts — no additional wiring required.
In read-only mode the chart passes readOnly: true and an onCloneAndEdit(code) callback to the EditorComponent; calling it reopens the editor in write mode with the same code pre-filled. How that is surfaced (button, menu, …) is up to the editor.
Saved script indicators
A script indicator can belong to the chart state like any other indicator.
It is saved by reference, never by code, in ChartState.scripts:
interface SavedScriptIndicator {
id: string // stable; names its templates and panes
ref: string // host script id, or `builtin:<name>`
name: string // shown while the script is unavailable
settings?: Record<string, SettingValue>
}
Built-in indicators picked from the indicator picker are saved this way
(builtin:<name>). Host scripts need a scriptLibrary:
new AltradyCharts({
// ...
scriptProvider,
scriptLibrary: {
// The picker's "Scripts" section, fetched when the picker opens.
// A `group` lists the item under its own category, after Scripts.
list: async () => [{ id: '42', name: 'My strategy', description: '…', group: 'Acme' }],
// null: gone for good. Throw: transient, retried on the next load.
resolve: async (id) => ({ code, modules, name }),
},
})
- On load and on
setStorageKey/switchLayout, each saved script is resolved and run again under its entry id. Scripts already running for the same entry and settings are left alone. - A script that can't be resolved or run stays saved and gets a legend row
<name> (unavailable)with nothing drawn; ✕ removes it like any indicator. - Settings changes are saved. A settings change the script rejects puts the script back on its saved settings.
- Adding, removing and changing a saved script are undo/redo steps like any indicator change.
- Every running script (saved or not) re-runs when the chart's symbol or period changes.
addScriptIndicator({ ref, code, ... })adds and saves one; withoutrefit is a preview that lives until removed or the chart unloads, as the editor's "Add to chart" is.
Script alerts
A script fires alerts with the SDK's declareAlert(name) / alert(name, message) — Pine's alertcondition. A provider surfaces them on the subscription:
onAlert?(handler: (alert: ScriptAlert) => void): void // { name, message, timestamp }
Altrady Charts registers that channel and hands each alert to the host:
new AltradyCharts({
scriptProvider,
onScriptAlert: ({ scriptId, name, message, timestamp }) => { /* route it */ },
})
The chart delivers them and does nothing else: there is no notification, sound
or list for script alerts, because only the host knows what one should do.
This is unrelated to setAlerts, which is a list of price levels the chart
draws — a script alert is an event on a bar, with no price, and setAlerts
replaces its whole list on every call.
Alerts arrive for confirmed bars only (a forming bar re-emits its events every tick), and ones fired before a handler registers are buffered and delivered on registration, capped to the most recent.
Alerts on an indicator
onScriptAlert is the browser's copy of a running script's alerts. For alerts
that run without the chart (TradingView's "Add alert on
new AltradyCharts({
onAddIndicatorAlert: ({ scriptId, ref, name, settings, metadata, symbol, period, slug, sourceHash }) => {
// open the host's alert dialog
},
alertableBuiltins: ['relative-strength-index', 'macd'],
})
With the callback set, a script's legend row gets a bell button on hover, and
a script in its own pane gets the same icon in its pane legend. It shows for a
saved library script and for a built-in whose slug is in alertableBuiltins
(replace the list later with superchart.setAlertableBuiltins(slugs)). It never
shows for an unsaved editor preview or a script that could not start.
settings holds every input: the declared defaults with the user's edits on
top, without the style: keys. metadata carries the plots and the alerts the
script declares (metadata.alerts), so a dialog can offer both as conditions.
A built-in carries slug, its source file name (relative-strength-index),
and sourceHash, builtinSourceHash of the code it runs. A server names the
compiled built-in by the pair, so an alert runs exactly the version the user
saw. pnpm publish:builtins --out <dir> (see scripts/publish-builtins.mjs)
compiles the built-ins whose source changed into <dir>/<sha256>.wasm, with a
manifest-<version>.json mapping each slug and source hash to its wasm, inputs,
alerts and whether it is alertable. Coinray's alert server runs it against a
Altrady Charts release and ships the folder; which built-ins are alertable comes
from that server, and the host passes them as alertableBuiltins.
Reference implementation: AltradyScript (@altrady/script)
WasmScriptProvider, from the @altrady/script package (also published as
@coinrayio/superchart-script), is the provider examples/client runs. Its
language is AltradyScript: TypeScript against the @altrady/strategy
SDK (scripts written against its original name, @coinray/strategy, keep
compiling). A compile endpoint turns them into WebAssembly plus
metadata (declared inputs, alerts, warm-up length), and the WebAssembly runs in
the browser over the same Datafeed the chart reads, so no execution server
is involved. The package also supplies language, defaultScript and the
EditorComponent.
import { WasmScriptProvider } from '@altrady/script'
import '@altrady/script/styles'
const datafeed = new MyDatafeed()
const dataLoader = createDataLoader(datafeed)
const scriptProvider = new WasmScriptProvider({
datafeed, // the same instance the chart loads from
compileEndpoint: 'https://…/compile',
compileHeaders: { Authorization: `Bearer ${token}` },
})
dataLoader.setOnBarsLoaded((fromMs) => {
void scriptProvider.loadHistoryBefore(fromMs)
})
const chart = new AltradyCharts({ container: 'chart', symbol, period, dataLoader, scriptProvider })
What any provider has to handle
Whatever runs your scripts, two things recur:
Events can arrive before handlers. Altrady Charts registers onData / onTick
/ onHistory on the subscription after executeAsIndicator resolves, and a
fast backend can emit before then. Buffer events per kind and replay them when
the handler is registered, or the first dataset is silently lost.
Older bars need older values. When the user scrolls back and the data loader
fetches older candles, running scripts must compute over them too. Expose a
loadHistoryBefore(fromMs) and call it from dataLoader.setOnBarsLoaded, as
above, then deliver the result through onHistory.