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

Broker integration

Implement the Broker port interface to connect order execution, account state streaming, position management, and multi-account switching to your brokerage.

View as Markdown

The Trading module communicates with your execution backend through a single Broker interface. Once you pass a Broker implementation to trading({ broker }), chart overlays, the order ticket, the bottom-dock trading panel, DOM ladder click-trading, and the Journal module all operate against your live account.

Every UI surface reads account data synchronously from state(), which returns a cached in-memory snapshot maintained by your adapter, and subscribes to updates via subscribe(listener). User actions invoke asynchronous methods (placeOrder, modifyOrder, cancelOrder, closePosition), and any rejected Promise surfaces its error message directly in the UI.

See Orders, positions, and brackets for definitions of all domain types referenced below.

The Broker interface

MemberRequiredContract
infoYes{ id, name, paper } metadata displayed in account headers and menus.
capabilitiesYesSupported order types, times in force, and execution flags that configure the order ticket UI.
state()YesSynchronous getter returning the cached BrokerState (account, positions, orders, history, fills, trades).
subscribe(listener)YesRegisters a change callback invoked after state() updates. Returns an unsubscribe function.
placeOrder(request)YesSubmits a new order and resolves once accepted by your API.
modifyOrder(orderId, patch)YesUpdates a live order's qty, limitPrice, or stopPrice.
cancelOrder(orderId)YesCancels a live order by ID.
closePosition(symbol, qty?)YesCloses the full open position for symbol, or qty units when specified.
reversePosition(symbol)NoReverses an open position. When omitted, the UI hides Reverse actions.
accountsNoBrokerAccounts adapter enabling multi-account listing and switching.
onPrice(symbol, price, time)NoReceives live chart prices so brokers without server-side mark streams can mark open positions.
setKillSwitch(on)NoDelegates kill-switch enforcement to your server. When omitted, Vela Pro blocks new orders client-side and cancels working orders individually.
reset()NoSimulator-only hook. Defining it adds a "Reset paper account…" entry to the trading panel settings menu.
destroy()NoOptional cleanup method for your own lifecycle management (not called automatically by Vela Pro).

Always set paper: false in info for live brokerage accounts. Vela Pro treats any account whose paper property is not strictly false as simulated, displaying a Paper badge and using simulated-account wording in confirmation dialogs.

Minimal implementation

Start with a minimal Broker object implementing every required member with empty state and rejected action stubs. Mounting this stub verifies that your account name renders in the trading panel and that rejected promises surface error banners as expected.

import type { Broker, BrokerState } from '@luxalgo/vela-pro-trading';

const empty: BrokerState = {
    account: { currency: 'USD', balance: 0, equity: 0, unrealizedPnl: 0, realizedPnl: 0 },
    positions: [],
    orders: [],
    history: [],
    fills: [],
    trades: [],
};

const notYet = (): Promise<void> => Promise.reject(new Error('Trading is not connected yet.'));

export const broker: Broker = {
    info: { id: 'acme', name: 'ACME Live', paper: false },
    capabilities: { orderTypes: ['market', 'limit', 'stop'], brackets: true, modify: true, reverse: false },
    state: () => empty,
    subscribe: () => () => {},
    placeOrder: notYet,
    modifyOrder: notYet,
    cancelOrder: notYet,
    closePosition: notYet,
};

The sections below implement each slice of Broker independently with Pick<Broker, ...> so TypeScript validates every group against the port contract.

Order submission

Implement placeOrder, modifyOrder, and cancelOrder to forward user requests to your REST or WebSocket API. Resolve when the broker accepts the request, and reject with a descriptive Error message when validation or execution fails, because Vela Pro displays error.message directly to the user.

import type { Broker } from '@luxalgo/vela-pro-trading';

