# Orders, positions, and brackets (/vela-pro/modules/trading/trading-concepts)



The Trading module models brokerage accounts with a fixed set of domain types: orders, positions, fills, closed trades, and account summaries. Chart overlays and panels render state reported in these types and translate user interactions into typed requests. This page defines every field, enum value, and calculation rule in the model.

All types on this page are exported by `@luxalgo/vela-pro-trading`. See [Broker integration](/vela-pro/modules/trading/broker) for implementing the `Broker` interface with them.

## Orders [#orders]

Each order specifies a direction, an execution type, a quantity in base units of the instrument, and the price fields required by its type.

| Field              | Values                                          | Description                                                    |
| ------------------ | ----------------------------------------------- | -------------------------------------------------------------- |
| `side`             | `'buy'`, `'sell'`                               | Order direction.                                               |
| `type`             | `'market'`, `'limit'`, `'stop'`, `'stop-limit'` | Execution mechanism.                                           |
| `qty`, `filledQty` | `number`                                        | Total ordered quantity and cumulative filled quantity.         |
| `limitPrice`       | `number`                                        | Limit execution price for `'limit'` and `'stop-limit'` orders. |
| `stopPrice`        | `number`                                        | Trigger price for `'stop'` and `'stop-limit'` orders.          |
| `avgFillPrice`     | `number` (optional)                             | Volume-weighted average price of executed fills.               |

The order ticket creates `'market'`, `'limit'`, and `'stop'` orders. If your broker reports `'stop-limit'` orders, Vela Pro renders them on the chart and in order tables like any other order, although users cannot originate new `'stop-limit'` orders from the ticket UI.

When a user selects an entry price directly on the chart right-click menu, on the DOM ladder, or by dragging a line, Vela Pro infers the order type from the latest price. A buy order at or below the last price becomes a `'limit'` order, while a buy above the last price becomes a `'stop'` order. Conversely, a sell order at or above the last price becomes a `'limit'` order, and a sell below the last price becomes a `'stop'` order.

### Time in force and flags [#time-in-force-and-flags]

| `timeInForce` | UI label            | Validity rule                                                            |
| ------------- | ------------------- | ------------------------------------------------------------------------ |
| `'gtc'`       | Good till canceled  | Remains working until explicitly canceled                                |
| `'day'`       | Day                 | Remains working until the end of the trading session                     |
| `'ioc'`       | Immediate or cancel | Fills available liquidity immediately and cancels any unfilled remainder |
| `'fok'`       | Fill or kill        | Fills the entire quantity immediately or cancels the entire order        |
| `'opg'`       | At the open         | Executes only in the opening auction                                     |
| `'cls'`       | At the close        | Executes only in the closing auction                                     |

| Flag            | Description                                                                                  |
| --------------- | -------------------------------------------------------------------------------------------- |
| `postOnly`      | Rejects or cancels a limit order if it would match immediately as a liquidity taker.         |
| `extendedHours` | Allows execution outside regular trading hours.                                              |
| `reduceOnly`    | Restricts the order to reducing an existing position without opening or increasing exposure. |

