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

Orders, positions, and brackets

Reference for the Trading module's domain model, including order types, lifecycle states, bracket exits, sizing modes, positions, fills, and risk limits.

View as Markdown

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 for implementing the Broker interface with them.

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.

FieldValuesDescription
side'buy', 'sell'Order direction.
type'market', 'limit', 'stop', 'stop-limit'Execution mechanism.
qty, filledQtynumberTotal ordered quantity and cumulative filled quantity.
limitPricenumberLimit execution price for 'limit' and 'stop-limit' orders.
stopPricenumberTrigger price for 'stop' and 'stop-limit' orders.
avgFillPricenumber (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

timeInForceUI labelValidity rule
'gtc'Good till canceledRemains working until explicitly canceled
'day'DayRemains working until the end of the trading session
'ioc'Immediate or cancelFills available liquidity immediately and cancels any unfilled remainder
'fok'Fill or killFills the entire quantity immediately or cancels the entire order
'opg'At the openExecutes only in the opening auction
'cls'At the closeExecutes only in the closing auction
FlagDescription
postOnlyRejects or cancels a limit order if it would match immediately as a liquidity taker.
extendedHoursAllows execution outside regular trading hours.
reduceOnlyRestricts 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). 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

statusDescriptionTerminal
'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

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

roleDescription
'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:

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:

OrdersidetypePrice fieldstatusroleparentId
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

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 modeOffset unitResolved price for a 0.5-unit buy at 60,000 (tick 0.1, ATR 800)
'price'Absolute price levelExact value entered
'pct'Percentage of entry price1 resolves to 60,600 (take profit) or 59,400 (stop loss)
'ticks'Number of minimum price ticks500 resolves to 60,050 or 59,950
'atr'Multiple of 14-bar Average True Range on the chart timeframe1.5 resolves to 61,200 or 58,800
'usd'Target currency gain or loss across the entire order quantity300 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

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

Size modeInput meaningDerived unit quantity
'units'Base units of the symbolInput value directly
'usd'Notional currency valuevalue / entryPrice
'equity'Percentage of account equity(equity * value / 100) / entryPrice
'risk'Currency amount risked if the stop loss fillsvalue / 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

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

FieldDescription
symbolSymbol identifier matching the chart's spelling.
qtySigned net quantity (positive for long, negative for short).
avgPriceVolume-weighted average entry price.
realizedPnlCumulative PnL realized from partial reductions since the position opened.
markPrice, unrealizedPnlOptional mark price and open PnL at that mark.
openedAtPosition 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

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

Fill fieldDescription
id, orderIdUnique fill ID and parent order ID.
symbol, side, qty, price, timeExecuted instrument, direction, quantity, price, and epoch-ms timestamp.
effect'open' when opening or increasing exposure, 'close' when reducing or closing exposure.
realizedPnl, commissionOptional realized PnL (for closing fills) and execution commission.
ClosedTrade fieldDescription
id, symbolUnique trade ID and symbol.
sidePosition direction ('long' or 'short').
qty, entryPrice, exitPriceClosed quantity and entry/exit prices.
entryTime, exitTimeEntry and exit timestamps in epoch milliseconds.
pnlNet 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 module, while trades populate the Trades tab of the trading panel, draw chart trade paths, and feed the maxDailyLoss risk check.

Account summary

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

FieldDescription
currencyAccount denomination currency code (for example, 'USD').
balanceSettled cash balance including realized PnL.
equityTotal account value (balance plus open unrealizedPnl).
unrealizedPnl, realizedPnlAggregate open PnL and session/account realized PnL.
initialBalanceOptional 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

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

CapabilityTypeUI behavior
timeInForceTimeInForce[] (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.
postOnlybooleanShows the Post-only checkbox on limit orders when true.
extendedHoursbooleanPermits 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

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.

LimitCondition that blocks an opening order
maxOrderQtyOrder quantity exceeds this unit threshold.
maxOrderValueOrder notional (qty * price) exceeds this amount in account currency.
maxPositionValueResulting position notional would exceed this amount.
maxOpenOrdersResting order count is already at or above this limit.
maxDailyLossCumulative 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.

On this page