/** Sends an authenticated request to your trading API and rejects with the server's error text on failure. */
export async function send(method: 'POST' | 'PATCH' | 'DELETE', path: string, body?: unknown): Promise<void> {
    const res = await fetch(`https://api.acme.example/v1${path}`, {
        method,
        credentials: 'include',
        headers: { 'content-type': 'application/json' },
        ...(body === undefined ? {} : { body: JSON.stringify(body) }),
    });
    if (!res.ok) throw new Error((await res.text()) || `ACME refused the request (${res.status}).`);
}

/** Converts a chart symbol (`BTCUSDT` or `acme:BTCUSDT`) into your venue's instrument identifier. */
const instrumentOf = (symbol: string): string => symbol.slice(symbol.indexOf(':') + 1).toUpperCase();

export const orders: Pick<Broker, 'placeOrder' | 'modifyOrder' | 'cancelOrder'> = {
    placeOrder: (request) => send('POST', '/orders', { ...request, instrument: instrumentOf(request.symbol) }),
    modifyOrder: (orderId, patch) => send('PATCH', `/orders/${encodeURIComponent(orderId)}`, patch),
    cancelOrder: (orderId) => send('DELETE', `/orders/${encodeURIComponent(orderId)}`),
};

Outgoing OrderRequest payloads follow normalized conventions:

  • Resolved units and prices: Quantities are always expressed in base instrument units and exits are always absolute prices. Currency, equity-percentage, and risk-based sizing, as well as percentage, tick, ATR, and currency exit offsets, are resolved client-side before placeOrder runs.
  • Inline bracket exits: Entry requests may include takeProfit and stopLoss prices that remain held until the entry fills and then act as an OCO pair. If your venue lacks native bracket orders, submit the child exits from your adapter or server once the parent entry fills.
  • Standalone exits: Exits added after entry arrive as individual placeOrder calls with role set to 'take-profit' or 'stop-loss'. Exits attached to a working entry carry parentId, while exits protecting an open position carry reduceOnly: true.
  • Capability-filtered flags: timeInForce, postOnly, and extendedHours appear only when enabled in capabilities. Apply your venue's default time in force if request.timeInForce is undefined.
  • Consistent symbol spelling: Requests pass symbol exactly as formatted on the chart. Translate it to your venue's instrument ID when sending requests, and translate back to the chart's exact symbol string when populating BrokerState so chart overlays match active symbols.
  • Order amendments: Dragging an order line on the chart invokes modifyOrder. If your venue does not support atomic in-place amendments, implement cancel-and-replace inside modifyOrder.

Order methods resolve to void. Newly placed or modified orders appear in the UI as soon as state() includes them and subscribe listeners fire.

State updates

subscribe is the single notification channel from your Broker to Vela Pro. Maintain a local BrokerState snapshot, apply incoming REST or WebSocket updates to it, and invoke all registered listeners so the UI re-reads state().

If your backend broadcasts full account snapshots on each event, replace snapshot directly. If your stream emits incremental domain events, reduce them into the current BrokerState:

import type { AccountSummary, BrokerState, ClosedTrade, Fill, Order, Position } from '@luxalgo/vela-pro-trading';

/** Incremental account stream events mapped to Vela Pro domain types. */
export type AccountEvent =
    | { type: 'account'; account: AccountSummary }
    | { type: 'order'; order: Order }
    | { type: 'position'; symbol: string; position: Position | null }
    | { type: 'fill'; fill: Fill }
    | { type: 'trade'; trade: ClosedTrade };

const LIVE = new Set<Order['status']>(['pending', 'working', 'held']);

export function applyEvent(state: BrokerState, event: AccountEvent): BrokerState {
    switch (event.type) {
        case 'account':
            return { ...state, account: event.account };
        case 'order': {
            const others = state.orders.filter((o) => o.id !== event.order.id);
            // Terminal orders move from `orders` into `history` (newest first).
            return LIVE.has(event.order.status)
                ? { ...state, orders: [event.order, ...others] }
                : { ...state, orders: others, history: [event.order, ...state.history] };
        }
        case 'position': {
            const others = state.positions.filter((p) => p.symbol !== event.symbol);
            return { ...state, positions: event.position ? [...others, event.position] : others };
        }
        case 'fill':
            return { ...state, fills: [event.fill, ...state.fills] };
        case 'trade':
            return { ...state, trades: [event.trade, ...state.trades] };
    }
}

