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

Overview

Enable chart trading, configure the order ticket, trading dock, display layer, and paper broker, and submit or manage orders from code.

View as Markdown

The Trading module adds interactive order entry, position management, and execution overlays to Vela Pro workspaces. It is an opt-in module (@luxalgo/vela-pro-trading) built around a single Broker port interface, defaulting to a client-side PaperBroker simulator unless you pass a live brokerage adapter.

Key features include:

  • Interactive chart overlays for working orders, open positions, execution markers, and closed-trade paths. Users can drag working order lines to amend prices, drag take-profit or stop-loss grips directly from an entry order or open position, and close, partially close, or reverse a position from its chart label.
  • Floating Buy/Sell buttons with an inline order quantity control beneath each chart's status line.
  • Context-menu and keyboard execution to buy or sell at the pointer price from the chart right-click menu or trigger Shift+B and Shift+S on the active chart.
  • An order ticket side panel (vela-pro.order) for configuring side, order type (market, limit, stop), time in force, quantity, take profit, stop loss, and reusable presets with live chart previews.
  • A trading account panel (vela-pro.trading) in the bottom dock with account switching, open positions, working orders, order history, and closed trades.
  • Pre-trade safety controls including order confirmation dialogs, configurable risk limits, and a kill switch that blocks new orders and cancels working orders.
  • A mobile Trade button in the bottom bar that opens the order ticket and trading panel inside a bottom sheet.

See Installation for adding @luxalgo/vela-pro-trading to your project, then pass trading() in the plugins array of enableVelaPro():

import { VelaWorkspace } from '@luxalgo/vela/workspace';
import { BinanceProvider } from '@luxalgo/vela/providers/binance';
import { enableVelaPro } from '@luxalgo/vela-pro';
import { trading } from '@luxalgo/vela-pro-trading';

enableVelaPro({ plugins: [trading()] });

const workspace = new VelaWorkspace('#chart', {
    layout: false,
    symbol: 'BTCUSDT',
    timeframe: '60',
    live: true,
    providers: { binance: () => new BinanceProvider() },
    persist: true,
});

Trading requires live market data. The module renders trading overlays and forwards prices only on charts initialized with live: true, and suppresses trading overlays during bar replay so historical prices never trigger live or paper executions.

The paper broker

When you omit the broker option, the module creates a PaperBroker instance that simulates executions in the browser against live chart prices:

  • Market orders fill at the latest chart price, limit orders fill at their limit price once reached, stop orders fill at market once triggered, and stop-limit orders become resting limit orders once triggered.
  • Positions are netted per symbol, and realized profit and loss is credited to the account balance on each closing fill.
  • Bracket take-profit and stop-loss orders remain held until their parent entry fills, then activate as a linked OCO pair.
  • Supports four times in force (gtc, day, ioc, fok) and postOnly limit orders.
  • Supports multiple simulated accounts persisted in localStorage, each with independent balances and trade history.

Customize the simulator with the paper option:

OptionDefaultDescription
initialBalance100000Starting cash balance for the initial paper account.
currency'USD'Account currency code for the initial paper account.
commissionRate0Execution fee as a fraction of notional value (for example, 0.0004 equals 4 basis points).
persist'vela-pro.paper'localStorage key used to save paper accounts, or false for in-memory storage only.
name'Paper Trading'Display name of the initial paper account.

These options initialize the starter account when storage is empty. Once paper accounts have been saved in localStorage, the saved accounts are restored instead. Users can create, rename, reset, and delete paper accounts from the account menu in the trading panel.

To execute against a live brokerage, implement the Broker interface as described in Broker integration.

Configuration

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

enableVelaPro({
    plugins: [
        trading({
            paper: { initialBalance: 25_000, commissionRate: 0.0004 },
            defaultQty: 0.1,
            qtyPresets: [0.01, 0.05, 0.1, 0.5, 1],
            safety: { askBeforePlacing: true, limits: { maxOrderValue: 5_000, maxDailyLoss: 500 } },
            presets: [
                {
                    id: 'scalp',
                    name: 'Scalp',
                    size: { mode: 'usd', value: 1_000 },
                    exits: { mode: 'pct', takeProfit: 1, stopLoss: 0.5 },
                    timeInForce: 'gtc',
                },
            ],
            display: { tradePaths: true },
        }),
    ],
});

Options

OptionDefaultDescription
brokerPaperBroker instanceBroker adapter used for account state and order execution.
paperSee aboveConfiguration for the built-in PaperBroker. Ignored when broker is provided.
defaultQty1Initial order quantity used on charts.
qtyPresets[1, 2, 5, 10, 25, 50, 100]Quick-select quantity values shown in quantity pickers.
displaySee belowInitial chart overlay visibility and color overrides.
safetyAll disabledInitial pre-trade safety settings (askBeforePlacing, killSwitch, and limits).
presetsNoneInitial order ticket presets (up to 9).
orderPaneltrueRegisters the order ticket side panel. Pass { width, order } (defaults 400 and 2) to customize layout, or false to disable the side panel and manage orders directly on the chart.
tradingPaneltrueRegisters the trading panel in the bottom dock. Pass { order } (default 10) to change its sort position, or false to disable it.
contextMenutrueAdds buy and sell actions at the pointer price in the chart right-click menu.
shortcutstrueEnables trading keyboard shortcuts.
phoneSheettrueDisplays the mobile Trade button and bottom sheet on compact viewports.

display, safety, presets, and defaultQty act as initial defaults. When workspace persistence is enabled, user changes are saved in the workspace state document and take precedence on reload. For display, only individual properties changed by the user are persisted, so untouched display properties continue to reflect your configured options.

Display settings

