# Overview (/vela-pro/modules/trading/overview)



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](/vela-pro/get-started/setup) for adding `@luxalgo/vela-pro-trading` to your project, then pass `trading()` in the `plugins` array of `enableVelaPro()`:

```ts
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,
});
```

<Note>
  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.
</Note>

## The paper broker [#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:

| Option           | Default            | Description                                                                                  |
| ---------------- | ------------------ | -------------------------------------------------------------------------------------------- |
| `initialBalance` | `100000`           | Starting cash balance for the initial paper account.                                         |
| `currency`       | `'USD'`            | Account currency code for the initial paper account.                                         |
| `commissionRate` | `0`                | Execution 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](/vela-pro/modules/trading/broker).

## Configuration [#configuration]

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

| Option         | Default                      | Description                                                                                                                                                                                |
| -------------- | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `broker`       | `PaperBroker` instance       | `Broker` adapter used for account state and order execution.                                                                                                                               |
| `paper`        | See above                    | Configuration for the built-in `PaperBroker`. Ignored when `broker` is provided.                                                                                                           |
| `defaultQty`   | `1`                          | Initial order quantity used on charts.                                                                                                                                                     |
| `qtyPresets`   | `[1, 2, 5, 10, 25, 50, 100]` | Quick-select quantity values shown in quantity pickers.                                                                                                                                    |
| `display`      | See below                    | Initial chart overlay visibility and color overrides.                                                                                                                                      |
| `safety`       | All disabled                 | Initial pre-trade safety settings (`askBeforePlacing`, `killSwitch`, and `limits`).                                                                                                        |
| `presets`      | None                         | Initial order ticket presets (up to 9).                                                                                                                                                    |
| `orderPanel`   | `true`                       | Registers 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. |
| `tradingPanel` | `true`                       | Registers the trading panel in the bottom dock. Pass `{ order }` (default `10`) to change its sort position, or `false` to disable it.                                                     |
| `contextMenu`  | `true`                       | Adds buy and sell actions at the pointer price in the chart right-click menu.                                                                                                              |
| `shortcuts`    | `true`                       | Enables trading keyboard shortcuts.                                                                                                                                                        |
| `phoneSheet`   | `true`                       | Displays 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 [#display-settings]

| Setting               | Default                       | Description                                                                                                         |
| --------------------- | ----------------------------- | ------------------------------------------------------------------------------------------------------------------- |
| `visible`             | `true`                        | Master toggle for the chart trading overlay layer.                                                                  |
| `orders`, `positions` | `true`                        | Toggles working order lines and open position lines on the chart.                                                   |
| `executions`          | `true`                        | Renders fill markers on bars. `clusterExecutions` (default `true`) groups fills occurring at the same bar and side. |
| `tradePaths`          | `false`                       | Draws 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`, `quantity`     | `true`                        | Displays unrealized PnL and size on chart order and position labels.                                                |
| `labels`              | `'right'`                     | Horizontal alignment of chart trading labels (`'right'` or `'left'`).                                               |
| `buttons`             | `true`                        | Displays the floating Buy/Sell card on charts. `spread` (default `true`) shows the bid-ask spread inside the card.  |
| `oneClick`            | `false`                       | Submits Buy/Sell button orders immediately when `true`, or stages a draft in the order panel when `false`.          |
| `lineWidth`           | `1`                           | Stroke width of order and position lines in pixels (`1` to `4`).                                                    |
| `colors`              | Chart bullish/bearish palette | Custom color overrides for `buy`, `sell`, `takeProfit`, `stopLoss`, `profit`, and `loss`.                           |

## Controller API [#controller-api]

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

```ts
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));
}
```

| Member                                                                   | Description                                                                                                                                                   |
| ------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `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.                                                                                                        |
| `broker`                                                                 | Underlying `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 [#widgets]

Both the order ticket and the trading account panel can be mounted outside a workspace as standalone widgets (see [Standalone widgets](/vela-pro/modules/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.

| Prop         | Description                                                                                            |
| ------------ | ------------------------------------------------------------------------------------------------------ |
| `controller` | Required. `TradingController` managing draft orders and execution.                                     |
| `symbol`     | Active symbol for staging new orders.                                                                  |
| `host`       | Portal container for confirmation dialogs and menus. Defaults to the widget's root element.            |
| `active`     | Controls draft lifecycle. When `true`, maintains a draft on `symbol`; when `false`, clears the draft.  |
| `onDiscard`  | Callback invoked when the draft is dismissed from the chart so host UI can close its ticket container. |
| `onNotify`   | Callback invoked with `(message, kind)` for status feedback.                                           |

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

| Prop               | Description                                                                                                   |
| ------------------ | ------------------------------------------------------------------------------------------------------------- |
| `controller`       | Required. `TradingController` providing account state.                                                        |
| `symbol`           | Currently viewed symbol. Clicking a different symbol in the table triggers `onSelectSymbol`.                  |
| `host`             | Portal container for menus. Defaults to the widget's root element.                                            |
| `icons`            | Accessor returning a symbol icon source (`() => chart.data` or any object implementing `symbolIcon(symbol)`). |
| `active`           | Controls rendering updates. When `false`, DOM updates are paused while hidden.                                |
| `onSelectSymbol`   | Callback invoked when the user clicks a position or order symbol.                                             |
| `onNotify`         | Callback invoked with `(message, kind)` for status feedback.                                                  |
| `onSettingsChange` | Callback invoked when the user changes a display preference.                                                  |
| `onClose`          | Callback invoked by the panel's close button (rendered only when provided).                                   |
| `onCount`          | Callback 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 [#keyboard-shortcuts]

| Keys               | Action                                                                                                               |
| ------------------ | -------------------------------------------------------------------------------------------------------------------- |
| Shift+B            | Buy the active chart's symbol (stages a draft in the order panel, or submits immediately when `oneClick` is enabled) |
| Shift+S            | Sell the active chart's symbol using the same workflow                                                               |
| Shift+1 to Shift+9 | Apply 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.

## Related [#related]

* [Orders, positions, and brackets](/vela-pro/modules/trading/trading-concepts)
* [Broker integration](/vela-pro/modules/trading/broker)
* [Journal](/vela-pro/modules/catalog/journal) and [Order book](/vela-pro/modules/catalog/order-book)
* [API reference: Trading](/vela-pro/api/trading)