Fetch an initial snapshot on connection (and on every reconnect) so missed socket frames never leave stale orders on screen:

import type { Broker, BrokerState } from '@luxalgo/vela-pro-trading';

declare const empty: BrokerState;
declare function applyEvent(state: BrokerState, event: unknown): BrokerState;

export function accountFeed(base: string): Pick<Broker, 'state' | 'subscribe'> & { reload(): Promise<void> } {
    let snapshot = empty;
    const listeners = new Set<() => void>();
    const publish = (next: BrokerState): void => {
        snapshot = next;
        for (const listener of listeners) listener();
    };
    const reload = async (): Promise<void> => {
        const res = await fetch(`${base}/account`, { credentials: 'include' });
        if (res.ok) publish((await res.json()) as BrokerState);
    };

    const connect = (): void => {
        const socket = new WebSocket(`${base.replace(/^http/, 'ws')}/account/events`);
        socket.onopen = () => void reload(); // resync full state on initial connect and reconnect
        socket.onmessage = (message) => publish(applyEvent(snapshot, JSON.parse(String(message.data))));
        socket.onclose = () => setTimeout(connect, 2_000);
    };
    connect();

    return {
        state: () => snapshot,
        subscribe: (listener) => {
            listeners.add(listener);
            return () => listeners.delete(listener);
        },
        reload,
    };
}

Keep three state invariants in mind when mapping events:

  • Partial fills: Keep partially executed orders in state().orders with status: 'working' and filledQty updated, while appending each individual execution to state().fills.
  • Immutable fill IDs: Assign deterministic, permanent IDs to Fill records. The Journal module deduplicates synchronized executions by fill.id.
  • Closed round trips: Populate state().trades from your server or derive them from fills, because trades drives the Trades tab, chart trade paths, and the maxDailyLoss risk check.

If your venue accepts order submissions asynchronously before exchange acknowledgment, emit the order initially with status: 'pending' so the chart renders it at reduced opacity until it becomes 'working'.

Position management

Report at most one net Position per symbol in state().positions using a signed qty (positive for long, negative for short). Pass server-computed markPrice and unrealizedPnl when available, or implement onPrice(symbol, price, time) to recompute unrealized PnL from live chart ticks.

Implement closePosition (required) and optionally reversePosition:

import type { Broker } from '@luxalgo/vela-pro-trading';

declare function send(method: 'POST', path: string, body?: unknown): Promise<void>;

export const positions: Pick<Broker, 'closePosition' | 'reversePosition'> = {
    // Omit `qty` in the request body when closing the entire position.
    closePosition: (symbol, qty) => send('POST', `/positions/${encodeURIComponent(symbol)}/close`, qty === undefined ? {} : { qty }),
    reversePosition: (symbol) => send('POST', `/positions/${encodeURIComponent(symbol)}/reverse`),
};

Multiple accounts

Provide accounts (BrokerAccounts) when users can trade across multiple sub-accounts. Defining accounts turns the account name in the trading panel header into a dropdown switcher.

import type { BrokerAccount, BrokerAccounts } from '@luxalgo/vela-pro-trading';

const API = 'https://api.acme.example/v1';

/** Reloads the broker snapshot and notifies subscribers after switching accounts. */
export async function loadAccounts(onSwitch: () => Promise<void>): Promise<BrokerAccounts> {
    const res = await fetch(`${API}/accounts`, { credentials: 'include' });
    if (!res.ok) throw new Error(`Accounts: HTTP ${res.status}`);
    const loaded = (await res.json()) as { accounts: BrokerAccount[]; active: string };
    let active = loaded.active;

    return {
        list: () => loaded.accounts,
        activeId: () => active,
        switchTo: async (id) => {
            const answer = await fetch(`${API}/accounts/${encodeURIComponent(id)}/activate`, { method: 'POST', credentials: 'include' });
            if (!answer.ok) throw new Error('This account cannot be opened right now.');
            active = id;
            await onSwitch();
        },
    };
}

