# Custom modules (/vela-pro/modules/extending/custom-modules)



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`.

```ts
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 [#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](/vela-pro/modules/extending/custom-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 the `ctx.plugins` registry containing `TradingApi`, `AlertsApi`, and custom module APIs.
* **Dependency ordering and validation:** Modules declaring `requires` are 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 through `ctx.plugins.get(id)`.

## Plugin descriptor [#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 [#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 [#required-vs-optional-dependencies]

Choose between hard and optional dependencies based on whether your module can function standalone:

* **Hard dependency (`requires`):** Use `requires: ['trading']` when your module cannot operate without the target module. Vela Pro installs the dependency first so `ctx.plugins.get('trading')` is guaranteed to be defined immediately inside `install`. If the dependency is missing from `enableVelaPro()`, your module is skipped and a console error logs the missing requirement.
* **Optional integration (lazy lookup):** Omit `requires` when your module provides standalone value and only enhances its UI when another module is present. Resolve `ctx.plugins.get(...)` lazily inside `mount` or event handlers rather than at the top of `install`; by the time `mount` executes, 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 [#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.

```ts
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 `definePlugin` in `exposure(opts)` matches built-in modules (`trading(opts)`, `journal(opts)`), enabling `plugins: [exposure({ warnAbove: 50_000 })]`.
* **Lazy peer lookup:** Resolving `ctx.plugins.get('trading')` inside `mount` makes the module independent of array ordering and resilient when Trading is omitted.
* **Safety-aware execution:** Calling `api.closePosition(p.symbol)` routes through `TradingApi`, preserving kill-switch enforcement and standard error notifications.
* **API return value:** Returning `{ total }` from `install` registers that object under `'acme.exposure'` in `ctx.plugins`. Modules without a public API can return `void`.

## Exposing a module API [#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:

```ts
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 [#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.

```ts
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 [#related]

* [Custom panels and widgets](/vela-pro/modules/extending/custom-widgets)
* [Plugin state](/vela-pro/persistence/stores/plugin-state)
* [Widget attachments](/vela/contributing/plugin-sdk#widget-attachments--registerwidgetattachment) in the plugin SDK of Vela's open-source core
* [API reference: Module SDK](/vela-pro/api/module-sdk)