The order ticket displays the time-in-force selector and the Post-only checkbox only when the broker advertises them in its capabilities (see [Broker capabilities](#broker-capabilities)). There is no built-in UI toggle for `extendedHours`; that flag is forwarded when host code sets it on the draft order and the broker advertises `extendedHours: true`.

### Order states [#order-states]

| `status`      | Description                                                         | Terminal |
| ------------- | ------------------------------------------------------------------- | -------- |
| `'pending'`   | Submitted to the broker and awaiting acknowledgment.                | No       |
| `'working'`   | Accepted and active on the broker or venue book.                    | No       |
| `'held'`      | Contingent bracket exit waiting for its parent entry order to fill. | No       |
| `'filled'`    | Completely executed.                                                | Yes      |
| `'cancelled'` | Canceled by the user, by the broker, or by an OCO sibling fill.     | Yes      |
| `'rejected'`  | Refused by the broker (`reason` contains the rejection message).    | Yes      |

Orders progress unidirectionally through these states:

1. Newly submitted orders start as `'pending'` until acknowledged by the broker, then move to `'working'`. Brokers with synchronous acknowledgment can report orders directly as `'working'`.
2. Bracket exits attached to an unfilled entry remain `'held'` until the parent entry fills, then transition to `'working'`.
3. Active orders terminate in `'filled'`, `'cancelled'`, or `'rejected'`. Partially filled orders remain `'working'` with `filledQty` less than `qty`.

`BrokerState` separates active and terminal orders into two arrays: `orders` holds active orders (`'pending'`, `'working'`, `'held'`) and `history` holds terminal orders sorted newest first. On the chart, limit orders render as dashed lines and stop orders render as dotted lines labeled with remaining unfilled quantity, while `'pending'` and `'held'` orders render at reduced opacity.

## Exits and brackets [#exits-and-brackets]

Every order includes a `role` indicating its relationship to a position:

| `role`          | Description                                                        |
| --------------- | ------------------------------------------------------------------ |
| `'entry'`       | Opens a new position or adds to an existing position.              |
| `'take-profit'` | Closing limit order placed on the opposite side to lock in profit. |
| `'stop-loss'`   | Closing stop order placed on the opposite side to cap losses.      |
| `'exit'`        | Any other closing order, such as a market close.                   |

A bracket pairs an entry order with a take-profit order, a stop-loss order, or both. Exits are submitted to the broker in one of three patterns:

**Submitted with the entry.** The initial `OrderRequest` carries `takeProfit` and `stopLoss` price levels:

```ts
import type { OrderRequest } from '@luxalgo/vela-pro-trading';

// Buy 0.5 at 60,000 with take profit at 63,000 and stop loss at 58,500.
const request: OrderRequest = {
    symbol: 'BTCUSDT',
    side: 'buy',
    type: 'limit',
    qty: 0.5,
    limitPrice: 60_000,
    takeProfit: 63_000,
    stopLoss: 58_500,
    timeInForce: 'gtc',
};
```

Once accepted, the broker reports three separate orders in `state().orders`:

| Order       | `side`   | `type`    | Price field         | `status`    | `role`          | `parentId`     |
| ----------- | -------- | --------- | ------------------- | ----------- | --------------- | -------------- |
| Entry       | `'buy'`  | `'limit'` | `limitPrice: 60000` | `'working'` | `'entry'`       | None           |
| Take profit | `'sell'` | `'limit'` | `limitPrice: 63000` | `'held'`    | `'take-profit'` | Entry order ID |
| Stop loss   | `'sell'` | `'stop'`  | `stopPrice: 58500`  | `'held'`    | `'stop-loss'`   | Entry order ID |

Both child exits carry `reduceOnly: true` and share a common `ocoGroup` identifier so that when one exit fills, the sibling exit cancels automatically. When the parent entry fills, both exits transition to `'working'` for the filled quantity.

**Attached to a working entry.** When the user drags a take-profit or stop-loss grip from a working entry line on the chart, Vela Pro sends a separate `OrderRequest` with `parentId` set to the entry's ID and `role` set to `'take-profit'` or `'stop-loss'`.

**Attached to an open position.** When the user drags a take-profit or stop-loss grip from an open position line on the chart, Vela Pro sends a separate `OrderRequest` with `reduceOnly: true` and `role` set to `'take-profit'` or `'stop-loss'`, without a `parentId`.

When a user drags a working entry line that already has attached bracket exits, Vela Pro shifts those exit prices by the same price delta.

### Exit calculation modes [#exit-calculation-modes]

In the order ticket, users can enter take-profit and stop-loss targets either as absolute prices or as offsets from the entry price. Offsets are converted to absolute prices before `placeOrder` is called, so your broker always receives resolved price levels.

| Exit mode | Offset unit                                                   | Resolved price for a 0.5-unit buy at 60,000 (tick `0.1`, ATR `800`) |
| --------- | ------------------------------------------------------------- | ------------------------------------------------------------------- |
| `'price'` | Absolute price level                                          | Exact value entered                                                 |
| `'pct'`   | Percentage of entry price                                     | `1` resolves to `60,600` (take profit) or `59,400` (stop loss)      |
| `'ticks'` | Number of minimum price ticks                                 | `500` resolves to `60,050` or `59,950`                              |
| `'atr'`   | Multiple of 14-bar Average True Range on the chart timeframe  | `1.5` resolves to `61,200` or `58,800`                              |
| `'usd'`   | Target currency gain or loss across the entire order quantity | `300` resolves to `60,600` or `59,400`                              |

Take-profit levels sit above long entries and below short entries, while stop-loss levels sit on the opposite side. For market order drafts, offset-based exit prices update dynamically with live ticks until the order is submitted.

## Order sizing [#order-sizing]

The order ticket supports four position-sizing modes. Non-unit modes are converted into base instrument units before `placeOrder` is invoked.

| Size mode  | Input meaning                                 | Derived unit quantity                     |
| ---------- | --------------------------------------------- | ----------------------------------------- |
| `'units'`  | Base units of the symbol                      | Input value directly                      |
| `'usd'`    | Notional currency value                       | `value / entryPrice`                      |
| `'equity'` | Percentage of account equity                  | `(equity * value / 100) / entryPrice`     |
| `'risk'`   | Currency amount risked if the stop loss fills | `value / Math.abs(entryPrice - stopLoss)` |

Derived quantities are rounded to four significant figures. On an account with `25,000` equity entering at `60,000`, `'usd'` `1,000` yields `0.01667` units, `'equity'` `2` yields `0.008333` units, and `'risk'` `100` with a stop loss at `58,500` yields `0.06667` units. Sizing in `'risk'` mode requires an active stop-loss price distinct from the entry price.

## Positions [#positions]

A `Position` represents the net open exposure in a single symbol.

| Field                        | Description                                                                |
| ---------------------------- | -------------------------------------------------------------------------- |
| `symbol`                     | Symbol identifier matching the chart's spelling.                           |
| `qty`                        | Signed net quantity (positive for long, negative for short).               |
| `avgPrice`                   | Volume-weighted average entry price.                                       |
| `realizedPnl`                | Cumulative PnL realized from partial reductions since the position opened. |
| `markPrice`, `unrealizedPnl` | Optional mark price and open PnL at that mark.                             |
| `openedAt`                   | Position opening timestamp in epoch milliseconds.                          |

Vela Pro expects at most one `Position` per symbol in `state().positions`. Brokers that maintain hedged or individual lot sub-positions must aggregate them into a single net position per symbol when building `BrokerState`.

Standard position-netting behavior (used by `PaperBroker` and typical net-position brokers) follows four rules:

* A fill in the same direction increases position size and recalculates `avgPrice` as a weighted average.
* A fill in the opposite direction reduces position size and realizes `(fillPrice - avgPrice) * closedQty`, signed according to position direction.
* An opposite-side fill larger than the open position closes the existing position and opens a new position in the opposite direction at `fillPrice`.
* Once `qty` reaches zero, the symbol is removed from `positions`.

## Fills and closed trades [#fills-and-closed-trades]

A `Fill` represents an individual trade execution, while a `ClosedTrade` represents a completed round-trip trade.

| `Fill` field                             | Description                                                                                |
| ---------------------------------------- | ------------------------------------------------------------------------------------------ |
| `id`, `orderId`                          | Unique fill ID and parent order ID.                                                        |
| `symbol`, `side`, `qty`, `price`, `time` | Executed instrument, direction, quantity, price, and epoch-ms timestamp.                   |
| `effect`                                 | `'open'` when opening or increasing exposure, `'close'` when reducing or closing exposure. |
| `realizedPnl`, `commission`              | Optional realized PnL (for closing fills) and execution commission.                        |

| `ClosedTrade` field              | Description                                      |
| -------------------------------- | ------------------------------------------------ |
| `id`, `symbol`                   | Unique trade ID and symbol.                      |
| `side`                           | Position direction (`'long'` or `'short'`).      |
| `qty`, `entryPrice`, `exitPrice` | Closed quantity and entry/exit prices.           |
| `entryTime`, `exitTime`          | Entry and exit timestamps in epoch milliseconds. |
| `pnl`                            | Net realized profit or loss for the round trip.  |

Both `fills` and `trades` are ordered newest first. `fills` power chart execution arrows and synchronize into the [Journal](/vela-pro/modules/catalog/journal) module, while `trades` populate the Trades tab of the trading panel, draw chart trade paths, and feed the `maxDailyLoss` risk check.

## Account summary [#account-summary]

`AccountSummary` provides top-level balance and equity metrics displayed in the trading panel header.

| Field                          | Description                                                          |
| ------------------------------ | -------------------------------------------------------------------- |
| `currency`                     | Account denomination currency code (for example, `'USD'`).           |
| `balance`                      | Settled cash balance including realized PnL.                         |
| `equity`                       | Total account value (`balance` plus open `unrealizedPnl`).           |
| `unrealizedPnl`, `realizedPnl` | Aggregate open PnL and session/account realized PnL.                 |
| `initialBalance`               | Optional starting balance used to compute percentage return metrics. |

Brokers that support multiple sub-accounts can implement `accounts` (`BrokerAccounts`), which turns the account title in the trading panel into an account switcher menu. Each `BrokerAccount` entry carries `id`, `name`, and optional `paper`, `currency`, and `initialBalance` fields. Only one account is active at a time; switching accounts updates `broker.info` and `broker.state()` to reflect the newly selected account.

## Broker capabilities [#broker-capabilities]

`BrokerCapabilities` declares which order features your broker supports. Three capability fields directly control order ticket inputs:

| Capability      | Type                            | UI behavior                                                                                                                                        |
| --------------- | ------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |
| `timeInForce`   | `TimeInForce[]` (default first) | Renders the Time in Force dropdown when two or more values are listed, defaulting new drafts to the first entry and never sending unlisted values. |
| `postOnly`      | `boolean`                       | Shows the Post-only checkbox on limit orders when `true`.                                                                                          |
| `extendedHours` | `boolean`                       | Permits `extendedHours` on outgoing `OrderRequest` payloads when `true`.                                                                           |

Additional capability fields describe supported `orderTypes`, `brackets` (native server-side bracket support), `modify` (in-place order amendment), and `reverse`. Populate them accurately for your venue. Note that the Reverse position button is gated by the presence of the `broker.reversePosition` method on the `Broker` object; when `reversePosition` is omitted, Reverse controls are hidden regardless of `capabilities.reverse`.

## Risk limits and kill switch [#risk-limits-and-kill-switch]

Pre-trade safety settings are configured by the user and evaluated client-side before requests reach your `Broker`. Always enforce authoritative margin and risk validation on your backend as well.

**Risk limits** block orders that open or increase exposure beyond configured thresholds. Reduce-only and position-closing orders are never blocked by risk limits.

| Limit              | Condition that blocks an opening order                                                                 |
| ------------------ | ------------------------------------------------------------------------------------------------------ |
| `maxOrderQty`      | Order quantity exceeds this unit threshold.                                                            |
| `maxOrderValue`    | Order notional (`qty * price`) exceeds this amount in account currency.                                |
| `maxPositionValue` | Resulting position notional would exceed this amount.                                                  |
| `maxOpenOrders`    | Resting order count is already at or above this limit.                                                 |
| `maxDailyLoss`     | Cumulative loss across `ClosedTrade` records closed since local midnight meets or exceeds this amount. |

Unset limits are inactive. Blocked orders emit an error message prefixed with `"Refused by your risk limits"`.

**Kill switch** halts order submission immediately. Activating it discards any staged draft and cancels all working orders while leaving open positions intact. While active, every new order (including closing orders) is rejected, whereas order cancellations remain allowed. Kill switch state is saved in the workspace state document across reloads. Brokers with native server-side kill switches can implement the optional `setKillSwitch(on)` method on `Broker`.

**Order confirmation (`askBeforePlacing`)** displays a confirmation dialog before submitting orders from the order ticket, amending working orders via chart drag, or dragging new exit orders from chart lines. One-click trading buttons and position close actions bypass confirmation.

## Related [#related]

* [Broker integration](/vela-pro/modules/trading/broker)
* [Trading](/vela-pro/modules/trading/overview)
* [API reference: Trading](/vela-pro/api/trading)