Because list() and activeId() are synchronous, prefetch the account list before constructing the broker (const accounts = await loadAccounts(() => feed.reload())). Before switchTo resolves, ensure info and state() reflect the newly selected account and that subscribe listeners have been notified.

BrokerAccounts also declares optional create, rename, reset, and remove methods. Those methods render simulator-specific menu items (such as "New paper account…"), so omit them on live brokerage adapters.

Registration

Combine the slices into a Broker implementation and pass it to trading():

import { enableVelaPro } from '@luxalgo/vela-pro';
import { trading, type Broker, type BrokerAccounts, type BrokerCapabilities, type BrokerInfo } from '@luxalgo/vela-pro-trading';

// Slices implemented in the sections above.
declare const feed: Pick<Broker, 'state' | 'subscribe'>;
declare const orders: Pick<Broker, 'placeOrder' | 'modifyOrder' | 'cancelOrder'>;
declare const positions: Pick<Broker, 'closePosition' | 'reversePosition'>;
declare const accounts: BrokerAccounts;

class MyBroker implements Broker {
    readonly capabilities: BrokerCapabilities = {
        orderTypes: ['market', 'limit', 'stop'],
        brackets: true,
        modify: true,
        reverse: true,
        timeInForce: ['gtc', 'day', 'ioc'], // first entry is the default
    };
    readonly accounts = accounts;
    readonly state = feed.state;
    readonly subscribe = feed.subscribe;
    readonly placeOrder = orders.placeOrder;
    readonly modifyOrder = orders.modifyOrder;
    readonly cancelOrder = orders.cancelOrder;
    readonly closePosition = positions.closePosition;
    readonly reversePosition = positions.reversePosition;

    /** Dynamic getter so `info` tracks the currently active sub-account. */
    get info(): BrokerInfo {
        const active = accounts.list().find((a) => a.id === accounts.activeId());
        return { id: `acme:${accounts.activeId()}`, name: active?.name ?? 'ACME', paper: false };
    }
}

enableVelaPro({ plugins: [trading({ broker: new MyBroker() })] });

Client-side safety controls (kill switch, risk limits, and order confirmation) run before requests reach MyBroker, complementing your backend's own margin and risk checks.

Integration checklist

Unlike PaperBroker, which fills immediately and never drops connections, a live brokerage adapter must handle asynchronous rejections, partial fills, and network disconnects. Verify each scenario below across the chart, trading panel, and DOM ladder:

ScenarioAdapter behaviorExpected UI result
Synchronous order rejectionplaceOrder rejects with an ErrorError notification displays your message; no order line remains on the chart.
Asynchronous exchange rejectionStream emits the order with status: 'rejected' and reasonOrder line disappears from the chart and appears under Rejected in order history.
Rejected order modificationmodifyOrder rejects with an ErrorError notification appears and the dragged chart line snaps back to the broker's price.
Partial executionOrder stays 'working' with incremented filledQty, Fill appended, Position updatedPosition shows filled size while the working order line shows remaining unfilled quantity.
Bracket lifecycleExits start 'held', become 'working' on entry fill, and cancel the OCO sibling on exit fillFaint exit lines turn solid when the entry fills and clear completely once either exit fills.
Late cancellation racecancelOrder rejects because the order already filledError notification appears alongside the resulting fill and updated position.
Stream disconnect and recoveryAction methods reject clearly while offline; reload() replaces full BrokerState on reconnectStale working orders are cleared as soon as the resync snapshot arrives.
Sub-account switchUpdates info and state(), then invokes subscribe listenersAccount header, balances, working orders, and chart overlays switch to the selected account.

Broker does not include a separate connection-status field. While your transport is disconnected, reject outgoing action promises with a clear offline message and reload the full BrokerState immediately upon reconnection.

On this page