Vela, our next-generation charting platform, is live at vela.luxalgo.com.
LuxAlgo

AI

API reference for @luxalgo/vela-pro-ai, including the AI plugin, chat widget, chart helpers, input schemas, and message types.

View as Markdown

This page documents @luxalgo/vela-pro-ai, including the ai() plugin factory, AiChatWidget and createAiChat, createAiHelpers, AI_HELPER_SCHEMAS, and the message and chart-surface types.

Import symbols on this page from @luxalgo/vela-pro-ai. Related guides: AI, Standalone widgets.

Functions

ai

The AI module as a Vela Pro plugin.

function ai(opts: EnableAiOptions): VelaProPlugin<AiApi>

See also: AiApi, EnableAiOptions, VelaProPlugin.

aiApi

The page's AI API, once enableAi or ai() installed.

function aiApi(): AiApi | null

See also: AiApi.

aiSurface

The helpers' surface over the shell ctx belongs to. It reads the shell's charts afresh at every call, so it stays right across layout changes.

function aiSurface(ctx: WidgetContext): AiSurface

See also: AiSurface. From @luxalgo/vela/plugin: WidgetContext.

chartAt

The chart a call targets: the one at slot, or the active one. A string says why there is none.

function chartAt(surface: AiSurface, slot: unknown): AiChartRef | string

See also: AiChartRef, AiSurface.

createAiChat

The AI chat: the conversation, the suggestions and the prompt. Returns { el, tools, update, submit, focus, destroy }.

function createAiChat(props: AiChatProps): AiChatWidget

See also: AiChatProps, AiChatWidget.

createAiHelpers

The helpers over surface.

function createAiHelpers(surface: AiSurface, options?: AiHelpersOptions): AiHelpers

See also: AiHelpers, AiHelpersOptions, AiSurface.

enableAi

Enable the AI side panel on every shell built afterwards. Returns the page's AiApi. Call ONCE, before constructing shells. Idempotent.

function enableAi(opts: EnableAiOptions): AiApi

See also: AiApi, EnableAiOptions.

normalizeTimeframe

A timeframe as a person writes it, as the chart takes it: minutes are bare numbers ("15m" → "15", "4h" → "240"), longer units are letters ("1D" → "D", "2W", "1M" → "M"). Lowercase m is minutes and uppercase M months. Null for anything else, seconds included.

function normalizeTimeframe(input: string): string | null

outcomeErrorText

A failed outcome's error with what the helper said about it, as lines.

function outcomeErrorText(outcome: Extract<AiOutcome, { ok: false }>): string

See also: AiOutcome.

registerAiNative

Register the bars native. Idempotent; call before charts are built or after, a chart adds it on its first read.

function registerAiNative(): void

schemaProblems

Why value does not fit schema, one sentence per problem; empty when it fits.

function schemaProblems(schema: JsonSchema, value: unknown, path?: string): string[]

Default: path = 'input'.

See also: JsonSchema.

Classes

AiChatWidget

class AiChatWidget {
    constructor(props: AiChatProps);
    readonly el: HTMLElement;
    readonly tools: HTMLElement;
    readonly status: AiChatStatus;
    readonly busy: boolean;
    readonly model: string | undefined;
    update(next: AiChatState & Partial<Pick<AiChatProps, 'suggestions' | 'models'>>): void;
    submit(text: string): void;
    setModel(id: string): void;
    focus(): void;
    destroy(): void;
}
MemberTypeDescription
constructor(props: AiChatProps)
elHTMLElement
toolsHTMLElementCompact controls (new chat): in the widget's top row until lifted into a panel header.
statusAiChatStatusWhere the conversation stands: as last given, or streaming while a call of the last reply has no result.
busybooleanWhether a reply is on its way.
modelstring | undefinedThe id of the model picked; undefined when no model is listed.
update()(next: AiChatState & Partial<Pick<AiChatProps, 'suggestions' | 'models'>>) => voidDraw the conversation as it now stands, and take new suggestions or models. Only the fields given change.
submit()(text: string) => voidSend text as if the user had typed it. Ignored while a reply is on its way.
setModel()(id: string) => voidShow id as the model picked. Ignored for a model the picker does not list.
focus()() => voidPut the caret in the prompt.
destroy()() => void

See also: AiChatProps, AiChatState, AiChatStatus.

Interfaces and types

AddIndicatorInput

interface AddIndicatorInput extends OnChart {
    type?: string;
    inputs?: Readonly<Record<string, AiInputValue>>;
}

// Unexported supporting type referenced above
interface OnChart {
    slot?: number;
}
MemberTypeDescription
type?stringThe built-in type to add. Absent: the helper lists the types the chart offers.
inputs?Readonly<Record<string, AiInputValue>>Settings to start it with, by input key or title.

See also: AiInputValue.

AiApi interface

What the AI plugin offers the host and other plugins.