SettingDefaultDescription
visibletrueMaster toggle for the chart trading overlay layer.
orders, positionstrueToggles working order lines and open position lines on the chart.
executionstrueRenders fill markers on bars. clusterExecutions (default true) groups fills occurring at the same bar and side.
tradePathsfalseDraws connecting lines from entry to exit for closed trades.
zones'never'Controls shaded risk/reward zones between an entry and its bracket exits ('always', 'hover', or 'never').
pnl, quantitytrueDisplays unrealized PnL and size on chart order and position labels.
labels'right'Horizontal alignment of chart trading labels ('right' or 'left').
buttonstrueDisplays the floating Buy/Sell card on charts. spread (default true) shows the bid-ask spread inside the card.
oneClickfalseSubmits Buy/Sell button orders immediately when true, or stages a draft in the order panel when false.
lineWidth1Stroke width of order and position lines in pixels (1 to 4).
colorsChart bullish/bearish paletteCustom color overrides for buy, sell, takeProfit, stopLoss, profit, and loss.

Controller API

tradingController() returns the TradingController instance after enableVelaPro() installs the module, or null beforehand.

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

const account = tradingController();
if (account) {
    // Stage a bracket limit order and submit it through the user's safety checks
    // (kill switch, risk limits, and optional confirmation dialog).
    account.openDraft({
        symbol: 'BTCUSDT',
        side: 'buy',
        type: 'limit',
        qty: 0.1,
        price: 60_000,
        takeProfit: 63_000,
        stopLoss: 58_500,
    });
    const placed = await account.submitDraft(); // false when refused or canceled
    console.info(placed ? 'Order sent' : 'Order not sent');

    // Read account state initially and subscribe to broker updates.
    const report = (): void => {
        const { account: summary, positions, orders } = account.state();
        console.info(summary.equity, positions, orders);
    };
    report();
    account.onChange((what) => {
        if (what === 'broker') report();
    });

    // Listen for human-readable rejection or validation errors.
    account.onError((message) => console.warn(message));
}
MemberDescription
state()Returns the current BrokerState (account, positions, orders, history, fills, trades).
trade(symbol, side, opts?)Executes the standard Buy/Sell workflow at market or at opts.price, staging a draft in the order panel or submitting immediately when oneClick is active.
openDraft(draft), setDraft(patch), submitDraft(), discardDraft()Manages the staged draft order previewed on the chart and in the order ticket. Read the active draft via draft.
cancelOrder(id), cancelAll(symbol?)Cancels a single order by ID or all working orders (optionally scoped to symbol).
closePosition(symbol, qty?), reversePosition(symbol)Closes a full or partial position at market, or reverses its direction.
flatten(symbol)Cancels all working orders for symbol and closes its open position.
breakEven(symbol)Moves an existing stop-loss for symbol to its average entry price, or places a new stop there.
setRiskLimits(limits), setKillSwitch(on), setAskBeforePlacing(on)Updates pre-trade safety settings. Read current values via safety.
setDisplay(patch)Updates chart overlay display settings. Read current values via display.
setPresets(list), applyPreset(id, symbol)Replaces saved order presets or applies a preset by ID. Read current presets via presets.
onChange(listener)Subscribes to state changes ('broker', 'draft', 'display', 'price', 'selection', 'qty', 'safety', or 'presets').
onError(listener)Subscribes to order rejection and validation messages.
brokerUnderlying Broker instance.

Action methods return a Promise<boolean> that resolves to true when accepted by the broker and false when blocked or rejected. Orders submitted through TradingController pass through all client-side safety controls, whereas calling account.broker.placeOrder(...) directly bypasses them.

Widgets

Both the order ticket and the trading account panel can be mounted outside a workspace as standalone widgets (see Standalone widgets). Both factories read controller once on creation and accept updated values for the remaining props via update(props).

createOrderTicket(props) creates the order ticket widget.

PropDescription
controllerRequired. TradingController managing draft orders and execution.
symbolActive symbol for staging new orders.
hostPortal container for confirmation dialogs and menus. Defaults to the widget's root element.
activeControls draft lifecycle. When true, maintains a draft on symbol; when false, clears the draft.
onDiscardCallback invoked when the draft is dismissed from the chart so host UI can close its ticket container.
onNotifyCallback invoked with (message, kind) for status feedback.

createTradingPanel(props) creates the positions, orders, and history table widget.

PropDescription
controllerRequired. TradingController providing account state.
symbolCurrently viewed symbol. Clicking a different symbol in the table triggers onSelectSymbol.
hostPortal container for menus. Defaults to the widget's root element.
iconsAccessor returning a symbol icon source (() => chart.data or any object implementing symbolIcon(symbol)).
activeControls rendering updates. When false, DOM updates are paused while hidden.
onSelectSymbolCallback invoked when the user clicks a position or order symbol.
onNotifyCallback invoked with (message, kind) for status feedback.
onSettingsChangeCallback invoked when the user changes a display preference.
onCloseCallback invoked by the panel's close button (rendered only when provided).
onCountCallback invoked with the combined count of open positions and working orders for updating a custom badge.

When running outside a workspace, forward live prices to the controller with controller.notePrice(symbol, price, time) so positions mark to market and PaperBroker orders can fill.

Keyboard shortcuts

KeysAction
Shift+BBuy the active chart's symbol (stages a draft in the order panel, or submits immediately when oneClick is enabled)
Shift+SSell the active chart's symbol using the same workflow
Shift+1 to Shift+9Apply the corresponding numbered order preset

Keyboard shortcuts are ignored when focus is inside a text input. On pages with multiple workspaces, shortcuts route first to the focused workspace, otherwise to the workspace under the pointer, then to the most recently interacted workspace, and finally to the first workspace in the document. Pass shortcuts: false to disable them.

On this page