Custom modules
Author custom Vela Pro modules with definePlugin, declare module dependencies, consume TradingApi and AlertsApi, and expose typed module APIs.
Custom modules install alongside Vela Pro's built-in modules in enableVelaPro({ plugins }), participating in dependency resolution and inter-module API discovery. You author a custom module with definePlugin from @luxalgo/vela-pro/plugin.
import { enableVelaPro } from '@luxalgo/vela-pro';
import { definePlugin } from '@luxalgo/vela-pro/plugin';
import { trading } from '@luxalgo/vela-pro-trading';
const exposureReport = definePlugin({
id: 'acme.exposure-report',
requires: ['trading'],
install: (ctx) => {
const account = ctx.plugins.get('trading')!; // typed as TradingApi
account.onChange(() => {
const open = account.state().positions.map((p) => ({ symbol: p.symbol, qty: p.qty }));
void fetch('/api/exposure', { method: 'POST', body: JSON.stringify(open) });
});
},
});
enableVelaPro({ plugins: [trading(), exposureReport] });When to write a module
Registering a standalone side panel, bottom dock panel, or side rail button does not require a module; you can call those registration functions directly before constructing a workspace as shown in Custom panels and widgets. Wrap your code in definePlugin when you need one or more of the following capabilities:
- Access to peer module APIs: Only
install(ctx)receives thectx.pluginsregistry containingTradingApi,AlertsApi, and custom module APIs. - Dependency ordering and validation: Modules declaring
requiresare guaranteed to install after their dependencies and are skipped automatically if a required module is absent. - Exporting a typed runtime API:
install(ctx)can return an API object that other modules look up by ID throughctx.plugins.get(id).
Plugin descriptor
A module descriptor contains three properties:
| Property | Description |
|---|---|
id | Unique module identifier on the page. Vela Pro reserves 'alerts', 'watchlist', 'dom', 'trading', 'journal', and 'calendar'. Prefix custom module IDs with your organization namespace (such as 'acme.exposure'). |
requires | Optional array of module IDs that must be installed before this module. |
install(ctx) | Initialization callback invoked once by enableVelaPro() before workspaces are constructed. Its return value becomes the module's public API in ctx.plugins. |
definePlugin(descriptor) is an identity helper that preserves type inference for the API returned by install.
Inside install, register side panels, bottom panels, rail items, widget actions, and state serializers. Because install runs before any VelaWorkspace exists, avoid building DOM trees eagerly inside install; create per-workspace DOM inside the mount callbacks you register.
Only enableVelaPro() invokes install, and each module ID is installed at most once per page. Subsequent calls to enableVelaPro() skip modules that are already installed.
Accessing other module APIs
ctx.plugins provides typed lookup over installed modules:
| Method | Return value |
|---|---|
ctx.plugins.get('trading') | TradingApi when Trading is installed, or undefined |
ctx.plugins.get('alerts') | AlertsApi when Alerts is installed, or undefined |
ctx.plugins.get<T>(id) | Custom module API typed as T, or undefined |
ctx.plugins.has(id) | true when the module with id is installed |
TradingApi and AlertsApi are declared directly in @luxalgo/vela-pro/plugin, allowing your module to interact with Trading or Alerts without adding a package dependency on @luxalgo/vela-pro-trading or @luxalgo/vela-pro-alerts.
TradingApi member | Description |
|---|---|
state() | Returns working orders, open positions (with signed qty), and account currency. |
onChange(listener) | Invokes listener after every state() update and returns an unsubscribe function. |
trade(symbol, side, opts?) | Initiates an order via the order panel or submits immediately when oneClick is enabled (opts accepts price and qty). |
cancelOrder(orderId), cancelAll(symbol?) | Cancels one working order or all working orders, resolving false if rejected. |
closePosition(symbol, qty?) | Closes an open position (or qty units) at market. |
AlertsApi exposes open(ctx, init), which opens the alert creation dialog on ctx seeded with { symbol, price? }.
Required vs. optional dependencies
Choose between hard and optional dependencies based on whether your module can function standalone:
- Hard dependency (
requires): Userequires: ['trading']when your module cannot operate without the target module. Vela Pro installs the dependency first soctx.plugins.get('trading')is guaranteed to be defined immediately insideinstall. If the dependency is missing fromenableVelaPro(), your module is skipped and a console error logs the missing requirement. - Optional integration (lazy lookup): Omit
requireswhen your module provides standalone value and only enhances its UI when another module is present. Resolvectx.plugins.get(...)lazily insidemountor event handlers rather than at the top ofinstall; by the timemountexecutes, all registered modules have finished installing regardless of array order. Vela Pro's Order Book uses this pattern to enable DOM click-trading when Trading is present while remaining usable read-only without it.
Full example
The module below registers an Exposure bottom-dock panel that lists open positions with per-symbol close buttons, highlights exposure breaches above a configurable threshold, degrades gracefully when Trading is not installed, and exports an ExposureApi for other modules.
import { registerIcon } from '@luxalgo/vela/plugin';
import { registerBottomPanel } from '@luxalgo/vela-pro';
import { definePlugin, type TradingApi } from '@luxalgo/vela-pro/plugin';
export interface ExposureApi {
/** Sum of open position notionals valued at average entry price. */
total(): number;
}
/** `warnAbove` sets the notional threshold that sets `data-warn` on the panel body. */
export function exposure(opts: { warnAbove?: number } = {}) {
return definePlugin<ExposureApi>({
id: 'acme.exposure',
install: (ctx) => {
// Resolve lazily so all modules in `plugins` have finished installing.
const account = (): TradingApi | undefined => ctx.plugins.get('trading');
const total = (): number => (account()?.state().positions ?? []).reduce((sum, p) => sum + Math.abs(p.qty) * p.avgPrice, 0);
registerIcon('acme-exposure', '<svg viewBox="0 0 16 16" fill="none" stroke="currentColor"><path d="M2.5 13.5h11M4.5 11V7M8 11V3.5M11.5 11V8.5"/></svg>');
registerBottomPanel({
id: 'acme.exposure',
title: 'Exposure',
icon: 'acme-exposure',
mount: (_ctx, body, header) => {
const render = (): void => {
const api = account();
if (!api) {
body.textContent = 'Add the trading module to see your exposure.';
return;
}
const rows = api.state().positions.map((p) => {
const row = document.createElement('button');
row.textContent = `Close ${p.symbol} (${p.qty} at ${p.avgPrice})`;
row.onclick = () => void api.closePosition(p.symbol);
return row;
});
body.replaceChildren(...rows);
header.setCount(rows.length || null);
body.toggleAttribute('data-warn', total() > (opts.warnAbove ?? Infinity));
};
render();
return { destroy: account()?.onChange(render) };
},
});
return { total };
},
});
}Design notes for this pattern:
- Factory function for options: Wrapping
definePlugininexposure(opts)matches built-in modules (trading(opts),journal(opts)), enablingplugins: [exposure({ warnAbove: 50_000 })]. - Lazy peer lookup: Resolving
ctx.plugins.get('trading')insidemountmakes the module independent of array ordering and resilient when Trading is omitted. - Safety-aware execution: Calling
api.closePosition(p.symbol)routes throughTradingApi, preserving kill-switch enforcement and standard error notifications. - API return value: Returning
{ total }frominstallregisters that object under'acme.exposure'inctx.plugins. Modules without a public API can returnvoid.
Exposing a module API
Downstream modules consume a custom API by passing its interface type to ctx.plugins.get<T>(id). Declaring requires: ['acme.exposure'] guarantees that 'acme.exposure' is installed before 'acme.margin-check' runs:
import { definePlugin } from '@luxalgo/vela-pro/plugin';
interface ExposureApi {
total(): number;
}
export const marginCheck = definePlugin({
id: 'acme.margin-check',
requires: ['acme.exposure'],
install: (ctx) => {
const exposure = ctx.plugins.get<ExposureApi>('acme.exposure')!;
setInterval(() => {
if (exposure.total() > 100_000) console.warn('Exposure is above the margin threshold.');
}, 60_000);
},
});Communicating through ctx.plugins instead of direct module imports keeps packages decoupled so any module can be omitted or replaced independently.
Registration
Pass custom modules alongside built-in modules in the plugins array of enableVelaPro(). Vela Pro topologically sorts modules based on requires, so array order between dependent modules does not matter.
import { enableVelaPro } from '@luxalgo/vela-pro';
import type { VelaProPlugin } from '@luxalgo/vela-pro/plugin';
import { trading } from '@luxalgo/vela-pro-trading';
declare const exposure: (opts?: { warnAbove?: number }) => VelaProPlugin;
declare const marginCheck: VelaProPlugin;
enableVelaPro({ plugins: [marginCheck, exposure({ warnAbove: 50_000 }), trading()] });If a module cannot be installed, enableVelaPro() logs a console error prefixed with [vela-pro]:
| Console error | Cause |
|---|---|
"acme.margin-check" needs "acme.exposure", which is not installed | A required dependency is missing. Both this module and any modules requiring it are skipped. |
"acme.exposure" is listed twice; the first one is kept. | Duplicate module IDs were passed in plugins. |
"acme.a" requires itself through acme.b and was not installed. | Circular dependency detected across requires declarations. |
Related
- Custom panels and widgets
- Plugin state
- Widget attachments in the plugin SDK of Vela's open-source core
- API reference: Module SDK
Custom panels and widgets
Register custom side panels, bottom dock panels, and side rail actions in a Vela Pro workspace using reusable widget components.
Theming and branding
Configure chart and panel themes, override panel styles with CSS tokens and data-part selectors, and customize the corner attribution mark.