interface AiApi {
    helpers(ctx?: WidgetContext): AiHelpers | null;
    chat(ctx?: WidgetContext): AiChatWidget | null;
    ask(ctx: WidgetContext, text?: string): void;
}
MemberTypeDescription
helpers()(ctx?: WidgetContext) => AiHelpers | nullThe helpers over ctx's shell, or over the shell built last; null without ctx before a shell is built. The same ones connect was given, so the host's code and its tools queue their changes in one line.
chat()(ctx?: WidgetContext) => AiChatWidget | nullThe chat of ctx's shell, or of the shell built last; null before its panel is built.
ask()(ctx: WidgetContext, text?: string) => voidOpen the AI panel on ctx's shell and, given text, send it as the user's message.

See also: AiChatWidget, AiHelpers. From @luxalgo/vela/plugin: WidgetContext.

AiBar

interface AiBar {
    readonly time: number;
    readonly open: number;
    readonly high: number;
    readonly low: number;
    readonly close: number;
    readonly volume?: number;
}

AiCallOptions

interface AiCallOptions {
    signal?: AbortSignal;
}
MemberTypeDescription
signal?AbortSignalAborted when the user stops the reply: a helper that waits stops waiting.

AiChart

The part of a Vela chart the helpers use.

interface AiChart {
    readonly market: { readonly symbol?: string; readonly timeframe?: string; readonly session?: AiMarketSession };
    setMarket(next: { symbol?: string; timeframe?: string; session?: AiMarketSession; visibleRange?: AiRangePreset | { from: number; to: number } }): Promise<unknown>;
    ready(): Promise<unknown>;
    indicators(): readonly AiIndicator[];
    runIndicator(
        source: string,
        options?: { language?: string },
    ): Promise<{ ok: boolean; handle: AiIndicator | null; error: Error | null }>;
    addNativeIndicator(type: string, options?: { inputs?: Record<string, AiInputValue> }): AiIndicator;
    availableNativeIndicators(): Promise<ReadonlyArray<{ readonly type: string; readonly title: string; readonly supported: boolean; readonly present: boolean }>>;
    getVisibleRange(): { from: number; to: number } | null;
    setVisibleRange(range: { from: number; to: number }): unknown;
    setVisibleRangePreset(preset: AiRangePreset): unknown;
    readonly renderer: {
        supports(feature: string): boolean;
        get(feature: string): unknown;
        set(feature: string, value: unknown): unknown;
        screenshot(): string | null;
    };
    readonly data: {
        resolve(symbol: string): { provider: string; ticker: string } | null;
        ready(): Promise<unknown>;
        symbolInfo(symbol: string): Promise<unknown>;
    };
    readonly drawings: AiDrawings;
    readonly replay: { readonly state: { readonly active: boolean } };
}
MemberTypeDescription
market{ readonly symbol?: string; readonly timeframe?: string; readonly session?: AiMarketSession }
setMarket()(next: { symbol?: string; timeframe?: string; session?: AiMarketSession; … (truncated; see declaration)
ready()() => Promise<unknown>
indicators()() => readonly AiIndicator[]
runIndicator()(source: string, options?: { language?: string }) => Promise<{ ok: boolean; … (truncated; see declaration)
addNativeIndicator()(type: string, options?: { inputs?: Record<string, AiInputValue> }) => AiIndicator
availableNativeIndicators()() => Promise<ReadonlyArray<{ readonly type: string; readonly title: string; … (truncated; see declaration)
getVisibleRange()() => { from: number; to: number } | null
setVisibleRange()(range: { from: number; to: number }) => unknown
setVisibleRangePreset()(preset: AiRangePreset) => unknown
renderer{ supports(feature: string): boolean; get(feature: string): unknown; … (truncated; see declaration)
data{ resolve(symbol: string): { provider: string; ticker: string } | null; … (truncated; see declaration)
drawingsAiDrawings
replay{ readonly state: { readonly active: boolean } }Bar replay: while it runs, the chart's last bar is the replay's cursor, not the present.

See also: AiDrawings, AiIndicator, AiInputValue, AiMarketSession, AiRangePreset.

AiChartRef

One chart of the shell: slot is its place in the layout, 0 first, in reading order.

interface AiChartRef {
    readonly slot: number;
    readonly chart: AiChart;
}

See also: AiChart.

AiChatHandlers

What the host's code does when the user acts on the chat.

interface AiChatHandlers {
    onSubmit(message: AiChatSubmission): void | Promise<unknown>;
    onStop?(): void;
    onNewChat?(): void;
    destroy?(): void;
}
MemberTypeDescription
onSubmit()(message: AiChatSubmission) => void | Promise<unknown>The user sent a message: add it to the conversation and ask the model. A rejected promise puts the text back in the prompt.
onStop?()() => voidThe user pressed stop while a reply was on its way.
onNewChat?()() => voidThe user asked for a new conversation. Without it there is no New chat button.
destroy?()() => voidThe panel is going away with its shell.

See also: AiChatSubmission.

AiChatMessage

One message of the conversation, as the chat draws it.

interface AiChatMessage {
    readonly id: string;
    readonly role: 'system' | 'user' | 'assistant';
    readonly parts: readonly AiChatPart[];
}
MemberTypeDescription
idstringStable for the message's life: the chat follows a message by it.
role'system' | 'user' | 'assistant'
partsreadonly AiChatPart[]

See also: AiChatPart.

AiChatPart

One part of a message. The shapes are those of the AI SDK's UIMessage parts, so a conversation it keeps is drawn as it is. A part the chat does not know (a step boundary, a data part) draws nothing unless the host's renderPart draws it.

type AiChatPart =
    | AiTextPart
    | AiReasoningPart
    | AiToolPart
    | AiFilePart
    | AiSourcePart
    | { readonly type: string; readonly [key: string]: unknown };

See also: AiFilePart, AiReasoningPart, AiSourcePart, AiTextPart, AiToolPart.

AiChatProps

The chat widget's props. The callbacks and host are read once; the state, the suggestions and the models can change through update.

interface AiChatProps extends AiChatState {
    onSubmit: (message: AiChatSubmission) => void | Promise<unknown>;
    onStop?: () => void;
    onNewChat?: () => void;
    host?: HTMLElement;
    title?: string;
    description?: string;
    suggestions?: readonly string[];
    placeholder?: string;
    highlight?: AiCodeHighlighter;
    models?: readonly AiModel[];
    model?: string;
    modelLogo?: (key: string) => string | Node | null | undefined;
    onModelChange?: (id: string) => void;
    promptTools?: HTMLElement;
    renderPart?: (part: AiChatPart, message: AiChatMessage) => Node | null | undefined;
}
MemberTypeDescription
onSubmit(message: AiChatSubmission) => void | Promise<unknown>The user sent a message. The host adds it to its conversation and asks its model. When the promise it returns rejects, the text goes back into the prompt.
onStop?() => voidThe user pressed stop while a reply was on its way.
onNewChat?() => voidThe user asked for a new conversation. Without it there is no New chat button.
host?HTMLElementWhere tooltips mount (default: the widget's own element).
title?stringWhat an empty conversation says.
description?string
suggestions?readonly string[]Prompts offered above the input while the conversation is empty; a press sends one.
placeholder?string
highlight?AiCodeHighlighterHighlights the code blocks of a reply; the kit ships no highlighter.
models?readonly AiModel[]The models the user can pick from. With any, a picker sits in the prompt's footer and model is the id picked: the host names it in its requests. Without any, there is no picker.
model?stringThe id of the model picked to start with (default: the first of models).
modelLogo?(key: string) => string | Node | null | undefinedThe logo of a model's maker or of a service, by its key: an address, an element, or null for the key's initial.
onModelChange?(id: string) => voidThe user picked a model.
promptTools?HTMLElementA control of the host's in the prompt's footer, after the model picker.
renderPart?(part: AiChatPart, message: AiChatMessage) => Node | null | undefinedDraw a part of a message yourself: a data part, a tool call with a card of its own. Return a node to draw it, null to draw nothing, undefined to leave it to the chat. Asked again when the part changes.

See also: AiChatMessage, AiChatPart, AiChatState, AiChatSubmission, AiModel. From @luxalgo/vela-ui/ai-code-block: AiCodeHighlighter.

AiChatState

What the chat draws: the host's conversation as it stands.

interface AiChatState {
    messages?: readonly AiChatMessage[];
    status?: AiChatStatus;
    error?: Error | string | null;
}
MemberTypeDescription
messages?readonly AiChatMessage[]The conversation, oldest first. Replace a message that changed, or change the last one in place.
status?AiChatStatusWhere the conversation stands (default ready). While the last reply has a tool call without a result, the chat counts a ready conversation as still streaming: the prompt shows stop, and nothing can be sent.
error?Error | string | nullWhy the last request failed, shown under the conversation.

See also: AiChatMessage, AiChatStatus.

AiChatStatus

Where the conversation stands: submitted once a message is sent and nothing has come back, streaming while the reply arrives, error when the last request failed.

type AiChatStatus = 'ready' | 'submitted' | 'streaming' | 'error';

AiChatSubmission

What the user sent from the prompt, or picked among the suggestions.

interface AiChatSubmission {
    text: string;
}

AiChatView

A shell's chat, as the host's code drives it.

interface AiChatView {
    update(state: AiChatState): void;
    readonly model: string | undefined;
    focus(): void;
}
MemberTypeDescription
update()(state: AiChatState) => voidDraw the conversation as it now stands: its messages, its status, its error. Only the fields given change.
modelstring | undefinedThe id of the model the user picked; undefined when no model is listed.
focus()() => voidPut the caret in the prompt.

See also: AiChatState.

AiDrawingGroup

A named bundle of drawings: what the chart's object tree lists as one.

interface AiDrawingGroup {
    id: string;
    name: string;
    ids: string[];
    pane?: string;
}

AiDrawingInit

A drawing as a helper asks a chart to add it.

interface AiDrawingInit {
    anchors?: Array<{ time: number; price: number }>;
    style?: Record<string, unknown>;
    text?: {
        value: string;
        size: 'small';
        hAlign: 'left' | 'center' | 'right';
        vAlign: 'top' | 'center' | 'bottom';
        color?: string;
        place?: 'start' | 'middle' | 'end';
        side?: 'above' | 'below';
    };
    props?: Record<string, unknown>;
}

AiDrawings

The part of a chart's drawings the helpers use.

interface AiDrawings {
    readonly supported: boolean;
    add(type: string, init?: AiDrawingInit): { readonly id: string } | null;
    removeMany(ids: readonly string[]): unknown;
    lock(id: string, locked?: boolean): unknown;
    bringToFront(id: string): unknown;
    groups(): AiDrawingGroup[];
    setGroups(groups: readonly AiDrawingGroup[]): unknown;
    toolDefaults(): Readonly<Record<string, unknown>>;
    setToolDefaults(map: Readonly<Record<string, unknown>>): unknown;
}
MemberTypeDescription
supportedbooleanWhether the chart can paint drawings at all.
add()(type: string, init?: AiDrawingInit) => { readonly id: string } | nullNull when the chart could not make the drawing.
removeMany()(ids: readonly string[]) => unknown
lock()(id: string, locked?: boolean) => unknown
bringToFront()(id: string) => unknown
groups()() => AiDrawingGroup[]
setGroups()(groups: readonly AiDrawingGroup[]) => unknown
toolDefaults()() => Readonly<Record<string, unknown>>Each tool's remembered settings: what its next drawing starts from.
setToolDefaults()(map: Readonly<Record<string, unknown>>) => unknown

See also: AiDrawingGroup, AiDrawingInit.

AiFilePart

A file of a message; an image is drawn.

interface AiFilePart {
    readonly type: 'file';
    readonly mediaType: string;
    readonly url: string;
    readonly filename?: string;
}
MemberTypeDescription
type'file'
mediaTypestring
urlstringA data URL or an address.
filename?string

AiHelperName

type AiHelperName = keyof typeof SPECS;

AiHelpers

The helpers over one chart shell. Each one checks its input against its schema and answers with an AiOutcome; none throws. A refusal and a failure come back as { ok: false, error }, with the error written for a model to act on. Helpers that change the chart run one at a time, in the order they were called, and a helper that reads runs after the changes asked before it.

interface AiHelpers {
    readChart(): Promise<AiOutcome>;
    setChartState(input: SetChartStateInput, options?: AiCallOptions): Promise<AiOutcome>;
    captureChartScreenshot(
        input?: CaptureChartScreenshotInput,
        options?: AiCallOptions,
    ): Promise<AiOutcome>;
    readChartData(input: ReadChartDataInput, options?: AiCallOptions): Promise<AiOutcome>;
    writeScript(input: WriteScriptInput, options?: AiCallOptions): Promise<AiOutcome>;
    editScript(input: EditScriptInput, options?: AiCallOptions): Promise<AiOutcome>;
    readScript(input: ReadScriptInput, options?: AiCallOptions): Promise<AiOutcome>;
    removeScript(input: RemoveScriptInput, options?: AiCallOptions): Promise<AiOutcome>;
    setScriptInputs(input: SetScriptInputsInput, options?: AiCallOptions): Promise<AiOutcome>;
    addIndicator(input?: AddIndicatorInput, options?: AiCallOptions): Promise<AiOutcome>;
    markUpChart(input: MarkUpChartInput, options?: AiCallOptions): Promise<AiOutcome>;
    run(name: AiHelperName, input: unknown, options?: AiCallOptions): Promise<AiOutcome>;
    describe(): AiWorkspace;
}
MemberTypeDescription
readChart()() => Promise<AiOutcome>What the charts show: each chart's market, chart type, scale, visible range and indicators, with their ids.
setChartState()(input: SetChartStateInput, options?: AiCallOptions) => Promise<AiOutcome>Change a chart's symbol, timeframe, chart type, session, scale or visible range, and wait for the chart to show it.
captureChartScreenshot()(input?: CaptureChartScreenshotInput, options?: AiCallOptions) => Promise<AiOutcome>Capture a chart as an image: the outcome carries it in images.
readChartData()(input: ReadChartDataInput, options?: AiCallOptions) => Promise<AiOutcome>Read exact values: price bars, a script's plots, a strategy's trades, an indicator's settings, the window in view.
writeScript()(input: WriteScriptInput, options?: AiCallOptions) => Promise<AiOutcome>Add a script to the chart, or replace the whole code of one in place. A script the engine refuses leaves the chart as it was.
editScript()(input: EditScriptInput, options?: AiCallOptions) => Promise<AiOutcome>Change one script with an exact string replacement.
readScript()(input: ReadScriptInput, options?: AiCallOptions) => Promise<AiOutcome>Read a script's code, with line numbers.
removeScript()(input: RemoveScriptInput, options?: AiCallOptions) => Promise<AiOutcome>Remove one script or built-in indicator from the chart.
setScriptInputs()(input: SetScriptInputsInput, options?: AiCallOptions) => Promise<AiOutcome>Change an indicator's settings, as its settings dialog would.
addIndicator()(input?: AddIndicatorInput, options?: AiCallOptions) => Promise<AiOutcome>Add one of the chart's built-in indicators, or list the ones it offers.
markUpChart()(input: MarkUpChartInput, options?: AiCallOptions) => Promise<AiOutcome>Mark the chart up from its own bars (fair value gaps, liquidity, key levels…), as drawings grouped per concept.
run()(name: AiHelperName, input: unknown, options?: AiCallOptions) => Promise<AiOutcome>Run a helper by its name, with an input of unknown shape: what a model sent.
describe()() => AiWorkspaceWhat the charts show now, without a call: what readChart answers with, for a host that tells its model with each request.

See also: AddIndicatorInput, AiCallOptions, AiHelperName, AiOutcome, AiWorkspace, CaptureChartScreenshotInput, EditScriptInput, MarkUpChartInput, ReadChartDataInput, ReadScriptInput, RemoveScriptInput, SetChartStateInput, SetScriptInputsInput, WriteScriptInput.

AiHelpersOptions

interface AiHelpersOptions {
    language?: string;
}
MemberTypeDescription
language?stringThe key of the engine scripts are written for, and read from (default 'pine').

AiImage

An image a helper hands back for the model to look at (a chart screenshot).

interface AiImage {
    mediaType: string;
    dataUrl: string;
    alt: string;
}
MemberTypeDescription
mediaTypestring
dataUrlstringdata:image/png;base64,…
altstringWhat the image shows, for a model or a client that cannot take the image.

AiIndicator

An indicator or a strategy on a chart: a script, or a built-in.

interface AiIndicator {
    readonly id: string;
    readonly title: string;
    readonly source?: string;
    readonly nativeType?: string;
    readonly language?: string;
    readonly inputs: readonly AiInputSchema[];
    readonly visible: boolean;
    inputValues(): Record<string, AiInputValue>;
    setInputs(values: Record<string, AiInputValue>): void;
    updateCode(source: string): Promise<{ ok: boolean; error: Error | null }>;
    context(select?: ReadonlyArray<'plots' | 'meta' | 'strategy' | 'trades'>): Promise<AiScriptContext | null>;
    remove(): void;
}
MemberTypeDescription
idstring
titlestring
source?stringA script's code; absent for a built-in.
nativeType?stringA built-in's type; absent for a script.
language?stringThe key of the engine that runs a script.
inputsreadonly AiInputSchema[]
visibleboolean
inputValues()() => Record<string, AiInputValue>
setInputs()(values: Record<string, AiInputValue>) => void
updateCode()(source: string) => Promise<{ ok: boolean; error: Error | null }>
context()(select?: ReadonlyArray<'plots' | 'meta' | 'strategy' | 'trades'>) => Promise<AiScriptContext | null>
remove()() => void

See also: AiInputSchema, AiInputValue, AiScriptContext.

AiInputSchema

One input a script or a built-in indicator declares.

interface AiInputSchema {
    readonly key: string;
    readonly title: string;
    readonly type: string;
    readonly defval: AiInputValue;
    readonly min?: number;
    readonly max?: number;
    readonly step?: number;
    readonly options?: readonly string[];
}

See also: AiInputValue.

AiInputValue

type AiInputValue = number | string | boolean;

AiMarketSession

type AiMarketSession = 'regular' | 'extended';

AiModel

A model the user can pick: its id is what the host names it by.

type AiModel = KitAiModel;

From @luxalgo/vela-ui/ai-model-selector: KitAiModel.

AiOutcome

What a helper came to. result and details are plain JSON. A failed one is an answer too: its error is written for the model to act on.

type AiOutcome =
    | { ok: true; result: unknown; images?: readonly AiImage[] }
    | { ok: false; error: string; details?: unknown };

See also: AiImage.

AiPanelContext

What connect is given: one shell's chat, its helpers, and the shell itself.

interface AiPanelContext {
    chat: AiChatView;
    helpers: AiHelpers;
    ctx: WidgetContext;
}
MemberTypeDescription
chatAiChatView
helpersAiHelpersThe helpers over this shell's charts: what the host's tools call.
ctxWidgetContext

See also: AiChatView, AiHelpers. From @luxalgo/vela/plugin: WidgetContext.

AiRangePreset

type AiRangePreset = '1D' | '1W' | '1M' | '3M' | '6M' | '1Y' | '5Y' | 'YTD' | 'ALL';

AiReasoningPart

The model's reasoning, folded above what follows it.

interface AiReasoningPart {
    readonly type: 'reasoning';
    readonly text: string;
    readonly state?: 'streaming' | 'done';
}

AiScriptContext

The part of a script's execution context the helpers read.

interface AiScriptContext {
    readonly plots?: Readonly<Record<string, ReadonlyArray<{ readonly time: number; readonly value: unknown }>>>;
    readonly strategy?: Readonly<Record<string, unknown>> | object;
    readonly trades?: readonly AiStrategyTrade[];
}

See also: AiStrategyTrade.

AiSourcePart

A page the reply drew on.

interface AiSourcePart {
    readonly type: 'source-url';
    readonly url: string;
    readonly title?: string;
}

AiStrategyTrade

interface AiStrategyTrade {
    readonly id: string;
    readonly side: 'long' | 'short';
    readonly qty: number;
    readonly entry: { readonly time: number; readonly price: number };
    readonly exit?: { readonly time: number; readonly price: number };
    readonly open: boolean;
    readonly pnl?: number;
}

AiSurface interface

The chart shell, as the helpers see it.

interface AiSurface {
    charts(): AiChartRef[];
    activeSlot(): number | null;
    chartTypes?(): readonly string[];
    isInternal(indicator: AiIndicator): boolean;
    bars(chart: AiChart): Promise<readonly AiBar[]>;
    theme?(): 'light' | 'dark';
}
MemberTypeDescription
charts()() => AiChartRef[]The charts, in layout order. Read afresh at each call: a layout change replaces them.
activeSlot()() => number | nullThe slot of the chart the user works on; null before one exists.
chartTypes?()() => readonly string[]The chart types a plugin registered beside the built-in ones, when the shell can say.
isInternal()(indicator: AiIndicator) => booleanAn indicator a plugin keeps on the chart for its own use: never listed, read or removed.
bars()(chart: AiChart) => Promise<readonly AiBar[]>The chart's bars, oldest first. Rejects when the chart cannot hand them over.
theme?()() => 'light' | 'dark'Whether the charts sit on a light or a dark background: drawings take colors that read on it. Default dark.

See also: AiBar, AiChart, AiChartRef, AiIndicator.

AiTextPart

Text of a message. An assistant's is drawn as Markdown.

interface AiTextPart {
    readonly type: 'text';
    readonly text: string;
    readonly state?: 'streaming' | 'done';
}
MemberTypeDescription
type'text'
textstring
state?'streaming' | 'done'streaming while the text is still arriving.

AiToolPart

One call of a tool: its name is in the type (tool-write_script), or in toolName when the type is dynamic-tool.

interface AiToolPart {
    readonly type: `tool-${string}` | 'dynamic-tool';
    readonly toolName?: string;
    readonly toolCallId: string;
    readonly title?: string;
    readonly state: AiToolState;
    readonly input?: unknown;
    readonly output?: unknown;
    readonly errorText?: string;
}
MemberTypeDescription
type`tool-${string}` | 'dynamic-tool'
toolName?string
toolCallIdstring
title?stringWhat a person reads for the call ("Write script"). Default: the tool's name.
stateAiToolState
input?unknown
output?unknownWhat the tool returned. A helper's outcome is read as one: its images are drawn, a failed one shows as an error.
errorText?string

See also: AiToolState.

AiToolState

Where a tool call stands.

type AiToolState =
    | 'input-streaming'
    | 'input-available'
    | 'approval-requested'
    | 'approval-responded'
    | 'output-available'
    | 'output-error'
    | 'output-denied';

AiWorkspace

What the charts show: the layout's charts, and which one the user is working on.

interface AiWorkspace {
    activeSlot: number | null;
    charts: DescribedChart[];
}

See also: DescribedChart.

CaptureChartScreenshotInput

interface CaptureChartScreenshotInput extends OnChart {
    all?: boolean;
}

// Unexported supporting type referenced above
interface OnChart {
    slot?: number;
}
MemberTypeDescription
all?booleanCapture every chart of the layout, one image each (default: one chart).

ChartStatePatch

What to change on one chart. Only the fields present change.

interface ChartStatePatch extends OnChart {
    symbol?: string;
    timeframe?: string;
    chartType?: string;
    session?: AiMarketSession;
    scale?: { mode?: 'price' | 'percent' | 'indexed'; log?: boolean; invert?: boolean };
    visibleRange?: { preset?: AiRangePreset; from?: string | number; to?: string | number };
}

// Unexported supporting type referenced above
interface OnChart {
    slot?: number;
}
MemberTypeDescription
symbol?stringA bare ticker resolves against every data source of the chart; SOURCE:TICKER pins one.
timeframe?string
chartType?stringHow the price series is drawn: a built-in type, or another the chart has registered.
session?AiMarketSession
scale?{ mode?: 'price' | 'percent' | 'indexed'; log?: boolean; invert?: boolean }
visibleRange?{ preset?: AiRangePreset; from?: string | number; to?: string | number }A range ending now (preset), or an absolute window (from and to: ISO 8601 in UTC, or epoch milliseconds).

See also: AiMarketSession, AiRangePreset.

DescribedChart

interface DescribedChart {
    slot: number;
    symbol: string;
    timeframe: string;
    chartType?: string;
    session?: string;
    scale?: { mode?: string; log?: boolean; invert?: boolean };
    visibleRange: { from: string; to: string } | null;
    indicators: Array<Omit<DescribedIndicator, 'slot'>>;
}

See also: DescribedIndicator.

DescribedIndicator

interface DescribedIndicator {
    id: string;
    name: string;
    kind: 'indicator' | 'strategy' | 'builtin';
    slot: number;
    editable: boolean;
    hidden?: true;
}
MemberTypeDescription
idstring
namestring
kind'indicator' | 'strategy' | 'builtin'
slotnumber
editablebooleanIts code can be read and changed: a script the helpers' engine runs.
hidden?trueOn the chart but switched off: not drawn, not computing.

EditScriptInput

interface EditScriptInput extends OnChart {
    id: string;
    oldString: string;
    newString: string;
    replaceAll?: boolean;
}

// Unexported supporting type referenced above
interface OnChart {
    slot?: number;
}
MemberTypeDescription
idstringThe script, by the id the chart holds it under.
oldStringstringThe exact text to replace: it must occur once, unless replaceAll.
newStringstring
replaceAll?booleanReplace every occurrence (default false).

EnableAiOptions

Options for enableAi and ai.

interface EnableAiOptions {
    connect: (panel: AiPanelContext) => AiChatHandlers;
    language?: string;
    title?: string;
    emptyTitle?: string;
    emptyDescription?: string;
    suggestions?: readonly string[];
    placeholder?: string;
    highlight?: AiChatProps['highlight'];
    models?: readonly AiModel[];
    model?: string;
    modelLogo?: AiChatProps['modelLogo'];
    onModelChange?: (id: string, ctx: WidgetContext) => void;
    promptTools?: (ctx: WidgetContext) => HTMLElement;
    renderPart?: AiChatProps['renderPart'];
    width?: number;
    order?: number;
}
MemberTypeDescription
connect(panel: AiPanelContext) => AiChatHandlersConnect a shell's chat to the host's conversation. Called once per shell. The host creates its chat state here (its model calls, its tools over helpers), draws it with chat.update({ messages, status, error }) whenever it changes, and returns what to do when the user sends, stops or starts over.
language?stringThe key of the engine the script helpers write for, and read from (default 'pine').
title?stringThe panel's title, and its rail button's tooltip (default 'AI').
emptyTitle?stringWhat an empty conversation says.
emptyDescription?string
suggestions?readonly string[]Prompts offered while the conversation is empty.
placeholder?string
highlight?AiChatProps['highlight']Highlights the code blocks of a reply.
models?readonly AiModel[]The models the user can pick from. With any, a picker sits in the prompt's footer, and chat.model is the id picked. Without any, there is no picker.
model?stringThe id of the model picked to start with (default: the first of models). A choice the user made persists over it.
modelLogo?AiChatProps['modelLogo']The logo of a model's maker or of a service, by its key: an address, an element, or null for the key's initial.
onModelChange?(id: string, ctx: WidgetContext) => voidCalled when the user picks a model.
promptTools?(ctx: WidgetContext) => HTMLElementA control of the host's in the prompt's footer, built per shell.
renderPart?AiChatProps['renderPart']Draws a part of a message the host's way: see AiChatProps.renderPart.
width?number
order?numberPlace among the sidebar panel buttons (default 6).

See also: AiChatHandlers, AiChatProps, AiModel, AiPanelContext. From @luxalgo/vela/plugin: WidgetContext.

JsonSchema

The JSON Schema subset the helpers' inputs are written in: what a model API takes as a tool's parameters. Its arrays are plain arrays so a schema passes where JSON Schema's own type is asked for (the AI SDK's jsonSchema()).

interface JsonSchema {
    type?: 'object' | 'array' | 'string' | 'number' | 'integer' | 'boolean';
    description?: string;
    properties?: Record<string, JsonSchema>;
    required?: string[];
    additionalProperties?: boolean;
    items?: JsonSchema;
    enum?: Array<string | number>;
    minimum?: number;
    maximum?: number;
    minLength?: number;
    maxLength?: number;
    minItems?: number;
    maxItems?: number;
}
MemberTypeDescription
type?'object' | 'array' | 'string' | 'number' | 'integer' | 'boolean'Absent: any JSON value.
description?string
properties?Record<string, JsonSchema>
required?string[]
additionalProperties?boolean
items?JsonSchema
enum?Array<string | number>
minimum?number
maximum?number
minLength?number
maxLength?number
minItems?number
maxItems?number

MarkUpChartInput

interface MarkUpChartInput extends OnChart {
    concepts?: readonly MarkupRequest[];
    replace?: boolean;
    clear?: ReadonlyArray<MarkupConcept | 'all'>;
}

// Unexported supporting type referenced above
interface OnChart {
    slot?: number;
}
MemberTypeDescription
concepts?readonly MarkupRequest[]The concepts to mark, each with its options.
replace?booleanRemove the earlier markup of the same concepts first (default true), so a redraw never stacks.
clear?ReadonlyArray<MarkupConcept | 'all'>Markups to take off the chart, by concept, or ['all']. Can be sent alone.

See also: MarkupConcept, MarkupRequest.

MarkupConcept

type MarkupConcept = (typeof MARKUP_CONCEPTS)[number];

See also: MARKUP_CONCEPTS.

MarkupRequest

One concept to mark, with the options that apply to it.

interface MarkupRequest {
    concept: MarkupConcept;
    count?: number;
    direction?: 'bullish' | 'bearish' | 'both';
    mitigation?: 'full' | 'ce';
    includeMitigated?: boolean;
    inversions?: boolean;
    includeSwept?: boolean;
    strength?: number;
    breakers?: boolean;
    ote?: boolean;
    quarters?: boolean;
    high?: number;
    low?: number;
    leg?: 'up' | 'down';
    extensions?: number[];
    gapKind?: 'week' | 'day' | 'both';
    only?: string[];
    windows?: Array<{ name: string; start: string; end: string }>;
    days?: number;
    levels?: Array<(typeof KEY_LEVEL_KINDS)[number]>;
}

See also: KEY_LEVEL_KINDS, MarkupConcept.

ReadChartDataInput

interface ReadChartDataInput extends OnChart {
    kind: 'bars' | 'plots' | 'trades' | 'inputs' | 'visible_range';
    count?: number;
    from?: string | number;
    to?: string | number;
    scriptId?: string;
    plots?: readonly string[];
}

// Unexported supporting type referenced above
interface OnChart {
    slot?: number;
}
MemberTypeDescription
kind'bars' | 'plots' | 'trades' | 'inputs' | 'visible_range'The chart's price bars, a script's plotted values, a strategy's trades, an indicator's settings, or the time window in view.
count?numberbars / plots: how many rows, the latest ones (default 100).
from?string | numberbars / plots: a time window, ISO 8601 (UTC) or epoch milliseconds.
to?string | number
scriptId?stringplots / trades / inputs: the indicator, by the id the chart holds it under.
plots?readonly string[]plots: the plot names to read (default: all).

ReadScriptInput

interface ReadScriptInput extends OnChart {
    id: string;
    startLine?: number;
    endLine?: number;
}

// Unexported supporting type referenced above
interface OnChart {
    slot?: number;
}
MemberTypeDescription
idstring
startLine?numberFirst line to return (1 = the first line). Default: the first.
endLine?numberLast line to return. Default: the last.

RemoveScriptInput

interface RemoveScriptInput extends OnChart {
    id: string;
}

// Unexported supporting type referenced above
interface OnChart {
    slot?: number;
}
MemberTypeDescription
idstringA script or a built-in indicator, by the id the chart holds it under.

SetChartStateInput

interface SetChartStateInput {
    charts: readonly ChartStatePatch[];
}
MemberTypeDescription
chartsreadonly ChartStatePatch[]One entry per chart to change.

See also: ChartStatePatch.

SetScriptInputsInput

interface SetScriptInputsInput extends OnChart {
    id: string;
    inputs: ReadonlyArray<{ name: string; value: AiInputValue }>;
}

// Unexported supporting type referenced above
interface OnChart {
    slot?: number;
}
MemberTypeDescription
idstring
inputsReadonlyArray<{ name: string; value: AiInputValue }>Each setting by the title its dialog shows, or its key, with its new value.

See also: AiInputValue.

WriteScriptInput

interface WriteScriptInput extends OnChart {
    code: string;
    id?: string;
}

// Unexported supporting type referenced above
interface OnChart {
    slot?: number;
}
MemberTypeDescription
codestringThe complete source of the script.
id?stringThe id of a script on the chart to overwrite in place. Absent: a new script is added.

Constants

AI_HELPER_NAMES

Every helper, by name.

const AI_HELPER_NAMES: readonly ('markUpChart' | 'writeScript' | 'editScript' | 'readScript' | 'removeScript' | 'setScriptInputs' | 'addIndicator' | 'readChart' | 'setChartState' | 'captureChartScreenshot' | 'readChartData')[];

AI_HELPER_SCHEMAS

The JSON Schema of each helper's input: what the helper checks an input against, and what a host can hand its model as the parameters of the tool that calls the helper.

const AI_HELPER_SCHEMAS: Readonly<Record<AiHelperName, JsonSchema>>;

See also: AiHelperName, JsonSchema.

AI_INSTRUCTIONS

A system prompt to start from, for a model that works the chart through tools built on the helpers. It names no tool: add what yours are called. The module sends it nowhere: the host's code builds its own requests.

const AI_INSTRUCTIONS: string;

AI_NATIVE_TYPE

The native every chart the agent reads bars from carries: no legend row, no output, never in a picker.

const AI_NATIVE_TYPE: 'vela-pro.ai';

AI_PANEL_ID

const AI_PANEL_ID: 'vela-pro.ai';

KEY_LEVEL_KINDS

const KEY_LEVEL_KINDS: readonly ['previous-day', 'previous-week', 'midnight-open', 'sessions'];

MARKUP_CONCEPTS

const MARKUP_CONCEPTS: readonly ['fair_value_gaps', 'liquidity', 'market_structure', 'order_blocks', 'dealing_range', 'opening_gaps', 'killzones', 'macros', 'key_levels', 'support_resistance', 'trendlines', 'pattern', 'range'];

On this page